1 use crate::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
2 use crate::ast::{Attribute, GenericArg, MacArgs};
3 use crate::ast::{GenericBound, SelfKind, TraitBoundModifier};
5 use crate::print::pp::Breaks::{Consistent, Inconsistent};
6 use crate::print::pp::{self, Breaks};
8 use crate::sess::ParseSess;
9 use crate::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
10 use crate::tokenstream::{self, TokenStream, TokenTree};
11 use crate::util::classify;
12 use crate::util::comments;
13 use crate::util::parser::{self, AssocOp, Fixity};
15 use rustc_span::source_map::{dummy_spanned, SourceMap, Spanned};
16 use rustc_span::symbol::{kw, sym};
17 use rustc_span::{BytePos, FileName, Span};
24 pub enum MacHeader<'a> {
26 Keyword(&'static str),
29 pub enum AnnNode<'a> {
30 Ident(&'a ast::Ident),
32 Block(&'a ast::Block),
37 Crate(&'a ast::Crate),
41 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
42 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
45 #[derive(Copy, Clone)]
48 impl PpAnn for NoAnn {}
50 pub struct Comments<'a> {
52 comments: Vec<comments::Comment>,
56 impl<'a> Comments<'a> {
63 let comments = comments::gather_comments(sess, filename, input);
64 Comments { cm, comments, current: 0 }
67 pub fn next(&self) -> Option<comments::Comment> {
68 self.comments.get(self.current).cloned()
71 pub fn trailing_comment(
73 span: rustc_span::Span,
74 next_pos: Option<BytePos>,
75 ) -> Option<comments::Comment> {
76 if let Some(cmnt) = self.next() {
77 if cmnt.style != comments::Trailing {
80 let span_line = self.cm.lookup_char_pos(span.hi());
81 let comment_line = self.cm.lookup_char_pos(cmnt.pos);
82 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
83 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
92 pub struct State<'a> {
94 comments: Option<Comments<'a>>,
95 ann: &'a (dyn PpAnn + 'a),
99 crate const INDENT_UNIT: usize = 4;
101 /// Requires you to pass an input filename and reader so that
102 /// it can scan the input text for comments to copy forward.
103 pub fn print_crate<'a>(
114 comments: Some(Comments::new(cm, sess, filename, input)),
119 if is_expanded && sess.injected_crate_name.try_get().is_some() {
120 // We need to print `#![no_std]` (and its feature gate) so that
121 // compiling pretty-printed source won't inject libstd again.
122 // However, we don't want these attributes in the AST because
123 // of the feature gate, so we fake them up here.
125 // `#![feature(prelude_import)]`
126 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_dummy_span(sym::prelude_import));
127 let list = attr::mk_list_item(ast::Ident::with_dummy_span(sym::feature), vec![pi_nested]);
128 let fake_attr = attr::mk_attr_inner(list);
129 s.print_attribute(&fake_attr);
131 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
132 // root, so this is not needed, and actually breaks things.
133 if sess.edition == rustc_span::edition::Edition::Edition2015 {
135 let no_std_meta = attr::mk_word_item(ast::Ident::with_dummy_span(sym::no_std));
136 let fake_attr = attr::mk_attr_inner(no_std_meta);
137 s.print_attribute(&fake_attr);
141 s.print_mod(&krate.module, &krate.attrs);
142 s.print_remaining_comments();
143 s.ann.post(&mut s, AnnNode::Crate(krate));
147 pub fn to_string<F>(f: F) -> String
149 F: FnOnce(&mut State<'_>),
152 State { s: pp::mk_printer(), comments: None, ann: &NoAnn, is_expanded: false };
157 // This makes comma-separated lists look slightly nicer,
158 // and also addresses a specific regression described in issue #63896.
159 fn tt_prepend_space(tt: &TokenTree) -> bool {
161 TokenTree::Token(token) => match token.kind {
162 token::Comma => false,
169 fn binop_to_string(op: BinOpToken) -> &'static str {
175 token::Percent => "%",
184 pub fn literal_to_string(lit: token::Lit) -> String {
185 let token::Lit { kind, symbol, suffix } = lit;
186 let mut out = match kind {
187 token::Byte => format!("b'{}'", symbol),
188 token::Char => format!("'{}'", symbol),
189 token::Str => format!("\"{}\"", symbol),
190 token::StrRaw(n) => {
191 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
193 token::ByteStr => format!("b\"{}\"", symbol),
194 token::ByteStrRaw(n) => {
195 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
197 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
200 if let Some(suffix) = suffix {
201 out.push_str(&suffix.as_str())
207 /// Print an ident from AST, `$crate` is converted into its respective crate name.
208 pub fn ast_ident_to_string(ident: ast::Ident, is_raw: bool) -> String {
209 ident_to_string(ident.name, is_raw, Some(ident.span))
212 // AST pretty-printer is used as a fallback for turning AST structures into token streams for
213 // proc macros. Additionally, proc macros may stringify their input and expect it survive the
214 // stringification (especially true for proc macro derives written between Rust 1.15 and 1.30).
215 // So we need to somehow pretty-print `$crate` in a way preserving at least some of its
216 // hygiene data, most importantly name of the crate it refers to.
217 // As a result we print `$crate` as `crate` if it refers to the local crate
218 // and as `::other_crate_name` if it refers to some other crate.
219 // Note, that this is only done if the ident token is printed from inside of AST pretty-pringing,
220 // but not otherwise. Pretty-printing is the only way for proc macros to discover token contents,
221 // so we should not perform this lossy conversion if the top level call to the pretty-printer was
222 // done for a token stream or a single token.
223 fn ident_to_string(name: ast::Name, is_raw: bool, convert_dollar_crate: Option<Span>) -> String {
225 format!("r#{}", name)
227 if name == kw::DollarCrate {
228 if let Some(span) = convert_dollar_crate {
229 let converted = span.ctxt().dollar_crate_name();
230 return if converted.is_path_segment_keyword() {
231 converted.to_string()
233 format!("::{}", converted)
241 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
242 pub fn token_kind_to_string(tok: &TokenKind) -> String {
243 token_kind_to_string_ext(tok, None)
246 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
248 token::Eq => "=".to_string(),
249 token::Lt => "<".to_string(),
250 token::Le => "<=".to_string(),
251 token::EqEq => "==".to_string(),
252 token::Ne => "!=".to_string(),
253 token::Ge => ">=".to_string(),
254 token::Gt => ">".to_string(),
255 token::Not => "!".to_string(),
256 token::Tilde => "~".to_string(),
257 token::OrOr => "||".to_string(),
258 token::AndAnd => "&&".to_string(),
259 token::BinOp(op) => binop_to_string(op).to_string(),
260 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
262 /* Structural symbols */
263 token::At => "@".to_string(),
264 token::Dot => ".".to_string(),
265 token::DotDot => "..".to_string(),
266 token::DotDotDot => "...".to_string(),
267 token::DotDotEq => "..=".to_string(),
268 token::Comma => ",".to_string(),
269 token::Semi => ";".to_string(),
270 token::Colon => ":".to_string(),
271 token::ModSep => "::".to_string(),
272 token::RArrow => "->".to_string(),
273 token::LArrow => "<-".to_string(),
274 token::FatArrow => "=>".to_string(),
275 token::OpenDelim(token::Paren) => "(".to_string(),
276 token::CloseDelim(token::Paren) => ")".to_string(),
277 token::OpenDelim(token::Bracket) => "[".to_string(),
278 token::CloseDelim(token::Bracket) => "]".to_string(),
279 token::OpenDelim(token::Brace) => "{".to_string(),
280 token::CloseDelim(token::Brace) => "}".to_string(),
281 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => " ".to_string(),
282 token::Pound => "#".to_string(),
283 token::Dollar => "$".to_string(),
284 token::Question => "?".to_string(),
285 token::SingleQuote => "'".to_string(),
288 token::Literal(lit) => literal_to_string(lit),
290 /* Name components */
291 token::Ident(s, is_raw) => ident_to_string(s, is_raw, convert_dollar_crate),
292 token::Lifetime(s) => s.to_string(),
295 token::DocComment(s) => s.to_string(),
296 token::Eof => "<eof>".to_string(),
297 token::Whitespace => " ".to_string(),
298 token::Comment => "/* */".to_string(),
299 token::Shebang(s) => format!("/* shebang: {}*/", s),
300 token::Unknown(s) => s.to_string(),
302 token::Interpolated(ref nt) => nonterminal_to_string(nt),
306 /// Print the token precisely, without converting `$crate` into its respective crate name.
307 pub fn token_to_string(token: &Token) -> String {
308 token_to_string_ext(token, false)
311 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
312 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
313 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
316 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
318 token::NtExpr(ref e) => expr_to_string(e),
319 token::NtMeta(ref e) => attr_item_to_string(e),
320 token::NtTy(ref e) => ty_to_string(e),
321 token::NtPath(ref e) => path_to_string(e),
322 token::NtItem(ref e) => item_to_string(e),
323 token::NtBlock(ref e) => block_to_string(e),
324 token::NtStmt(ref e) => stmt_to_string(e),
325 token::NtPat(ref e) => pat_to_string(e),
326 token::NtIdent(e, is_raw) => ast_ident_to_string(e, is_raw),
327 token::NtLifetime(e) => e.to_string(),
328 token::NtLiteral(ref e) => expr_to_string(e),
329 token::NtTT(ref tree) => tt_to_string(tree.clone()),
330 // FIXME(Centril): merge these variants.
331 token::NtImplItem(ref e) | token::NtTraitItem(ref e) => assoc_item_to_string(e),
332 token::NtVis(ref e) => vis_to_string(e),
333 token::NtForeignItem(ref e) => foreign_item_to_string(e),
337 pub fn ty_to_string(ty: &ast::Ty) -> String {
338 to_string(|s| s.print_type(ty))
341 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
342 to_string(|s| s.print_type_bounds("", bounds))
345 pub fn pat_to_string(pat: &ast::Pat) -> String {
346 to_string(|s| s.print_pat(pat))
349 pub fn expr_to_string(e: &ast::Expr) -> String {
350 to_string(|s| s.print_expr(e))
353 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
354 to_string(|s| s.print_tt(tt, false))
357 pub fn tts_to_string(tokens: TokenStream) -> String {
358 to_string(|s| s.print_tts(tokens, false))
361 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
362 to_string(|s| s.print_stmt(stmt))
365 pub fn item_to_string(i: &ast::Item) -> String {
366 to_string(|s| s.print_item(i))
369 fn assoc_item_to_string(i: &ast::AssocItem) -> String {
370 to_string(|s| s.print_assoc_item(i))
373 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
374 to_string(|s| s.print_generic_params(generic_params))
377 pub fn path_to_string(p: &ast::Path) -> String {
378 to_string(|s| s.print_path(p, false, 0))
381 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
382 to_string(|s| s.print_path_segment(p, false))
385 pub fn vis_to_string(v: &ast::Visibility) -> String {
386 to_string(|s| s.print_visibility(v))
389 fn block_to_string(blk: &ast::Block) -> String {
391 // Containing cbox, will be closed by `print_block` at `}`.
393 // Head-ibox, will be closed by `print_block` after `{`.
399 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
400 to_string(|s| s.print_meta_list_item(li))
403 fn attr_item_to_string(ai: &ast::AttrItem) -> String {
404 to_string(|s| s.print_attr_item(ai, ai.path.span))
407 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
408 to_string(|s| s.print_attribute(attr))
411 pub fn param_to_string(arg: &ast::Param) -> String {
412 to_string(|s| s.print_param(arg, false))
415 fn foreign_item_to_string(arg: &ast::ForeignItem) -> String {
416 to_string(|s| s.print_foreign_item(arg))
419 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
420 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
423 impl std::ops::Deref for State<'_> {
424 type Target = pp::Printer;
425 fn deref(&self) -> &Self::Target {
430 impl std::ops::DerefMut for State<'_> {
431 fn deref_mut(&mut self) -> &mut Self::Target {
436 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
437 fn comments(&mut self) -> &mut Option<Comments<'a>>;
438 fn print_ident(&mut self, ident: ast::Ident);
439 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
449 F: FnMut(&mut Self, &T),
452 if let Some((first, rest)) = elts.split_first() {
458 self.word_space(sep);
465 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
467 F: FnMut(&mut Self, &T),
469 self.strsep(",", false, b, elts, op)
472 fn maybe_print_comment(&mut self, pos: BytePos) {
473 while let Some(ref cmnt) = self.next_comment() {
475 self.print_comment(cmnt);
482 fn print_comment(&mut self, cmnt: &comments::Comment) {
485 assert_eq!(cmnt.lines.len(), 1);
487 self.word(cmnt.lines[0].clone());
490 comments::Isolated => {
491 self.hardbreak_if_not_bol();
492 for line in &cmnt.lines {
493 // Don't print empty lines because they will end up as trailing
495 if !line.is_empty() {
496 self.word(line.clone());
501 comments::Trailing => {
502 if !self.is_beginning_of_line() {
505 if cmnt.lines.len() == 1 {
506 self.word(cmnt.lines[0].clone());
510 for line in &cmnt.lines {
511 if !line.is_empty() {
512 self.word(line.clone());
519 comments::BlankLine => {
520 // We need to do at least one, possibly two hardbreaks.
521 let twice = match self.last_token() {
522 pp::Token::String(s) => ";" == s,
523 pp::Token::Begin(_) => true,
524 pp::Token::End => true,
533 if let Some(cm) = self.comments() {
538 fn next_comment(&mut self) -> Option<comments::Comment> {
539 self.comments().as_mut().and_then(|c| c.next())
542 fn print_literal(&mut self, lit: &ast::Lit) {
543 self.maybe_print_comment(lit.span.lo());
544 self.word(lit.token.to_string())
547 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
548 let st = match style {
549 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
550 ast::StrStyle::Raw(n) => {
552 "r{delim}\"{string}\"{delim}",
553 delim = "#".repeat(n as usize),
561 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
562 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
565 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
566 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
569 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
570 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
573 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
574 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
577 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
578 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
581 fn print_either_attributes(
583 attrs: &[ast::Attribute],
584 kind: ast::AttrStyle,
586 trailing_hardbreak: bool,
590 if attr.style == kind {
591 self.print_attribute_inline(attr, is_inline);
598 if count > 0 && trailing_hardbreak && !is_inline {
599 self.hardbreak_if_not_bol();
603 fn print_attribute(&mut self, attr: &ast::Attribute) {
604 self.print_attribute_inline(attr, false)
607 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
609 self.hardbreak_if_not_bol();
611 self.maybe_print_comment(attr.span.lo());
613 ast::AttrKind::Normal(ref item) => {
615 ast::AttrStyle::Inner => self.word("#!["),
616 ast::AttrStyle::Outer => self.word("#["),
618 self.print_attr_item(&item, attr.span);
621 ast::AttrKind::DocComment(comment) => {
622 self.word(comment.to_string());
628 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
631 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
632 Some(MacHeader::Path(&item.path)),
640 MacArgs::Empty | MacArgs::Eq(..) => {
641 self.print_path(&item.path, false, 0);
642 if let MacArgs::Eq(_, tokens) = &item.args {
644 self.word_space("=");
645 self.print_tts(tokens.clone(), true);
652 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
654 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
655 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
659 fn print_meta_item(&mut self, item: &ast::MetaItem) {
660 self.ibox(INDENT_UNIT);
662 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
663 ast::MetaItemKind::NameValue(ref value) => {
664 self.print_path(&item.path, false, 0);
666 self.word_space("=");
667 self.print_literal(value);
669 ast::MetaItemKind::List(ref items) => {
670 self.print_path(&item.path, false, 0);
672 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
679 /// This doesn't deserve to be called "pretty" printing, but it should be
680 /// meaning-preserving. A quick hack that might help would be to look at the
681 /// spans embedded in the TTs to decide where to put spaces and newlines.
682 /// But it'd be better to parse these according to the grammar of the
683 /// appropriate macro, transcribe back into the grammar we just parsed from,
684 /// and then pretty-print the resulting AST nodes (so, e.g., we print
685 /// expression arguments as expressions). It can be done! I think.
686 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
688 TokenTree::Token(ref token) => {
689 self.word(token_to_string_ext(&token, convert_dollar_crate));
691 token::DocComment(..) => self.hardbreak(),
695 TokenTree::Delimited(dspan, delim, tts) => {
696 self.print_mac_common(
702 convert_dollar_crate,
709 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
710 for (i, tt) in tts.into_trees().enumerate() {
711 if i != 0 && tt_prepend_space(&tt) {
714 self.print_tt(tt, convert_dollar_crate);
720 header: Option<MacHeader<'_>>,
722 ident: Option<ast::Ident>,
725 convert_dollar_crate: bool,
728 if delim == DelimToken::Brace {
729 self.cbox(INDENT_UNIT);
732 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
733 Some(MacHeader::Keyword(kw)) => self.word(kw),
739 if let Some(ident) = ident {
741 self.print_ident(ident);
744 DelimToken::Brace => {
745 if header.is_some() || has_bang || ident.is_some() {
753 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
756 self.print_tts(tts, convert_dollar_crate);
759 DelimToken::Brace => self.bclose(span),
760 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
764 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
765 self.maybe_print_comment(path.span.lo());
767 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
771 self.print_path_segment(segment, colons_before_params);
775 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
776 if segment.ident.name != kw::PathRoot {
777 self.print_ident(segment.ident);
778 if let Some(ref args) = segment.args {
779 self.print_generic_args(args, colons_before_params);
784 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
786 // Outer-box is consistent.
787 self.cbox(INDENT_UNIT);
788 // Head-box is inconsistent.
789 self.ibox(w.len() + 1);
790 // Keyword that starts the head.
796 fn bopen(&mut self) {
798 self.end(); // Close the head-box.
801 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
802 self.maybe_print_comment(span.hi());
803 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
806 self.end(); // Close the outer-box.
810 fn bclose(&mut self, span: rustc_span::Span) {
811 self.bclose_maybe_open(span, true)
814 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
815 if !self.is_beginning_of_line() {
816 self.break_offset(n, off)
818 if off != 0 && self.last_token().is_hardbreak_tok() {
819 // We do something pretty sketchy here: tuck the nonzero
820 // offset-adjustment we were going to deposit along with the
821 // break into the previous hardbreak.
822 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
828 impl<'a> PrintState<'a> for State<'a> {
829 fn comments(&mut self) -> &mut Option<Comments<'a>> {
833 fn print_ident(&mut self, ident: ast::Ident) {
834 self.s.word(ast_ident_to_string(ident, ident.is_raw_guess()));
835 self.ann.post(self, AnnNode::Ident(&ident))
838 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
839 if colons_before_params {
844 ast::GenericArgs::AngleBracketed(ref data) => {
847 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
848 s.print_generic_arg(generic_arg)
851 let mut comma = data.args.len() != 0;
853 for constraint in data.constraints.iter() {
857 self.print_ident(constraint.ident);
859 match constraint.kind {
860 ast::AssocTyConstraintKind::Equality { ref ty } => {
861 self.word_space("=");
864 ast::AssocTyConstraintKind::Bound { ref bounds } => {
865 self.print_type_bounds(":", &*bounds);
874 ast::GenericArgs::Parenthesized(ref data) => {
876 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
878 self.print_fn_ret_ty(&data.output);
885 // Synthesizes a comment that was not textually present in the original source
887 pub fn synth_comment(&mut self, text: String) {
895 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
897 F: FnMut(&mut State<'_>, &T),
898 G: FnMut(&T) -> rustc_span::Span,
901 let len = elts.len();
904 self.maybe_print_comment(get_span(elt).hi());
909 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
910 self.space_if_not_bol();
916 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
917 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
920 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
921 self.print_inner_attributes(attrs);
922 for item in &_mod.items {
923 self.print_item(item);
927 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[ast::Attribute]) {
928 self.print_inner_attributes(attrs);
929 for item in &nmod.items {
930 self.print_foreign_item(item);
934 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
935 if let Some(lt) = *lifetime {
936 self.print_lifetime(lt);
941 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
943 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
944 GenericArg::Type(ty) => self.print_type(ty),
945 GenericArg::Const(ct) => self.print_expr(&ct.value),
949 pub fn print_type(&mut self, ty: &ast::Ty) {
950 self.maybe_print_comment(ty.span.lo());
953 ast::TyKind::Slice(ref ty) => {
958 ast::TyKind::Ptr(ref mt) => {
960 self.print_mt(mt, true);
962 ast::TyKind::Rptr(ref lifetime, ref mt) => {
964 self.print_opt_lifetime(lifetime);
965 self.print_mt(mt, false);
967 ast::TyKind::Never => {
970 ast::TyKind::Tup(ref elts) => {
972 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
978 ast::TyKind::Paren(ref typ) => {
980 self.print_type(typ);
983 ast::TyKind::BareFn(ref f) => {
984 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
986 ast::TyKind::Path(None, ref path) => {
987 self.print_path(path, false, 0);
989 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
990 ast::TyKind::TraitObject(ref bounds, syntax) => {
991 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
992 self.print_type_bounds(prefix, &bounds[..]);
994 ast::TyKind::ImplTrait(_, ref bounds) => {
995 self.print_type_bounds("impl", &bounds[..]);
997 ast::TyKind::Array(ref ty, ref length) => {
1001 self.print_expr(&length.value);
1004 ast::TyKind::Typeof(ref e) => {
1005 self.s.word("typeof(");
1006 self.print_expr(&e.value);
1009 ast::TyKind::Infer => {
1012 ast::TyKind::Err => {
1014 self.s.word("/*ERROR*/");
1017 ast::TyKind::ImplicitSelf => {
1018 self.s.word("Self");
1020 ast::TyKind::Mac(ref m) => {
1023 ast::TyKind::CVarArgs => {
1030 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
1031 self.hardbreak_if_not_bol();
1032 self.maybe_print_comment(item.span.lo());
1033 self.print_outer_attributes(&item.attrs);
1035 ast::ForeignItemKind::Fn(ref decl, ref generics) => {
1039 ast::FnHeader::default(),
1044 self.end(); // end head-ibox
1046 self.end(); // end the outer fn box
1048 ast::ForeignItemKind::Static(ref t, m) => {
1049 self.head(visibility_qualified(&item.vis, "static"));
1050 if m == ast::Mutability::Mut {
1051 self.word_space("mut");
1053 self.print_ident(item.ident);
1054 self.word_space(":");
1057 self.end(); // end the head-ibox
1058 self.end(); // end the outer cbox
1060 ast::ForeignItemKind::Ty => {
1061 self.head(visibility_qualified(&item.vis, "type"));
1062 self.print_ident(item.ident);
1064 self.end(); // end the head-ibox
1065 self.end(); // end the outer cbox
1067 ast::ForeignItemKind::Macro(ref m) => {
1069 if m.args.need_semicolon() {
1076 fn print_associated_const(
1080 default: Option<&ast::Expr>,
1081 vis: &ast::Visibility,
1083 self.s.word(visibility_qualified(vis, ""));
1084 self.word_space("const");
1085 self.print_ident(ident);
1086 self.word_space(":");
1087 self.print_type(ty);
1088 if let Some(expr) = default {
1090 self.word_space("=");
1091 self.print_expr(expr);
1096 fn print_associated_type(
1099 bounds: &ast::GenericBounds,
1100 ty: Option<&ast::Ty>,
1102 self.word_space("type");
1103 self.print_ident(ident);
1104 self.print_type_bounds(":", bounds);
1105 if let Some(ty) = ty {
1107 self.word_space("=");
1108 self.print_type(ty);
1113 /// Pretty-prints an item.
1114 crate fn print_item(&mut self, item: &ast::Item) {
1115 self.hardbreak_if_not_bol();
1116 self.maybe_print_comment(item.span.lo());
1117 self.print_outer_attributes(&item.attrs);
1118 self.ann.pre(self, AnnNode::Item(item));
1120 ast::ItemKind::ExternCrate(orig_name) => {
1121 self.head(visibility_qualified(&item.vis, "extern crate"));
1122 if let Some(orig_name) = orig_name {
1123 self.print_name(orig_name);
1128 self.print_ident(item.ident);
1130 self.end(); // end inner head-block
1131 self.end(); // end outer head-block
1133 ast::ItemKind::Use(ref tree) => {
1134 self.head(visibility_qualified(&item.vis, "use"));
1135 self.print_use_tree(tree);
1137 self.end(); // end inner head-block
1138 self.end(); // end outer head-block
1140 ast::ItemKind::Static(ref ty, m, ref expr) => {
1141 self.head(visibility_qualified(&item.vis, "static"));
1142 if m == ast::Mutability::Mut {
1143 self.word_space("mut");
1145 self.print_ident(item.ident);
1146 self.word_space(":");
1147 self.print_type(ty);
1149 self.end(); // end the head-ibox
1151 self.word_space("=");
1152 self.print_expr(expr);
1154 self.end(); // end the outer cbox
1156 ast::ItemKind::Const(ref ty, ref expr) => {
1157 self.head(visibility_qualified(&item.vis, "const"));
1158 self.print_ident(item.ident);
1159 self.word_space(":");
1160 self.print_type(ty);
1162 self.end(); // end the head-ibox
1164 self.word_space("=");
1165 self.print_expr(expr);
1167 self.end(); // end the outer cbox
1169 ast::ItemKind::Fn(ref sig, ref param_names, ref body) => {
1171 self.print_fn(&sig.decl, sig.header, Some(item.ident), param_names, &item.vis);
1173 self.print_block_with_attrs(body, &item.attrs);
1175 ast::ItemKind::Mod(ref _mod) => {
1176 self.head(visibility_qualified(&item.vis, "mod"));
1177 self.print_ident(item.ident);
1179 if _mod.inline || self.is_expanded {
1182 self.print_mod(_mod, &item.attrs);
1183 self.bclose(item.span);
1186 self.end(); // end inner head-block
1187 self.end(); // end outer head-block
1190 ast::ItemKind::ForeignMod(ref nmod) => {
1191 self.head("extern");
1192 if let Some(abi) = nmod.abi {
1193 self.print_literal(&abi.as_lit());
1197 self.print_foreign_mod(nmod, &item.attrs);
1198 self.bclose(item.span);
1200 ast::ItemKind::GlobalAsm(ref ga) => {
1201 self.head(visibility_qualified(&item.vis, "global_asm!"));
1202 self.s.word(ga.asm.to_string());
1205 ast::ItemKind::TyAlias(ref ty, ref generics) => {
1206 self.head(visibility_qualified(&item.vis, "type"));
1207 self.print_ident(item.ident);
1208 self.print_generic_params(&generics.params);
1209 self.end(); // end the inner ibox
1211 self.print_where_clause(&generics.where_clause);
1213 self.word_space("=");
1214 self.print_type(ty);
1216 self.end(); // end the outer ibox
1218 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1219 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1221 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1222 self.head(visibility_qualified(&item.vis, "struct"));
1223 self.print_struct(struct_def, generics, item.ident, item.span, true);
1225 ast::ItemKind::Union(ref struct_def, ref generics) => {
1226 self.head(visibility_qualified(&item.vis, "union"));
1227 self.print_struct(struct_def, generics, item.ident, item.span, true);
1229 ast::ItemKind::Impl {
1240 self.print_visibility(&item.vis);
1241 self.print_defaultness(defaultness);
1242 self.print_unsafety(unsafety);
1243 self.word_nbsp("impl");
1244 self.print_constness(constness);
1246 if !generics.params.is_empty() {
1247 self.print_generic_params(&generics.params);
1251 if polarity == ast::ImplPolarity::Negative {
1255 if let Some(ref t) = *of_trait {
1256 self.print_trait_ref(t);
1258 self.word_space("for");
1261 self.print_type(self_ty);
1262 self.print_where_clause(&generics.where_clause);
1266 self.print_inner_attributes(&item.attrs);
1267 for impl_item in items {
1268 self.print_assoc_item(impl_item);
1270 self.bclose(item.span);
1272 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1274 self.print_visibility(&item.vis);
1275 self.print_unsafety(unsafety);
1276 self.print_is_auto(is_auto);
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 for b in bounds.iter() {
1282 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1284 self.word_space("for ?");
1285 self.print_trait_ref(&ptr.trait_ref);
1287 real_bounds.push(b.clone());
1290 self.print_type_bounds(":", &real_bounds[..]);
1291 self.print_where_clause(&generics.where_clause);
1294 for trait_item in trait_items {
1295 self.print_assoc_item(trait_item);
1297 self.bclose(item.span);
1299 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1301 self.print_visibility(&item.vis);
1302 self.word_nbsp("trait");
1303 self.print_ident(item.ident);
1304 self.print_generic_params(&generics.params);
1305 let mut real_bounds = Vec::with_capacity(bounds.len());
1306 // FIXME(durka) this seems to be some quite outdated syntax
1307 for b in bounds.iter() {
1308 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1310 self.word_space("for ?");
1311 self.print_trait_ref(&ptr.trait_ref);
1313 real_bounds.push(b.clone());
1317 self.print_type_bounds("=", &real_bounds[..]);
1318 self.print_where_clause(&generics.where_clause);
1321 ast::ItemKind::Mac(ref mac) => {
1322 self.print_mac(mac);
1323 if mac.args.need_semicolon() {
1327 ast::ItemKind::MacroDef(ref macro_def) => {
1328 let (kw, has_bang) = if macro_def.legacy {
1329 ("macro_rules", true)
1331 self.print_visibility(&item.vis);
1334 self.print_mac_common(
1335 Some(MacHeader::Keyword(kw)),
1338 macro_def.body.delim(),
1339 macro_def.body.inner_tokens(),
1345 self.ann.post(self, AnnNode::Item(item))
1348 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1349 self.print_path(&t.path, false, 0)
1352 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1353 if !generic_params.is_empty() {
1355 self.print_generic_params(generic_params);
1360 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1361 self.print_formal_generic_params(&t.bound_generic_params);
1362 self.print_trait_ref(&t.trait_ref)
1365 crate fn print_enum_def(
1367 enum_definition: &ast::EnumDef,
1368 generics: &ast::Generics,
1370 span: rustc_span::Span,
1371 visibility: &ast::Visibility,
1373 self.head(visibility_qualified(visibility, "enum"));
1374 self.print_ident(ident);
1375 self.print_generic_params(&generics.params);
1376 self.print_where_clause(&generics.where_clause);
1378 self.print_variants(&enum_definition.variants, span)
1381 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1384 self.space_if_not_bol();
1385 self.maybe_print_comment(v.span.lo());
1386 self.print_outer_attributes(&v.attrs);
1387 self.ibox(INDENT_UNIT);
1388 self.print_variant(v);
1391 self.maybe_print_trailing_comment(v.span, None);
1396 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1398 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1399 ast::VisibilityKind::Crate(sugar) => match sugar {
1400 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1401 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1403 ast::VisibilityKind::Restricted { ref path, .. } => {
1404 let path = to_string(|s| s.print_path(path, false, 0));
1405 if path == "self" || path == "super" {
1406 self.word_nbsp(format!("pub({})", path))
1408 self.word_nbsp(format!("pub(in {})", path))
1411 ast::VisibilityKind::Inherited => {}
1415 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1416 if let ast::Defaultness::Default = defaultness {
1417 self.word_nbsp("default");
1421 crate fn print_struct(
1423 struct_def: &ast::VariantData,
1424 generics: &ast::Generics,
1426 span: rustc_span::Span,
1427 print_finalizer: bool,
1429 self.print_ident(ident);
1430 self.print_generic_params(&generics.params);
1432 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1433 if let ast::VariantData::Tuple(..) = struct_def {
1435 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1436 s.maybe_print_comment(field.span.lo());
1437 s.print_outer_attributes(&field.attrs);
1438 s.print_visibility(&field.vis);
1439 s.print_type(&field.ty)
1443 self.print_where_clause(&generics.where_clause);
1444 if print_finalizer {
1448 self.end(); // Close the outer-box.
1450 ast::VariantData::Struct(..) => {
1451 self.print_where_clause(&generics.where_clause);
1454 self.hardbreak_if_not_bol();
1456 for field in struct_def.fields() {
1457 self.hardbreak_if_not_bol();
1458 self.maybe_print_comment(field.span.lo());
1459 self.print_outer_attributes(&field.attrs);
1460 self.print_visibility(&field.vis);
1461 self.print_ident(field.ident.unwrap());
1462 self.word_nbsp(":");
1463 self.print_type(&field.ty);
1472 crate fn print_variant(&mut self, v: &ast::Variant) {
1474 self.print_visibility(&v.vis);
1475 let generics = ast::Generics::default();
1476 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1480 self.word_space("=");
1481 self.print_expr(&d.value)
1487 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1488 self.ann.pre(self, AnnNode::SubItem(item.id));
1489 self.hardbreak_if_not_bol();
1490 self.maybe_print_comment(item.span.lo());
1491 self.print_outer_attributes(&item.attrs);
1492 self.print_defaultness(item.defaultness);
1494 ast::AssocItemKind::Const(ty, expr) => {
1495 self.print_associated_const(item.ident, ty, expr.as_deref(), &item.vis);
1497 ast::AssocItemKind::Fn(sig, body) => {
1501 self.print_fn(&sig.decl, sig.header, Some(item.ident), &item.generics, &item.vis);
1502 if let Some(body) = body {
1504 self.print_block_with_attrs(body, &item.attrs);
1509 ast::AssocItemKind::TyAlias(bounds, ty) => {
1510 self.print_associated_type(item.ident, bounds, ty.as_deref());
1512 ast::AssocItemKind::Macro(mac) => {
1513 self.print_mac(mac);
1514 if mac.args.need_semicolon() {
1519 self.ann.post(self, AnnNode::SubItem(item.id))
1522 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1523 self.maybe_print_comment(st.span.lo());
1525 ast::StmtKind::Local(ref loc) => {
1526 self.print_outer_attributes(&loc.attrs);
1527 self.space_if_not_bol();
1528 self.ibox(INDENT_UNIT);
1529 self.word_nbsp("let");
1531 self.ibox(INDENT_UNIT);
1532 self.print_local_decl(loc);
1534 if let Some(ref init) = loc.init {
1536 self.word_space("=");
1537 self.print_expr(init);
1542 ast::StmtKind::Item(ref item) => self.print_item(item),
1543 ast::StmtKind::Expr(ref expr) => {
1544 self.space_if_not_bol();
1545 self.print_expr_outer_attr_style(expr, false);
1546 if classify::expr_requires_semi_to_be_stmt(expr) {
1550 ast::StmtKind::Semi(ref expr) => {
1552 // Filter out empty `Tup` exprs created for the `redundant_semicolon`
1553 // lint, as they shouldn't be visible and interact poorly
1554 // with proc macros.
1555 ast::ExprKind::Tup(ref exprs) if exprs.is_empty() && expr.attrs.is_empty() => {
1559 self.space_if_not_bol();
1560 self.print_expr_outer_attr_style(expr, false);
1565 ast::StmtKind::Mac(ref mac) => {
1566 let (ref mac, style, ref attrs) = **mac;
1567 self.space_if_not_bol();
1568 self.print_outer_attributes(attrs);
1569 self.print_mac(mac);
1570 if style == ast::MacStmtStyle::Semicolon {
1575 self.maybe_print_trailing_comment(st.span, None)
1578 crate fn print_block(&mut self, blk: &ast::Block) {
1579 self.print_block_with_attrs(blk, &[])
1582 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1583 self.print_block_maybe_unclosed(blk, &[], false)
1586 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1587 self.print_block_maybe_unclosed(blk, attrs, true)
1590 crate fn print_block_maybe_unclosed(
1593 attrs: &[ast::Attribute],
1597 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1598 BlockCheckMode::Default => (),
1600 self.maybe_print_comment(blk.span.lo());
1601 self.ann.pre(self, AnnNode::Block(blk));
1604 self.print_inner_attributes(attrs);
1606 for (i, st) in blk.stmts.iter().enumerate() {
1608 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1609 self.maybe_print_comment(st.span.lo());
1610 self.space_if_not_bol();
1611 self.print_expr_outer_attr_style(expr, false);
1612 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1614 _ => self.print_stmt(st),
1618 self.bclose_maybe_open(blk.span, close_box);
1619 self.ann.post(self, AnnNode::Block(blk))
1622 /// Print a `let pat = scrutinee` expression.
1623 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1624 self.s.word("let ");
1626 self.print_pat(pat);
1629 self.word_space("=");
1630 self.print_expr_cond_paren(
1632 Self::cond_needs_par(scrutinee)
1633 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1637 fn print_else(&mut self, els: Option<&ast::Expr>) {
1638 if let Some(_else) = els {
1640 // Another `else if` block.
1641 ast::ExprKind::If(ref i, ref then, ref e) => {
1642 self.cbox(INDENT_UNIT - 1);
1644 self.s.word(" else if ");
1645 self.print_expr_as_cond(i);
1647 self.print_block(then);
1648 self.print_else(e.as_deref())
1650 // Final `else` block.
1651 ast::ExprKind::Block(ref b, _) => {
1652 self.cbox(INDENT_UNIT - 1);
1654 self.s.word(" else ");
1657 // Constraints would be great here!
1659 panic!("print_if saw if with weird alternative");
1665 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1668 self.print_expr_as_cond(test);
1671 self.print_block(blk);
1672 self.print_else(elseopt)
1675 crate fn print_mac(&mut self, m: &ast::Mac) {
1676 self.print_mac_common(
1677 Some(MacHeader::Path(&m.path)),
1681 m.args.inner_tokens(),
1687 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1689 self.commasep_exprs(Inconsistent, args);
1693 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1694 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1697 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1698 /// `if cond { ... }`.
1699 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1700 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1703 /// Does `expr` need parenthesis when printed in a condition position?
1704 fn cond_needs_par(expr: &ast::Expr) -> bool {
1706 // These cases need parens due to the parse error observed in #26461: `if return {}`
1707 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1708 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1710 _ => parser::contains_exterior_struct_lit(expr),
1714 /// Prints `expr` or `(expr)` when `needs_par` holds.
1715 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1719 self.print_expr(expr);
1725 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1726 self.ibox(INDENT_UNIT);
1728 self.print_inner_attributes_inline(attrs);
1729 self.commasep_exprs(Inconsistent, &exprs[..]);
1734 fn print_expr_repeat(
1736 element: &ast::Expr,
1737 count: &ast::AnonConst,
1738 attrs: &[Attribute],
1740 self.ibox(INDENT_UNIT);
1742 self.print_inner_attributes_inline(attrs);
1743 self.print_expr(element);
1744 self.word_space(";");
1745 self.print_expr(&count.value);
1750 fn print_expr_struct(
1753 fields: &[ast::Field],
1754 wth: &Option<P<ast::Expr>>,
1755 attrs: &[Attribute],
1757 self.print_path(path, true, 0);
1759 self.print_inner_attributes_inline(attrs);
1764 s.ibox(INDENT_UNIT);
1765 if !field.is_shorthand {
1766 s.print_ident(field.ident);
1769 s.print_expr(&field.expr);
1776 self.ibox(INDENT_UNIT);
1777 if !fields.is_empty() {
1782 self.print_expr(expr);
1786 if !fields.is_empty() {
1794 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1796 self.print_inner_attributes_inline(attrs);
1797 self.commasep_exprs(Inconsistent, &exprs[..]);
1798 if exprs.len() == 1 {
1804 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1805 let prec = match func.kind {
1806 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1807 _ => parser::PREC_POSTFIX,
1810 self.print_expr_maybe_paren(func, prec);
1811 self.print_call_post(args)
1814 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1815 let base_args = &args[1..];
1816 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1818 self.print_ident(segment.ident);
1819 if let Some(ref args) = segment.args {
1820 self.print_generic_args(args, true);
1822 self.print_call_post(base_args)
1825 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1826 let assoc_op = AssocOp::from_ast_binop(op.node);
1827 let prec = assoc_op.precedence() as i8;
1828 let fixity = assoc_op.fixity();
1830 let (left_prec, right_prec) = match fixity {
1831 Fixity::Left => (prec, prec + 1),
1832 Fixity::Right => (prec + 1, prec),
1833 Fixity::None => (prec + 1, prec + 1),
1836 let left_prec = match (&lhs.kind, op.node) {
1837 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1838 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1839 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1840 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt)
1841 | (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1842 // We are given `(let _ = a) OP b`.
1844 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1845 // as the parser will interpret this as `(let _ = a) OP b`.
1847 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1848 // parens are required since the parser would interpret `let a = b < c` as
1849 // `let a = (b < c)`. To achieve this, we force parens.
1850 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1851 parser::PREC_FORCE_PAREN
1856 self.print_expr_maybe_paren(lhs, left_prec);
1858 self.word_space(op.node.to_string());
1859 self.print_expr_maybe_paren(rhs, right_prec)
1862 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1863 self.s.word(ast::UnOp::to_string(op));
1864 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1867 fn print_expr_addr_of(
1869 kind: ast::BorrowKind,
1870 mutability: ast::Mutability,
1875 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1876 ast::BorrowKind::Raw => {
1877 self.word_nbsp("raw");
1878 self.print_mutability(mutability, true);
1881 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1884 pub fn print_expr(&mut self, expr: &ast::Expr) {
1885 self.print_expr_outer_attr_style(expr, true)
1888 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1889 self.maybe_print_comment(expr.span.lo());
1891 let attrs = &expr.attrs;
1893 self.print_outer_attributes_inline(attrs);
1895 self.print_outer_attributes(attrs);
1898 self.ibox(INDENT_UNIT);
1899 self.ann.pre(self, AnnNode::Expr(expr));
1901 ast::ExprKind::Box(ref expr) => {
1902 self.word_space("box");
1903 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1905 ast::ExprKind::Array(ref exprs) => {
1906 self.print_expr_vec(&exprs[..], attrs);
1908 ast::ExprKind::Repeat(ref element, ref count) => {
1909 self.print_expr_repeat(element, count, attrs);
1911 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1912 self.print_expr_struct(path, &fields[..], wth, attrs);
1914 ast::ExprKind::Tup(ref exprs) => {
1915 self.print_expr_tup(&exprs[..], attrs);
1917 ast::ExprKind::Call(ref func, ref args) => {
1918 self.print_expr_call(func, &args[..]);
1920 ast::ExprKind::MethodCall(ref segment, ref args) => {
1921 self.print_expr_method_call(segment, &args[..]);
1923 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1924 self.print_expr_binary(op, lhs, rhs);
1926 ast::ExprKind::Unary(op, ref expr) => {
1927 self.print_expr_unary(op, expr);
1929 ast::ExprKind::AddrOf(k, m, ref expr) => {
1930 self.print_expr_addr_of(k, m, expr);
1932 ast::ExprKind::Lit(ref lit) => {
1933 self.print_literal(lit);
1935 ast::ExprKind::Cast(ref expr, ref ty) => {
1936 let prec = AssocOp::As.precedence() as i8;
1937 self.print_expr_maybe_paren(expr, prec);
1939 self.word_space("as");
1940 self.print_type(ty);
1942 ast::ExprKind::Type(ref expr, ref ty) => {
1943 let prec = AssocOp::Colon.precedence() as i8;
1944 self.print_expr_maybe_paren(expr, prec);
1945 self.word_space(":");
1946 self.print_type(ty);
1948 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1949 self.print_let(pat, scrutinee);
1951 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1952 self.print_if(test, blk, elseopt.as_deref())
1954 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1955 if let Some(label) = opt_label {
1956 self.print_ident(label.ident);
1957 self.word_space(":");
1960 self.print_expr_as_cond(test);
1962 self.print_block_with_attrs(blk, attrs);
1964 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1965 if let Some(label) = opt_label {
1966 self.print_ident(label.ident);
1967 self.word_space(":");
1970 self.print_pat(pat);
1972 self.word_space("in");
1973 self.print_expr_as_cond(iter);
1975 self.print_block_with_attrs(blk, attrs);
1977 ast::ExprKind::Loop(ref blk, opt_label) => {
1978 if let Some(label) = opt_label {
1979 self.print_ident(label.ident);
1980 self.word_space(":");
1984 self.print_block_with_attrs(blk, attrs);
1986 ast::ExprKind::Match(ref expr, ref arms) => {
1987 self.cbox(INDENT_UNIT);
1988 self.ibox(INDENT_UNIT);
1989 self.word_nbsp("match");
1990 self.print_expr_as_cond(expr);
1993 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1995 self.print_arm(arm);
1997 self.bclose(expr.span);
1999 ast::ExprKind::Closure(
2007 self.print_movability(movability);
2008 self.print_asyncness(asyncness);
2009 self.print_capture_clause(capture_clause);
2011 self.print_fn_params_and_ret(decl, true);
2013 self.print_expr(body);
2014 self.end(); // need to close a box
2016 // a box will be closed by print_expr, but we didn't want an overall
2017 // wrapper so we closed the corresponding opening. so create an
2018 // empty box to satisfy the close.
2021 ast::ExprKind::Block(ref blk, opt_label) => {
2022 if let Some(label) = opt_label {
2023 self.print_ident(label.ident);
2024 self.word_space(":");
2026 // containing cbox, will be closed by print-block at }
2027 self.cbox(INDENT_UNIT);
2028 // head-box, will be closed by print-block after {
2030 self.print_block_with_attrs(blk, attrs);
2032 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2033 self.word_nbsp("async");
2034 self.print_capture_clause(capture_clause);
2036 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2037 self.cbox(INDENT_UNIT);
2039 self.print_block_with_attrs(blk, attrs);
2041 ast::ExprKind::Await(ref expr) => {
2042 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2043 self.s.word(".await");
2045 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2046 let prec = AssocOp::Assign.precedence() as i8;
2047 self.print_expr_maybe_paren(lhs, prec + 1);
2049 self.word_space("=");
2050 self.print_expr_maybe_paren(rhs, prec);
2052 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2053 let prec = AssocOp::Assign.precedence() as i8;
2054 self.print_expr_maybe_paren(lhs, prec + 1);
2056 self.s.word(op.node.to_string());
2057 self.word_space("=");
2058 self.print_expr_maybe_paren(rhs, prec);
2060 ast::ExprKind::Field(ref expr, ident) => {
2061 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2063 self.print_ident(ident);
2065 ast::ExprKind::Index(ref expr, ref index) => {
2066 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2068 self.print_expr(index);
2071 ast::ExprKind::Range(ref start, ref end, limits) => {
2072 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2073 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2074 // Here we use a fake precedence value so that any child with lower precedence than
2075 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2076 let fake_prec = AssocOp::LOr.precedence() as i8;
2077 if let Some(ref e) = *start {
2078 self.print_expr_maybe_paren(e, fake_prec);
2080 if limits == ast::RangeLimits::HalfOpen {
2085 if let Some(ref e) = *end {
2086 self.print_expr_maybe_paren(e, fake_prec);
2089 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2090 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2091 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2092 self.s.word("break");
2094 if let Some(label) = opt_label {
2095 self.print_ident(label.ident);
2098 if let Some(ref expr) = *opt_expr {
2099 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2103 ast::ExprKind::Continue(opt_label) => {
2104 self.s.word("continue");
2106 if let Some(label) = opt_label {
2107 self.print_ident(label.ident);
2111 ast::ExprKind::Ret(ref result) => {
2112 self.s.word("return");
2113 if let Some(ref expr) = *result {
2115 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2118 ast::ExprKind::InlineAsm(ref a) => {
2119 self.s.word("asm!");
2121 self.print_string(&a.asm.as_str(), a.asm_str_style);
2122 self.word_space(":");
2124 self.commasep(Inconsistent, &a.outputs, |s, out| {
2125 let constraint = out.constraint.as_str();
2126 let mut ch = constraint.chars();
2128 Some('=') if out.is_rw => {
2129 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2131 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2134 s.print_expr(&out.expr);
2138 self.word_space(":");
2140 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2141 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2147 self.word_space(":");
2149 self.commasep(Inconsistent, &a.clobbers, |s, co| {
2150 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2153 let mut options = vec![];
2155 options.push("volatile");
2158 options.push("alignstack");
2160 if a.dialect == ast::AsmDialect::Intel {
2161 options.push("intel");
2164 if !options.is_empty() {
2166 self.word_space(":");
2167 self.commasep(Inconsistent, &options, |s, &co| {
2168 s.print_string(co, ast::StrStyle::Cooked);
2174 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2175 ast::ExprKind::Paren(ref e) => {
2177 self.print_inner_attributes_inline(attrs);
2181 ast::ExprKind::Yield(ref e) => {
2182 self.s.word("yield");
2186 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2191 ast::ExprKind::Try(ref e) => {
2192 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2195 ast::ExprKind::TryBlock(ref blk) => {
2198 self.print_block_with_attrs(blk, attrs)
2200 ast::ExprKind::Err => {
2202 self.s.word("/*ERROR*/");
2206 self.ann.post(self, AnnNode::Expr(expr));
2210 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2211 self.print_pat(&loc.pat);
2212 if let Some(ref ty) = loc.ty {
2213 self.word_space(":");
2214 self.print_type(ty);
2218 pub fn print_usize(&mut self, i: usize) {
2219 self.s.word(i.to_string())
2222 crate fn print_name(&mut self, name: ast::Name) {
2223 self.s.word(name.to_string());
2224 self.ann.post(self, AnnNode::Name(&name))
2227 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2229 self.print_type(&qself.ty);
2230 if qself.position > 0 {
2232 self.word_space("as");
2233 let depth = path.segments.len() - qself.position;
2234 self.print_path(path, false, depth);
2238 let item_segment = path.segments.last().unwrap();
2239 self.print_ident(item_segment.ident);
2240 match item_segment.args {
2241 Some(ref args) => self.print_generic_args(args, colons_before_params),
2246 crate fn print_pat(&mut self, pat: &ast::Pat) {
2247 self.maybe_print_comment(pat.span.lo());
2248 self.ann.pre(self, AnnNode::Pat(pat));
2249 /* Pat isn't normalized, but the beauty of it
2250 is that it doesn't matter */
2252 PatKind::Wild => self.s.word("_"),
2253 PatKind::Ident(binding_mode, ident, ref sub) => {
2254 match binding_mode {
2255 ast::BindingMode::ByRef(mutbl) => {
2256 self.word_nbsp("ref");
2257 self.print_mutability(mutbl, false);
2259 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2260 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2261 self.word_nbsp("mut");
2264 self.print_ident(ident);
2265 if let Some(ref p) = *sub {
2267 self.s.word_space("@");
2271 PatKind::TupleStruct(ref path, ref elts) => {
2272 self.print_path(path, true, 0);
2274 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2277 PatKind::Or(ref pats) => {
2278 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2280 PatKind::Path(None, ref path) => {
2281 self.print_path(path, true, 0);
2283 PatKind::Path(Some(ref qself), ref path) => {
2284 self.print_qpath(path, qself, false);
2286 PatKind::Struct(ref path, ref fields, etc) => {
2287 self.print_path(path, true, 0);
2289 self.word_space("{");
2294 s.cbox(INDENT_UNIT);
2295 if !f.is_shorthand {
2296 s.print_ident(f.ident);
2299 s.print_pat(&f.pat);
2305 if !fields.is_empty() {
2306 self.word_space(",");
2313 PatKind::Tuple(ref elts) => {
2315 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2316 if elts.len() == 1 {
2321 PatKind::Box(ref inner) => {
2322 self.s.word("box ");
2323 self.print_pat(inner);
2325 PatKind::Ref(ref inner, mutbl) => {
2327 if mutbl == ast::Mutability::Mut {
2328 self.s.word("mut ");
2330 self.print_pat(inner);
2332 PatKind::Lit(ref e) => self.print_expr(&**e),
2333 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2334 if let Some(e) = begin {
2339 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2340 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2341 RangeEnd::Excluded => self.s.word(".."),
2343 if let Some(e) = end {
2347 PatKind::Slice(ref elts) => {
2349 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2352 PatKind::Rest => self.s.word(".."),
2353 PatKind::Paren(ref inner) => {
2355 self.print_pat(inner);
2358 PatKind::Mac(ref m) => self.print_mac(m),
2360 self.ann.post(self, AnnNode::Pat(pat))
2363 fn print_arm(&mut self, arm: &ast::Arm) {
2364 // Note, I have no idea why this check is necessary, but here it is.
2365 if arm.attrs.is_empty() {
2368 self.cbox(INDENT_UNIT);
2370 self.maybe_print_comment(arm.pat.span.lo());
2371 self.print_outer_attributes(&arm.attrs);
2372 self.print_pat(&arm.pat);
2374 if let Some(ref e) = arm.guard {
2375 self.word_space("if");
2379 self.word_space("=>");
2381 match arm.body.kind {
2382 ast::ExprKind::Block(ref blk, opt_label) => {
2383 if let Some(label) = opt_label {
2384 self.print_ident(label.ident);
2385 self.word_space(":");
2388 // The block will close the pattern's ibox.
2389 self.print_block_unclosed_indent(blk);
2391 // If it is a user-provided unsafe block, print a comma after it.
2392 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2397 self.end(); // Close the ibox for the pattern.
2398 self.print_expr(&arm.body);
2402 self.end(); // Close enclosing cbox.
2405 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2406 match explicit_self.node {
2407 SelfKind::Value(m) => {
2408 self.print_mutability(m, false);
2411 SelfKind::Region(ref lt, m) => {
2413 self.print_opt_lifetime(lt);
2414 self.print_mutability(m, false);
2417 SelfKind::Explicit(ref typ, m) => {
2418 self.print_mutability(m, false);
2419 self.s.word("self");
2420 self.word_space(":");
2421 self.print_type(typ)
2429 header: ast::FnHeader,
2430 name: Option<ast::Ident>,
2431 generics: &ast::Generics,
2432 vis: &ast::Visibility,
2434 self.print_fn_header_info(header, vis);
2436 if let Some(name) = name {
2438 self.print_ident(name);
2440 self.print_generic_params(&generics.params);
2441 self.print_fn_params_and_ret(decl, false);
2442 self.print_where_clause(&generics.where_clause)
2445 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2446 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2448 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2450 self.print_fn_ret_ty(&decl.output)
2453 crate fn print_movability(&mut self, movability: ast::Movability) {
2455 ast::Movability::Static => self.word_space("static"),
2456 ast::Movability::Movable => {}
2460 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2461 if asyncness.is_async() {
2462 self.word_nbsp("async");
2466 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2467 match capture_clause {
2468 ast::CaptureBy::Value => self.word_space("move"),
2469 ast::CaptureBy::Ref => {}
2473 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2474 if !bounds.is_empty() {
2475 self.s.word(prefix);
2476 let mut first = true;
2477 for bound in bounds {
2478 if !(first && prefix.is_empty()) {
2484 self.word_space("+");
2488 GenericBound::Trait(tref, modifier) => {
2489 if modifier == &TraitBoundModifier::Maybe {
2492 self.print_poly_trait_ref(tref);
2494 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2500 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2501 self.print_name(lifetime.ident.name)
2504 crate fn print_lifetime_bounds(
2506 lifetime: ast::Lifetime,
2507 bounds: &ast::GenericBounds,
2509 self.print_lifetime(lifetime);
2510 if !bounds.is_empty() {
2512 for (i, bound) in bounds.iter().enumerate() {
2517 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2524 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2525 if generic_params.is_empty() {
2531 self.commasep(Inconsistent, &generic_params, |s, param| {
2532 s.print_outer_attributes_inline(¶m.attrs);
2535 ast::GenericParamKind::Lifetime => {
2536 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2537 s.print_lifetime_bounds(lt, ¶m.bounds)
2539 ast::GenericParamKind::Type { ref default } => {
2540 s.print_ident(param.ident);
2541 s.print_type_bounds(":", ¶m.bounds);
2542 if let Some(ref default) = default {
2545 s.print_type(default)
2548 ast::GenericParamKind::Const { ref ty } => {
2549 s.word_space("const");
2550 s.print_ident(param.ident);
2554 s.print_type_bounds(":", ¶m.bounds)
2562 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2563 if where_clause.predicates.is_empty() {
2568 self.word_space("where");
2570 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2572 self.word_space(",");
2576 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2577 ref bound_generic_params,
2582 self.print_formal_generic_params(bound_generic_params);
2583 self.print_type(bounded_ty);
2584 self.print_type_bounds(":", bounds);
2586 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2591 self.print_lifetime_bounds(*lifetime, bounds);
2593 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2598 self.print_type(lhs_ty);
2600 self.word_space("=");
2601 self.print_type(rhs_ty);
2607 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2609 ast::UseTreeKind::Simple(rename, ..) => {
2610 self.print_path(&tree.prefix, false, 0);
2611 if let Some(rename) = rename {
2613 self.word_space("as");
2614 self.print_ident(rename);
2617 ast::UseTreeKind::Glob => {
2618 if !tree.prefix.segments.is_empty() {
2619 self.print_path(&tree.prefix, false, 0);
2624 ast::UseTreeKind::Nested(ref items) => {
2625 if tree.prefix.segments.is_empty() {
2628 self.print_path(&tree.prefix, false, 0);
2631 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2632 this.print_use_tree(tree)
2639 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2641 ast::Mutability::Mut => self.word_nbsp("mut"),
2642 ast::Mutability::Not => {
2644 self.word_nbsp("const");
2650 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2651 self.print_mutability(mt.mutbl, print_const);
2652 self.print_type(&mt.ty)
2655 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2656 self.ibox(INDENT_UNIT);
2658 self.print_outer_attributes_inline(&input.attrs);
2660 match input.ty.kind {
2661 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2663 if let Some(eself) = input.to_self() {
2664 self.print_explicit_self(&eself);
2666 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2667 ident.name == kw::Invalid
2672 self.print_pat(&input.pat);
2676 self.print_type(&input.ty);
2683 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FunctionRetTy) {
2684 if let ast::FunctionRetTy::Ty(ty) = fn_ret_ty {
2685 self.space_if_not_bol();
2686 self.ibox(INDENT_UNIT);
2687 self.word_space("->");
2688 self.print_type(ty);
2690 self.maybe_print_comment(ty.span.lo());
2694 crate fn print_ty_fn(
2697 unsafety: ast::Unsafety,
2699 name: Option<ast::Ident>,
2700 generic_params: &[ast::GenericParam],
2702 self.ibox(INDENT_UNIT);
2703 if !generic_params.is_empty() {
2705 self.print_generic_params(generic_params);
2707 let generics = ast::Generics {
2709 where_clause: ast::WhereClause { predicates: Vec::new(), span: rustc_span::DUMMY_SP },
2710 span: rustc_span::DUMMY_SP,
2714 ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() },
2717 &dummy_spanned(ast::VisibilityKind::Inherited),
2722 crate fn maybe_print_trailing_comment(
2724 span: rustc_span::Span,
2725 next_pos: Option<BytePos>,
2727 if let Some(cmnts) = self.comments() {
2728 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2729 self.print_comment(&cmnt);
2734 crate fn print_remaining_comments(&mut self) {
2735 // If there aren't any remaining comments, then we need to manually
2736 // make sure there is a line break at the end.
2737 if self.next_comment().is_none() {
2740 while let Some(ref cmnt) = self.next_comment() {
2741 self.print_comment(cmnt);
2745 crate fn print_fn_header_info(&mut self, header: ast::FnHeader, vis: &ast::Visibility) {
2746 self.s.word(visibility_qualified(vis, ""));
2748 match header.constness.node {
2749 ast::Constness::NotConst => {}
2750 ast::Constness::Const => self.word_nbsp("const"),
2753 self.print_asyncness(header.asyncness.node);
2754 self.print_unsafety(header.unsafety);
2757 ast::Extern::None => {}
2758 ast::Extern::Implicit => {
2759 self.word_nbsp("extern");
2761 ast::Extern::Explicit(abi) => {
2762 self.word_nbsp("extern");
2763 self.print_literal(&abi.as_lit());
2771 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2773 ast::Unsafety::Normal => {}
2774 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2778 crate fn print_constness(&mut self, s: ast::Constness) {
2780 ast::Constness::Const => self.word_nbsp("const"),
2781 ast::Constness::NotConst => {}
2785 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2787 ast::IsAuto::Yes => self.word_nbsp("auto"),
2788 ast::IsAuto::No => {}