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 {
1239 self.print_visibility(&item.vis);
1240 self.print_defaultness(defaultness);
1241 self.print_unsafety(unsafety);
1242 self.word_nbsp("impl");
1244 if !generics.params.is_empty() {
1245 self.print_generic_params(&generics.params);
1249 if polarity == ast::ImplPolarity::Negative {
1253 if let Some(ref t) = *of_trait {
1254 self.print_trait_ref(t);
1256 self.word_space("for");
1259 self.print_type(self_ty);
1260 self.print_where_clause(&generics.where_clause);
1264 self.print_inner_attributes(&item.attrs);
1265 for impl_item in items {
1266 self.print_assoc_item(impl_item);
1268 self.bclose(item.span);
1270 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1272 self.print_visibility(&item.vis);
1273 self.print_unsafety(unsafety);
1274 self.print_is_auto(is_auto);
1275 self.word_nbsp("trait");
1276 self.print_ident(item.ident);
1277 self.print_generic_params(&generics.params);
1278 let mut real_bounds = Vec::with_capacity(bounds.len());
1279 for b in bounds.iter() {
1280 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1282 self.word_space("for ?");
1283 self.print_trait_ref(&ptr.trait_ref);
1285 real_bounds.push(b.clone());
1288 self.print_type_bounds(":", &real_bounds[..]);
1289 self.print_where_clause(&generics.where_clause);
1292 for trait_item in trait_items {
1293 self.print_assoc_item(trait_item);
1295 self.bclose(item.span);
1297 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1299 self.print_visibility(&item.vis);
1300 self.word_nbsp("trait");
1301 self.print_ident(item.ident);
1302 self.print_generic_params(&generics.params);
1303 let mut real_bounds = Vec::with_capacity(bounds.len());
1304 // FIXME(durka) this seems to be some quite outdated syntax
1305 for b in bounds.iter() {
1306 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1308 self.word_space("for ?");
1309 self.print_trait_ref(&ptr.trait_ref);
1311 real_bounds.push(b.clone());
1315 self.print_type_bounds("=", &real_bounds[..]);
1316 self.print_where_clause(&generics.where_clause);
1319 ast::ItemKind::Mac(ref mac) => {
1320 self.print_mac(mac);
1321 if mac.args.need_semicolon() {
1325 ast::ItemKind::MacroDef(ref macro_def) => {
1326 let (kw, has_bang) = if macro_def.legacy {
1327 ("macro_rules", true)
1329 self.print_visibility(&item.vis);
1332 self.print_mac_common(
1333 Some(MacHeader::Keyword(kw)),
1336 macro_def.body.delim(),
1337 macro_def.body.inner_tokens(),
1343 self.ann.post(self, AnnNode::Item(item))
1346 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1347 self.print_path(&t.path, false, 0)
1350 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1351 if !generic_params.is_empty() {
1353 self.print_generic_params(generic_params);
1358 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1359 self.print_formal_generic_params(&t.bound_generic_params);
1360 self.print_trait_ref(&t.trait_ref)
1363 crate fn print_enum_def(
1365 enum_definition: &ast::EnumDef,
1366 generics: &ast::Generics,
1368 span: rustc_span::Span,
1369 visibility: &ast::Visibility,
1371 self.head(visibility_qualified(visibility, "enum"));
1372 self.print_ident(ident);
1373 self.print_generic_params(&generics.params);
1374 self.print_where_clause(&generics.where_clause);
1376 self.print_variants(&enum_definition.variants, span)
1379 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1382 self.space_if_not_bol();
1383 self.maybe_print_comment(v.span.lo());
1384 self.print_outer_attributes(&v.attrs);
1385 self.ibox(INDENT_UNIT);
1386 self.print_variant(v);
1389 self.maybe_print_trailing_comment(v.span, None);
1394 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1396 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1397 ast::VisibilityKind::Crate(sugar) => match sugar {
1398 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1399 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1401 ast::VisibilityKind::Restricted { ref path, .. } => {
1402 let path = to_string(|s| s.print_path(path, false, 0));
1403 if path == "self" || path == "super" {
1404 self.word_nbsp(format!("pub({})", path))
1406 self.word_nbsp(format!("pub(in {})", path))
1409 ast::VisibilityKind::Inherited => {}
1413 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1414 if let ast::Defaultness::Default = defaultness {
1415 self.word_nbsp("default");
1419 crate fn print_struct(
1421 struct_def: &ast::VariantData,
1422 generics: &ast::Generics,
1424 span: rustc_span::Span,
1425 print_finalizer: bool,
1427 self.print_ident(ident);
1428 self.print_generic_params(&generics.params);
1430 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1431 if let ast::VariantData::Tuple(..) = struct_def {
1433 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1434 s.maybe_print_comment(field.span.lo());
1435 s.print_outer_attributes(&field.attrs);
1436 s.print_visibility(&field.vis);
1437 s.print_type(&field.ty)
1441 self.print_where_clause(&generics.where_clause);
1442 if print_finalizer {
1446 self.end(); // Close the outer-box.
1448 ast::VariantData::Struct(..) => {
1449 self.print_where_clause(&generics.where_clause);
1452 self.hardbreak_if_not_bol();
1454 for field in struct_def.fields() {
1455 self.hardbreak_if_not_bol();
1456 self.maybe_print_comment(field.span.lo());
1457 self.print_outer_attributes(&field.attrs);
1458 self.print_visibility(&field.vis);
1459 self.print_ident(field.ident.unwrap());
1460 self.word_nbsp(":");
1461 self.print_type(&field.ty);
1470 crate fn print_variant(&mut self, v: &ast::Variant) {
1472 self.print_visibility(&v.vis);
1473 let generics = ast::Generics::default();
1474 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1478 self.word_space("=");
1479 self.print_expr(&d.value)
1485 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1486 self.ann.pre(self, AnnNode::SubItem(item.id));
1487 self.hardbreak_if_not_bol();
1488 self.maybe_print_comment(item.span.lo());
1489 self.print_outer_attributes(&item.attrs);
1490 self.print_defaultness(item.defaultness);
1492 ast::AssocItemKind::Const(ty, expr) => {
1493 self.print_associated_const(item.ident, ty, expr.as_deref(), &item.vis);
1495 ast::AssocItemKind::Fn(sig, body) => {
1499 self.print_fn(&sig.decl, sig.header, Some(item.ident), &item.generics, &item.vis);
1500 if let Some(body) = body {
1502 self.print_block_with_attrs(body, &item.attrs);
1507 ast::AssocItemKind::TyAlias(bounds, ty) => {
1508 self.print_associated_type(item.ident, bounds, ty.as_deref());
1510 ast::AssocItemKind::Macro(mac) => {
1511 self.print_mac(mac);
1512 if mac.args.need_semicolon() {
1517 self.ann.post(self, AnnNode::SubItem(item.id))
1520 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1521 self.maybe_print_comment(st.span.lo());
1523 ast::StmtKind::Local(ref loc) => {
1524 self.print_outer_attributes(&loc.attrs);
1525 self.space_if_not_bol();
1526 self.ibox(INDENT_UNIT);
1527 self.word_nbsp("let");
1529 self.ibox(INDENT_UNIT);
1530 self.print_local_decl(loc);
1532 if let Some(ref init) = loc.init {
1534 self.word_space("=");
1535 self.print_expr(init);
1540 ast::StmtKind::Item(ref item) => self.print_item(item),
1541 ast::StmtKind::Expr(ref expr) => {
1542 self.space_if_not_bol();
1543 self.print_expr_outer_attr_style(expr, false);
1544 if classify::expr_requires_semi_to_be_stmt(expr) {
1548 ast::StmtKind::Semi(ref expr) => {
1550 // Filter out empty `Tup` exprs created for the `redundant_semicolon`
1551 // lint, as they shouldn't be visible and interact poorly
1552 // with proc macros.
1553 ast::ExprKind::Tup(ref exprs) if exprs.is_empty() && expr.attrs.is_empty() => {
1557 self.space_if_not_bol();
1558 self.print_expr_outer_attr_style(expr, false);
1563 ast::StmtKind::Mac(ref mac) => {
1564 let (ref mac, style, ref attrs) = **mac;
1565 self.space_if_not_bol();
1566 self.print_outer_attributes(attrs);
1567 self.print_mac(mac);
1568 if style == ast::MacStmtStyle::Semicolon {
1573 self.maybe_print_trailing_comment(st.span, None)
1576 crate fn print_block(&mut self, blk: &ast::Block) {
1577 self.print_block_with_attrs(blk, &[])
1580 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1581 self.print_block_maybe_unclosed(blk, &[], false)
1584 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1585 self.print_block_maybe_unclosed(blk, attrs, true)
1588 crate fn print_block_maybe_unclosed(
1591 attrs: &[ast::Attribute],
1595 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1596 BlockCheckMode::Default => (),
1598 self.maybe_print_comment(blk.span.lo());
1599 self.ann.pre(self, AnnNode::Block(blk));
1602 self.print_inner_attributes(attrs);
1604 for (i, st) in blk.stmts.iter().enumerate() {
1606 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1607 self.maybe_print_comment(st.span.lo());
1608 self.space_if_not_bol();
1609 self.print_expr_outer_attr_style(expr, false);
1610 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1612 _ => self.print_stmt(st),
1616 self.bclose_maybe_open(blk.span, close_box);
1617 self.ann.post(self, AnnNode::Block(blk))
1620 /// Print a `let pat = scrutinee` expression.
1621 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1622 self.s.word("let ");
1624 self.print_pat(pat);
1627 self.word_space("=");
1628 self.print_expr_cond_paren(
1630 Self::cond_needs_par(scrutinee)
1631 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1635 fn print_else(&mut self, els: Option<&ast::Expr>) {
1636 if let Some(_else) = els {
1638 // Another `else if` block.
1639 ast::ExprKind::If(ref i, ref then, ref e) => {
1640 self.cbox(INDENT_UNIT - 1);
1642 self.s.word(" else if ");
1643 self.print_expr_as_cond(i);
1645 self.print_block(then);
1646 self.print_else(e.as_ref().map(|e| &**e))
1648 // Final `else` block.
1649 ast::ExprKind::Block(ref b, _) => {
1650 self.cbox(INDENT_UNIT - 1);
1652 self.s.word(" else ");
1655 // Constraints would be great here!
1657 panic!("print_if saw if with weird alternative");
1663 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1666 self.print_expr_as_cond(test);
1669 self.print_block(blk);
1670 self.print_else(elseopt)
1673 crate fn print_mac(&mut self, m: &ast::Mac) {
1674 self.print_mac_common(
1675 Some(MacHeader::Path(&m.path)),
1679 m.args.inner_tokens(),
1685 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1687 self.commasep_exprs(Inconsistent, args);
1691 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1692 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1695 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1696 /// `if cond { ... }`.
1697 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1698 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1701 /// Does `expr` need parenthesis when printed in a condition position?
1702 fn cond_needs_par(expr: &ast::Expr) -> bool {
1704 // These cases need parens due to the parse error observed in #26461: `if return {}`
1705 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1706 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1708 _ => parser::contains_exterior_struct_lit(expr),
1712 /// Prints `expr` or `(expr)` when `needs_par` holds.
1713 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1717 self.print_expr(expr);
1723 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1724 self.ibox(INDENT_UNIT);
1726 self.print_inner_attributes_inline(attrs);
1727 self.commasep_exprs(Inconsistent, &exprs[..]);
1732 fn print_expr_repeat(
1734 element: &ast::Expr,
1735 count: &ast::AnonConst,
1736 attrs: &[Attribute],
1738 self.ibox(INDENT_UNIT);
1740 self.print_inner_attributes_inline(attrs);
1741 self.print_expr(element);
1742 self.word_space(";");
1743 self.print_expr(&count.value);
1748 fn print_expr_struct(
1751 fields: &[ast::Field],
1752 wth: &Option<P<ast::Expr>>,
1753 attrs: &[Attribute],
1755 self.print_path(path, true, 0);
1757 self.print_inner_attributes_inline(attrs);
1762 s.ibox(INDENT_UNIT);
1763 if !field.is_shorthand {
1764 s.print_ident(field.ident);
1767 s.print_expr(&field.expr);
1774 self.ibox(INDENT_UNIT);
1775 if !fields.is_empty() {
1780 self.print_expr(expr);
1784 if !fields.is_empty() {
1792 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1794 self.print_inner_attributes_inline(attrs);
1795 self.commasep_exprs(Inconsistent, &exprs[..]);
1796 if exprs.len() == 1 {
1802 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1803 let prec = match func.kind {
1804 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1805 _ => parser::PREC_POSTFIX,
1808 self.print_expr_maybe_paren(func, prec);
1809 self.print_call_post(args)
1812 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1813 let base_args = &args[1..];
1814 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1816 self.print_ident(segment.ident);
1817 if let Some(ref args) = segment.args {
1818 self.print_generic_args(args, true);
1820 self.print_call_post(base_args)
1823 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1824 let assoc_op = AssocOp::from_ast_binop(op.node);
1825 let prec = assoc_op.precedence() as i8;
1826 let fixity = assoc_op.fixity();
1828 let (left_prec, right_prec) = match fixity {
1829 Fixity::Left => (prec, prec + 1),
1830 Fixity::Right => (prec + 1, prec),
1831 Fixity::None => (prec + 1, prec + 1),
1834 let left_prec = match (&lhs.kind, op.node) {
1835 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1836 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1837 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1838 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt)
1839 | (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1840 // We are given `(let _ = a) OP b`.
1842 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1843 // as the parser will interpret this as `(let _ = a) OP b`.
1845 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1846 // parens are required since the parser would interpret `let a = b < c` as
1847 // `let a = (b < c)`. To achieve this, we force parens.
1848 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1849 parser::PREC_FORCE_PAREN
1854 self.print_expr_maybe_paren(lhs, left_prec);
1856 self.word_space(op.node.to_string());
1857 self.print_expr_maybe_paren(rhs, right_prec)
1860 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1861 self.s.word(ast::UnOp::to_string(op));
1862 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1865 fn print_expr_addr_of(
1867 kind: ast::BorrowKind,
1868 mutability: ast::Mutability,
1873 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1874 ast::BorrowKind::Raw => {
1875 self.word_nbsp("raw");
1876 self.print_mutability(mutability, true);
1879 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1882 pub fn print_expr(&mut self, expr: &ast::Expr) {
1883 self.print_expr_outer_attr_style(expr, true)
1886 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1887 self.maybe_print_comment(expr.span.lo());
1889 let attrs = &expr.attrs;
1891 self.print_outer_attributes_inline(attrs);
1893 self.print_outer_attributes(attrs);
1896 self.ibox(INDENT_UNIT);
1897 self.ann.pre(self, AnnNode::Expr(expr));
1899 ast::ExprKind::Box(ref expr) => {
1900 self.word_space("box");
1901 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1903 ast::ExprKind::Array(ref exprs) => {
1904 self.print_expr_vec(&exprs[..], attrs);
1906 ast::ExprKind::Repeat(ref element, ref count) => {
1907 self.print_expr_repeat(element, count, attrs);
1909 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1910 self.print_expr_struct(path, &fields[..], wth, attrs);
1912 ast::ExprKind::Tup(ref exprs) => {
1913 self.print_expr_tup(&exprs[..], attrs);
1915 ast::ExprKind::Call(ref func, ref args) => {
1916 self.print_expr_call(func, &args[..]);
1918 ast::ExprKind::MethodCall(ref segment, ref args) => {
1919 self.print_expr_method_call(segment, &args[..]);
1921 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1922 self.print_expr_binary(op, lhs, rhs);
1924 ast::ExprKind::Unary(op, ref expr) => {
1925 self.print_expr_unary(op, expr);
1927 ast::ExprKind::AddrOf(k, m, ref expr) => {
1928 self.print_expr_addr_of(k, m, expr);
1930 ast::ExprKind::Lit(ref lit) => {
1931 self.print_literal(lit);
1933 ast::ExprKind::Cast(ref expr, ref ty) => {
1934 let prec = AssocOp::As.precedence() as i8;
1935 self.print_expr_maybe_paren(expr, prec);
1937 self.word_space("as");
1938 self.print_type(ty);
1940 ast::ExprKind::Type(ref expr, ref ty) => {
1941 let prec = AssocOp::Colon.precedence() as i8;
1942 self.print_expr_maybe_paren(expr, prec);
1943 self.word_space(":");
1944 self.print_type(ty);
1946 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1947 self.print_let(pat, scrutinee);
1949 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1950 self.print_if(test, blk, elseopt.as_ref().map(|e| &**e));
1952 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1953 if let Some(label) = opt_label {
1954 self.print_ident(label.ident);
1955 self.word_space(":");
1958 self.print_expr_as_cond(test);
1960 self.print_block_with_attrs(blk, attrs);
1962 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1963 if let Some(label) = opt_label {
1964 self.print_ident(label.ident);
1965 self.word_space(":");
1968 self.print_pat(pat);
1970 self.word_space("in");
1971 self.print_expr_as_cond(iter);
1973 self.print_block_with_attrs(blk, attrs);
1975 ast::ExprKind::Loop(ref blk, opt_label) => {
1976 if let Some(label) = opt_label {
1977 self.print_ident(label.ident);
1978 self.word_space(":");
1982 self.print_block_with_attrs(blk, attrs);
1984 ast::ExprKind::Match(ref expr, ref arms) => {
1985 self.cbox(INDENT_UNIT);
1986 self.ibox(INDENT_UNIT);
1987 self.word_nbsp("match");
1988 self.print_expr_as_cond(expr);
1991 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1993 self.print_arm(arm);
1995 self.bclose(expr.span);
1997 ast::ExprKind::Closure(
2005 self.print_movability(movability);
2006 self.print_asyncness(asyncness);
2007 self.print_capture_clause(capture_clause);
2009 self.print_fn_params_and_ret(decl, true);
2011 self.print_expr(body);
2012 self.end(); // need to close a box
2014 // a box will be closed by print_expr, but we didn't want an overall
2015 // wrapper so we closed the corresponding opening. so create an
2016 // empty box to satisfy the close.
2019 ast::ExprKind::Block(ref blk, opt_label) => {
2020 if let Some(label) = opt_label {
2021 self.print_ident(label.ident);
2022 self.word_space(":");
2024 // containing cbox, will be closed by print-block at }
2025 self.cbox(INDENT_UNIT);
2026 // head-box, will be closed by print-block after {
2028 self.print_block_with_attrs(blk, attrs);
2030 ast::ExprKind::Async(capture_clause, _, ref blk) => {
2031 self.word_nbsp("async");
2032 self.print_capture_clause(capture_clause);
2034 // cbox/ibox in analogy to the `ExprKind::Block` arm above
2035 self.cbox(INDENT_UNIT);
2037 self.print_block_with_attrs(blk, attrs);
2039 ast::ExprKind::Await(ref expr) => {
2040 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2041 self.s.word(".await");
2043 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
2044 let prec = AssocOp::Assign.precedence() as i8;
2045 self.print_expr_maybe_paren(lhs, prec + 1);
2047 self.word_space("=");
2048 self.print_expr_maybe_paren(rhs, prec);
2050 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
2051 let prec = AssocOp::Assign.precedence() as i8;
2052 self.print_expr_maybe_paren(lhs, prec + 1);
2054 self.s.word(op.node.to_string());
2055 self.word_space("=");
2056 self.print_expr_maybe_paren(rhs, prec);
2058 ast::ExprKind::Field(ref expr, ident) => {
2059 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2061 self.print_ident(ident);
2063 ast::ExprKind::Index(ref expr, ref index) => {
2064 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
2066 self.print_expr(index);
2069 ast::ExprKind::Range(ref start, ref end, limits) => {
2070 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
2071 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
2072 // Here we use a fake precedence value so that any child with lower precedence than
2073 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
2074 let fake_prec = AssocOp::LOr.precedence() as i8;
2075 if let Some(ref e) = *start {
2076 self.print_expr_maybe_paren(e, fake_prec);
2078 if limits == ast::RangeLimits::HalfOpen {
2083 if let Some(ref e) = *end {
2084 self.print_expr_maybe_paren(e, fake_prec);
2087 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
2088 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
2089 ast::ExprKind::Break(opt_label, ref opt_expr) => {
2090 self.s.word("break");
2092 if let Some(label) = opt_label {
2093 self.print_ident(label.ident);
2096 if let Some(ref expr) = *opt_expr {
2097 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2101 ast::ExprKind::Continue(opt_label) => {
2102 self.s.word("continue");
2104 if let Some(label) = opt_label {
2105 self.print_ident(label.ident);
2109 ast::ExprKind::Ret(ref result) => {
2110 self.s.word("return");
2111 if let Some(ref expr) = *result {
2113 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2116 ast::ExprKind::InlineAsm(ref a) => {
2117 self.s.word("asm!");
2119 self.print_string(&a.asm.as_str(), a.asm_str_style);
2120 self.word_space(":");
2122 self.commasep(Inconsistent, &a.outputs, |s, out| {
2123 let constraint = out.constraint.as_str();
2124 let mut ch = constraint.chars();
2126 Some('=') if out.is_rw => {
2127 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2129 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2132 s.print_expr(&out.expr);
2136 self.word_space(":");
2138 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2139 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2145 self.word_space(":");
2147 self.commasep(Inconsistent, &a.clobbers, |s, co| {
2148 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2151 let mut options = vec![];
2153 options.push("volatile");
2156 options.push("alignstack");
2158 if a.dialect == ast::AsmDialect::Intel {
2159 options.push("intel");
2162 if !options.is_empty() {
2164 self.word_space(":");
2165 self.commasep(Inconsistent, &options, |s, &co| {
2166 s.print_string(co, ast::StrStyle::Cooked);
2172 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2173 ast::ExprKind::Paren(ref e) => {
2175 self.print_inner_attributes_inline(attrs);
2179 ast::ExprKind::Yield(ref e) => {
2180 self.s.word("yield");
2184 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2189 ast::ExprKind::Try(ref e) => {
2190 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2193 ast::ExprKind::TryBlock(ref blk) => {
2196 self.print_block_with_attrs(blk, attrs)
2198 ast::ExprKind::Err => {
2200 self.s.word("/*ERROR*/");
2204 self.ann.post(self, AnnNode::Expr(expr));
2208 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2209 self.print_pat(&loc.pat);
2210 if let Some(ref ty) = loc.ty {
2211 self.word_space(":");
2212 self.print_type(ty);
2216 pub fn print_usize(&mut self, i: usize) {
2217 self.s.word(i.to_string())
2220 crate fn print_name(&mut self, name: ast::Name) {
2221 self.s.word(name.to_string());
2222 self.ann.post(self, AnnNode::Name(&name))
2225 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2227 self.print_type(&qself.ty);
2228 if qself.position > 0 {
2230 self.word_space("as");
2231 let depth = path.segments.len() - qself.position;
2232 self.print_path(path, false, depth);
2236 let item_segment = path.segments.last().unwrap();
2237 self.print_ident(item_segment.ident);
2238 match item_segment.args {
2239 Some(ref args) => self.print_generic_args(args, colons_before_params),
2244 crate fn print_pat(&mut self, pat: &ast::Pat) {
2245 self.maybe_print_comment(pat.span.lo());
2246 self.ann.pre(self, AnnNode::Pat(pat));
2247 /* Pat isn't normalized, but the beauty of it
2248 is that it doesn't matter */
2250 PatKind::Wild => self.s.word("_"),
2251 PatKind::Ident(binding_mode, ident, ref sub) => {
2252 match binding_mode {
2253 ast::BindingMode::ByRef(mutbl) => {
2254 self.word_nbsp("ref");
2255 self.print_mutability(mutbl, false);
2257 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2258 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2259 self.word_nbsp("mut");
2262 self.print_ident(ident);
2263 if let Some(ref p) = *sub {
2265 self.s.word_space("@");
2269 PatKind::TupleStruct(ref path, ref elts) => {
2270 self.print_path(path, true, 0);
2272 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2275 PatKind::Or(ref pats) => {
2276 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2278 PatKind::Path(None, ref path) => {
2279 self.print_path(path, true, 0);
2281 PatKind::Path(Some(ref qself), ref path) => {
2282 self.print_qpath(path, qself, false);
2284 PatKind::Struct(ref path, ref fields, etc) => {
2285 self.print_path(path, true, 0);
2287 self.word_space("{");
2292 s.cbox(INDENT_UNIT);
2293 if !f.is_shorthand {
2294 s.print_ident(f.ident);
2297 s.print_pat(&f.pat);
2303 if !fields.is_empty() {
2304 self.word_space(",");
2311 PatKind::Tuple(ref elts) => {
2313 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2314 if elts.len() == 1 {
2319 PatKind::Box(ref inner) => {
2320 self.s.word("box ");
2321 self.print_pat(inner);
2323 PatKind::Ref(ref inner, mutbl) => {
2325 if mutbl == ast::Mutability::Mut {
2326 self.s.word("mut ");
2328 self.print_pat(inner);
2330 PatKind::Lit(ref e) => self.print_expr(&**e),
2331 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2332 if let Some(e) = begin {
2337 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2338 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2339 RangeEnd::Excluded => self.s.word(".."),
2341 if let Some(e) = end {
2345 PatKind::Slice(ref elts) => {
2347 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2350 PatKind::Rest => self.s.word(".."),
2351 PatKind::Paren(ref inner) => {
2353 self.print_pat(inner);
2356 PatKind::Mac(ref m) => self.print_mac(m),
2358 self.ann.post(self, AnnNode::Pat(pat))
2361 fn print_arm(&mut self, arm: &ast::Arm) {
2362 // Note, I have no idea why this check is necessary, but here it is.
2363 if arm.attrs.is_empty() {
2366 self.cbox(INDENT_UNIT);
2368 self.maybe_print_comment(arm.pat.span.lo());
2369 self.print_outer_attributes(&arm.attrs);
2370 self.print_pat(&arm.pat);
2372 if let Some(ref e) = arm.guard {
2373 self.word_space("if");
2377 self.word_space("=>");
2379 match arm.body.kind {
2380 ast::ExprKind::Block(ref blk, opt_label) => {
2381 if let Some(label) = opt_label {
2382 self.print_ident(label.ident);
2383 self.word_space(":");
2386 // The block will close the pattern's ibox.
2387 self.print_block_unclosed_indent(blk);
2389 // If it is a user-provided unsafe block, print a comma after it.
2390 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2395 self.end(); // Close the ibox for the pattern.
2396 self.print_expr(&arm.body);
2400 self.end(); // Close enclosing cbox.
2403 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2404 match explicit_self.node {
2405 SelfKind::Value(m) => {
2406 self.print_mutability(m, false);
2409 SelfKind::Region(ref lt, m) => {
2411 self.print_opt_lifetime(lt);
2412 self.print_mutability(m, false);
2415 SelfKind::Explicit(ref typ, m) => {
2416 self.print_mutability(m, false);
2417 self.s.word("self");
2418 self.word_space(":");
2419 self.print_type(typ)
2427 header: ast::FnHeader,
2428 name: Option<ast::Ident>,
2429 generics: &ast::Generics,
2430 vis: &ast::Visibility,
2432 self.print_fn_header_info(header, vis);
2434 if let Some(name) = name {
2436 self.print_ident(name);
2438 self.print_generic_params(&generics.params);
2439 self.print_fn_params_and_ret(decl, false);
2440 self.print_where_clause(&generics.where_clause)
2443 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2444 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2446 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2448 self.print_fn_ret_ty(&decl.output)
2451 crate fn print_movability(&mut self, movability: ast::Movability) {
2453 ast::Movability::Static => self.word_space("static"),
2454 ast::Movability::Movable => {}
2458 crate fn print_asyncness(&mut self, asyncness: ast::IsAsync) {
2459 if asyncness.is_async() {
2460 self.word_nbsp("async");
2464 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2465 match capture_clause {
2466 ast::CaptureBy::Value => self.word_space("move"),
2467 ast::CaptureBy::Ref => {}
2471 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2472 if !bounds.is_empty() {
2473 self.s.word(prefix);
2474 let mut first = true;
2475 for bound in bounds {
2476 if !(first && prefix.is_empty()) {
2482 self.word_space("+");
2486 GenericBound::Trait(tref, modifier) => {
2487 if modifier == &TraitBoundModifier::Maybe {
2490 self.print_poly_trait_ref(tref);
2492 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2498 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2499 self.print_name(lifetime.ident.name)
2502 crate fn print_lifetime_bounds(
2504 lifetime: ast::Lifetime,
2505 bounds: &ast::GenericBounds,
2507 self.print_lifetime(lifetime);
2508 if !bounds.is_empty() {
2510 for (i, bound) in bounds.iter().enumerate() {
2515 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2522 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2523 if generic_params.is_empty() {
2529 self.commasep(Inconsistent, &generic_params, |s, param| {
2530 s.print_outer_attributes_inline(¶m.attrs);
2533 ast::GenericParamKind::Lifetime => {
2534 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2535 s.print_lifetime_bounds(lt, ¶m.bounds)
2537 ast::GenericParamKind::Type { ref default } => {
2538 s.print_ident(param.ident);
2539 s.print_type_bounds(":", ¶m.bounds);
2540 if let Some(ref default) = default {
2543 s.print_type(default)
2546 ast::GenericParamKind::Const { ref ty } => {
2547 s.word_space("const");
2548 s.print_ident(param.ident);
2552 s.print_type_bounds(":", ¶m.bounds)
2560 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2561 if where_clause.predicates.is_empty() {
2566 self.word_space("where");
2568 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2570 self.word_space(",");
2574 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2575 ref bound_generic_params,
2580 self.print_formal_generic_params(bound_generic_params);
2581 self.print_type(bounded_ty);
2582 self.print_type_bounds(":", bounds);
2584 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2589 self.print_lifetime_bounds(*lifetime, bounds);
2591 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2596 self.print_type(lhs_ty);
2598 self.word_space("=");
2599 self.print_type(rhs_ty);
2605 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2607 ast::UseTreeKind::Simple(rename, ..) => {
2608 self.print_path(&tree.prefix, false, 0);
2609 if let Some(rename) = rename {
2611 self.word_space("as");
2612 self.print_ident(rename);
2615 ast::UseTreeKind::Glob => {
2616 if !tree.prefix.segments.is_empty() {
2617 self.print_path(&tree.prefix, false, 0);
2622 ast::UseTreeKind::Nested(ref items) => {
2623 if tree.prefix.segments.is_empty() {
2626 self.print_path(&tree.prefix, false, 0);
2629 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2630 this.print_use_tree(tree)
2637 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2639 ast::Mutability::Mut => self.word_nbsp("mut"),
2640 ast::Mutability::Not => {
2642 self.word_nbsp("const");
2648 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2649 self.print_mutability(mt.mutbl, print_const);
2650 self.print_type(&mt.ty)
2653 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2654 self.ibox(INDENT_UNIT);
2656 self.print_outer_attributes_inline(&input.attrs);
2658 match input.ty.kind {
2659 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2661 if let Some(eself) = input.to_self() {
2662 self.print_explicit_self(&eself);
2664 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2665 ident.name == kw::Invalid
2670 self.print_pat(&input.pat);
2674 self.print_type(&input.ty);
2681 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FunctionRetTy) {
2682 if let ast::FunctionRetTy::Ty(ty) = fn_ret_ty {
2683 self.space_if_not_bol();
2684 self.ibox(INDENT_UNIT);
2685 self.word_space("->");
2686 self.print_type(ty);
2688 self.maybe_print_comment(ty.span.lo());
2692 crate fn print_ty_fn(
2695 unsafety: ast::Unsafety,
2697 name: Option<ast::Ident>,
2698 generic_params: &[ast::GenericParam],
2700 self.ibox(INDENT_UNIT);
2701 if !generic_params.is_empty() {
2703 self.print_generic_params(generic_params);
2705 let generics = ast::Generics {
2707 where_clause: ast::WhereClause { predicates: Vec::new(), span: rustc_span::DUMMY_SP },
2708 span: rustc_span::DUMMY_SP,
2712 ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() },
2715 &dummy_spanned(ast::VisibilityKind::Inherited),
2720 crate fn maybe_print_trailing_comment(
2722 span: rustc_span::Span,
2723 next_pos: Option<BytePos>,
2725 if let Some(cmnts) = self.comments() {
2726 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2727 self.print_comment(&cmnt);
2732 crate fn print_remaining_comments(&mut self) {
2733 // If there aren't any remaining comments, then we need to manually
2734 // make sure there is a line break at the end.
2735 if self.next_comment().is_none() {
2738 while let Some(ref cmnt) = self.next_comment() {
2739 self.print_comment(cmnt);
2743 crate fn print_fn_header_info(&mut self, header: ast::FnHeader, vis: &ast::Visibility) {
2744 self.s.word(visibility_qualified(vis, ""));
2746 match header.constness.node {
2747 ast::Constness::NotConst => {}
2748 ast::Constness::Const => self.word_nbsp("const"),
2751 self.print_asyncness(header.asyncness.node);
2752 self.print_unsafety(header.unsafety);
2755 ast::Extern::None => {}
2756 ast::Extern::Implicit => {
2757 self.word_nbsp("extern");
2759 ast::Extern::Explicit(abi) => {
2760 self.word_nbsp("extern");
2761 self.print_literal(&abi.as_lit());
2769 crate fn print_unsafety(&mut self, s: ast::Unsafety) {
2771 ast::Unsafety::Normal => {}
2772 ast::Unsafety::Unsafe => self.word_nbsp("unsafe"),
2776 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2778 ast::IsAuto::Yes => self.word_nbsp("auto"),
2779 ast::IsAuto::No => {}