1 use crate::pp::Breaks::{Consistent, Inconsistent};
2 use crate::pp::{self, Breaks};
4 use rustc_ast::ast::{self, BlockCheckMode, PatKind, RangeEnd, RangeSyntax};
5 use rustc_ast::ast::{Attribute, GenericArg, MacArgs};
6 use rustc_ast::ast::{GenericBound, SelfKind, TraitBoundModifier};
9 use rustc_ast::token::{self, BinOpToken, DelimToken, Nonterminal, Token, TokenKind};
10 use rustc_ast::tokenstream::{self, TokenStream, TokenTree};
11 use rustc_ast::util::parser::{self, AssocOp, Fixity};
12 use rustc_ast::util::{classify, comments};
13 use rustc_span::edition::Edition;
14 use rustc_span::source_map::{SourceMap, Spanned};
15 use rustc_span::symbol::{kw, sym, IdentPrinter};
16 use rustc_span::{BytePos, FileName, Span};
23 pub enum MacHeader<'a> {
25 Keyword(&'static str),
28 pub enum AnnNode<'a> {
29 Ident(&'a ast::Ident),
31 Block(&'a ast::Block),
36 Crate(&'a ast::Crate),
40 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
41 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
44 #[derive(Copy, Clone)]
47 impl PpAnn for NoAnn {}
49 pub struct Comments<'a> {
51 comments: Vec<comments::Comment>,
55 impl<'a> Comments<'a> {
56 pub fn new(sm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
57 let comments = comments::gather_comments(sm, filename, input);
58 Comments { sm, comments, current: 0 }
61 pub fn next(&self) -> Option<comments::Comment> {
62 self.comments.get(self.current).cloned()
65 pub fn trailing_comment(
67 span: rustc_span::Span,
68 next_pos: Option<BytePos>,
69 ) -> Option<comments::Comment> {
70 if let Some(cmnt) = self.next() {
71 if cmnt.style != comments::Trailing {
74 let span_line = self.sm.lookup_char_pos(span.hi());
75 let comment_line = self.sm.lookup_char_pos(cmnt.pos);
76 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
77 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
86 pub struct State<'a> {
88 comments: Option<Comments<'a>>,
89 ann: &'a (dyn PpAnn + 'a),
93 crate const INDENT_UNIT: usize = 4;
95 /// Requires you to pass an input filename and reader so that
96 /// it can scan the input text for comments to copy forward.
97 pub fn print_crate<'a>(
105 has_injected_crate: bool,
109 comments: Some(Comments::new(sm, filename, input)),
114 if is_expanded && has_injected_crate {
115 // We need to print `#![no_std]` (and its feature gate) so that
116 // compiling pretty-printed source won't inject libstd again.
117 // However, we don't want these attributes in the AST because
118 // of the feature gate, so we fake them up here.
120 // `#![feature(prelude_import)]`
121 let pi_nested = attr::mk_nested_word_item(ast::Ident::with_dummy_span(sym::prelude_import));
122 let list = attr::mk_list_item(ast::Ident::with_dummy_span(sym::feature), vec![pi_nested]);
123 let fake_attr = attr::mk_attr_inner(list);
124 s.print_attribute(&fake_attr);
126 // Currently, in Rust 2018 we don't have `extern crate std;` at the crate
127 // root, so this is not needed, and actually breaks things.
128 if edition == Edition::Edition2015 {
130 let no_std_meta = attr::mk_word_item(ast::Ident::with_dummy_span(sym::no_std));
131 let fake_attr = attr::mk_attr_inner(no_std_meta);
132 s.print_attribute(&fake_attr);
136 s.print_mod(&krate.module, &krate.attrs);
137 s.print_remaining_comments();
138 s.ann.post(&mut s, AnnNode::Crate(krate));
142 pub fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
144 State { s: pp::mk_printer(), comments: None, ann: &NoAnn, is_expanded: false };
149 // This makes comma-separated lists look slightly nicer,
150 // and also addresses a specific regression described in issue #63896.
151 fn tt_prepend_space(tt: &TokenTree) -> bool {
153 TokenTree::Token(token) => match token.kind {
154 token::Comma => false,
161 fn binop_to_string(op: BinOpToken) -> &'static str {
167 token::Percent => "%",
176 pub fn literal_to_string(lit: token::Lit) -> String {
177 let token::Lit { kind, symbol, suffix } = lit;
178 let mut out = match kind {
179 token::Byte => format!("b'{}'", symbol),
180 token::Char => format!("'{}'", symbol),
181 token::Str => format!("\"{}\"", symbol),
182 token::StrRaw(n) => {
183 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
185 token::ByteStr => format!("b\"{}\"", symbol),
186 token::ByteStrRaw(n) => {
187 format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
189 token::Integer | token::Float | token::Bool | token::Err => symbol.to_string(),
192 if let Some(suffix) = suffix {
193 out.push_str(&suffix.as_str())
199 /// Print the token kind precisely, without converting `$crate` into its respective crate name.
200 pub fn token_kind_to_string(tok: &TokenKind) -> String {
201 token_kind_to_string_ext(tok, None)
204 fn token_kind_to_string_ext(tok: &TokenKind, convert_dollar_crate: Option<Span>) -> String {
206 token::Eq => "=".to_string(),
207 token::Lt => "<".to_string(),
208 token::Le => "<=".to_string(),
209 token::EqEq => "==".to_string(),
210 token::Ne => "!=".to_string(),
211 token::Ge => ">=".to_string(),
212 token::Gt => ">".to_string(),
213 token::Not => "!".to_string(),
214 token::Tilde => "~".to_string(),
215 token::OrOr => "||".to_string(),
216 token::AndAnd => "&&".to_string(),
217 token::BinOp(op) => binop_to_string(op).to_string(),
218 token::BinOpEq(op) => format!("{}=", binop_to_string(op)),
220 /* Structural symbols */
221 token::At => "@".to_string(),
222 token::Dot => ".".to_string(),
223 token::DotDot => "..".to_string(),
224 token::DotDotDot => "...".to_string(),
225 token::DotDotEq => "..=".to_string(),
226 token::Comma => ",".to_string(),
227 token::Semi => ";".to_string(),
228 token::Colon => ":".to_string(),
229 token::ModSep => "::".to_string(),
230 token::RArrow => "->".to_string(),
231 token::LArrow => "<-".to_string(),
232 token::FatArrow => "=>".to_string(),
233 token::OpenDelim(token::Paren) => "(".to_string(),
234 token::CloseDelim(token::Paren) => ")".to_string(),
235 token::OpenDelim(token::Bracket) => "[".to_string(),
236 token::CloseDelim(token::Bracket) => "]".to_string(),
237 token::OpenDelim(token::Brace) => "{".to_string(),
238 token::CloseDelim(token::Brace) => "}".to_string(),
239 token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) => " ".to_string(),
240 token::Pound => "#".to_string(),
241 token::Dollar => "$".to_string(),
242 token::Question => "?".to_string(),
243 token::SingleQuote => "'".to_string(),
246 token::Literal(lit) => literal_to_string(lit),
248 /* Name components */
249 token::Ident(s, is_raw) => IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string(),
250 token::Lifetime(s) => s.to_string(),
253 token::DocComment(s) => s.to_string(),
254 token::Eof => "<eof>".to_string(),
255 token::Whitespace => " ".to_string(),
256 token::Comment => "/* */".to_string(),
257 token::Shebang(s) => format!("/* shebang: {}*/", s),
258 token::Unknown(s) => s.to_string(),
260 token::Interpolated(ref nt) => nonterminal_to_string(nt),
264 /// Print the token precisely, without converting `$crate` into its respective crate name.
265 pub fn token_to_string(token: &Token) -> String {
266 token_to_string_ext(token, false)
269 fn token_to_string_ext(token: &Token, convert_dollar_crate: bool) -> String {
270 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
271 token_kind_to_string_ext(&token.kind, convert_dollar_crate)
274 pub fn nonterminal_to_string(nt: &Nonterminal) -> String {
276 token::NtExpr(ref e) => expr_to_string(e),
277 token::NtMeta(ref e) => attr_item_to_string(e),
278 token::NtTy(ref e) => ty_to_string(e),
279 token::NtPath(ref e) => path_to_string(e),
280 token::NtItem(ref e) => item_to_string(e),
281 token::NtBlock(ref e) => block_to_string(e),
282 token::NtStmt(ref e) => stmt_to_string(e),
283 token::NtPat(ref e) => pat_to_string(e),
284 token::NtIdent(e, is_raw) => IdentPrinter::for_ast_ident(e, is_raw).to_string(),
285 token::NtLifetime(e) => e.to_string(),
286 token::NtLiteral(ref e) => expr_to_string(e),
287 token::NtTT(ref tree) => tt_to_string(tree.clone()),
288 token::NtVis(ref e) => vis_to_string(e),
292 pub fn ty_to_string(ty: &ast::Ty) -> String {
293 to_string(|s| s.print_type(ty))
296 pub fn bounds_to_string(bounds: &[ast::GenericBound]) -> String {
297 to_string(|s| s.print_type_bounds("", bounds))
300 pub fn pat_to_string(pat: &ast::Pat) -> String {
301 to_string(|s| s.print_pat(pat))
304 pub fn expr_to_string(e: &ast::Expr) -> String {
305 to_string(|s| s.print_expr(e))
308 pub fn tt_to_string(tt: tokenstream::TokenTree) -> String {
309 to_string(|s| s.print_tt(tt, false))
312 pub fn tts_to_string(tokens: TokenStream) -> String {
313 to_string(|s| s.print_tts(tokens, false))
316 pub fn stmt_to_string(stmt: &ast::Stmt) -> String {
317 to_string(|s| s.print_stmt(stmt))
320 pub fn item_to_string(i: &ast::Item) -> String {
321 to_string(|s| s.print_item(i))
324 pub fn generic_params_to_string(generic_params: &[ast::GenericParam]) -> String {
325 to_string(|s| s.print_generic_params(generic_params))
328 pub fn path_to_string(p: &ast::Path) -> String {
329 to_string(|s| s.print_path(p, false, 0))
332 pub fn path_segment_to_string(p: &ast::PathSegment) -> String {
333 to_string(|s| s.print_path_segment(p, false))
336 pub fn vis_to_string(v: &ast::Visibility) -> String {
337 to_string(|s| s.print_visibility(v))
340 fn block_to_string(blk: &ast::Block) -> String {
342 // Containing cbox, will be closed by `print_block` at `}`.
344 // Head-ibox, will be closed by `print_block` after `{`.
350 pub fn meta_list_item_to_string(li: &ast::NestedMetaItem) -> String {
351 to_string(|s| s.print_meta_list_item(li))
354 fn attr_item_to_string(ai: &ast::AttrItem) -> String {
355 to_string(|s| s.print_attr_item(ai, ai.path.span))
358 pub fn attribute_to_string(attr: &ast::Attribute) -> String {
359 to_string(|s| s.print_attribute(attr))
362 pub fn param_to_string(arg: &ast::Param) -> String {
363 to_string(|s| s.print_param(arg, false))
366 fn visibility_qualified(vis: &ast::Visibility, s: &str) -> String {
367 format!("{}{}", to_string(|s| s.print_visibility(vis)), s)
370 impl std::ops::Deref for State<'_> {
371 type Target = pp::Printer;
372 fn deref(&self) -> &Self::Target {
377 impl std::ops::DerefMut for State<'_> {
378 fn deref_mut(&mut self) -> &mut Self::Target {
383 pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
384 fn comments(&mut self) -> &mut Option<Comments<'a>>;
385 fn print_ident(&mut self, ident: ast::Ident);
386 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
396 F: FnMut(&mut Self, &T),
399 if let Some((first, rest)) = elts.split_first() {
405 self.word_space(sep);
412 fn commasep<T, F>(&mut self, b: Breaks, elts: &[T], op: F)
414 F: FnMut(&mut Self, &T),
416 self.strsep(",", false, b, elts, op)
419 fn maybe_print_comment(&mut self, pos: BytePos) {
420 while let Some(ref cmnt) = self.next_comment() {
422 self.print_comment(cmnt);
429 fn print_comment(&mut self, cmnt: &comments::Comment) {
432 assert_eq!(cmnt.lines.len(), 1);
434 self.word(cmnt.lines[0].clone());
437 comments::Isolated => {
438 self.hardbreak_if_not_bol();
439 for line in &cmnt.lines {
440 // Don't print empty lines because they will end up as trailing
442 if !line.is_empty() {
443 self.word(line.clone());
448 comments::Trailing => {
449 if !self.is_beginning_of_line() {
452 if cmnt.lines.len() == 1 {
453 self.word(cmnt.lines[0].clone());
457 for line in &cmnt.lines {
458 if !line.is_empty() {
459 self.word(line.clone());
466 comments::BlankLine => {
467 // We need to do at least one, possibly two hardbreaks.
468 let twice = match self.last_token() {
469 pp::Token::String(s) => ";" == s,
470 pp::Token::Begin(_) => true,
471 pp::Token::End => true,
480 if let Some(cmnts) = self.comments() {
485 fn next_comment(&mut self) -> Option<comments::Comment> {
486 self.comments().as_mut().and_then(|c| c.next())
489 fn print_literal(&mut self, lit: &ast::Lit) {
490 self.maybe_print_comment(lit.span.lo());
491 self.word(lit.token.to_string())
494 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
495 let st = match style {
496 ast::StrStyle::Cooked => (format!("\"{}\"", st.escape_debug())),
497 ast::StrStyle::Raw(n) => {
498 format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
504 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) {
505 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
508 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) {
509 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
512 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) {
513 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
516 fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
517 self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true)
520 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) {
521 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
524 fn print_either_attributes(
526 attrs: &[ast::Attribute],
527 kind: ast::AttrStyle,
529 trailing_hardbreak: bool,
533 if attr.style == kind {
534 self.print_attribute_inline(attr, is_inline);
541 if count > 0 && trailing_hardbreak && !is_inline {
542 self.hardbreak_if_not_bol();
546 fn print_attribute(&mut self, attr: &ast::Attribute) {
547 self.print_attribute_inline(attr, false)
550 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) {
552 self.hardbreak_if_not_bol();
554 self.maybe_print_comment(attr.span.lo());
556 ast::AttrKind::Normal(ref item) => {
558 ast::AttrStyle::Inner => self.word("#!["),
559 ast::AttrStyle::Outer => self.word("#["),
561 self.print_attr_item(&item, attr.span);
564 ast::AttrKind::DocComment(comment) => {
565 self.word(comment.to_string());
571 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
574 MacArgs::Delimited(_, delim, tokens) => self.print_mac_common(
575 Some(MacHeader::Path(&item.path)),
583 MacArgs::Empty | MacArgs::Eq(..) => {
584 self.print_path(&item.path, false, 0);
585 if let MacArgs::Eq(_, tokens) = &item.args {
587 self.word_space("=");
588 self.print_tts(tokens.clone(), true);
595 fn print_meta_list_item(&mut self, item: &ast::NestedMetaItem) {
597 ast::NestedMetaItem::MetaItem(ref mi) => self.print_meta_item(mi),
598 ast::NestedMetaItem::Literal(ref lit) => self.print_literal(lit),
602 fn print_meta_item(&mut self, item: &ast::MetaItem) {
603 self.ibox(INDENT_UNIT);
605 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
606 ast::MetaItemKind::NameValue(ref value) => {
607 self.print_path(&item.path, false, 0);
609 self.word_space("=");
610 self.print_literal(value);
612 ast::MetaItemKind::List(ref items) => {
613 self.print_path(&item.path, false, 0);
615 self.commasep(Consistent, &items[..], |s, i| s.print_meta_list_item(i));
622 /// This doesn't deserve to be called "pretty" printing, but it should be
623 /// meaning-preserving. A quick hack that might help would be to look at the
624 /// spans embedded in the TTs to decide where to put spaces and newlines.
625 /// But it'd be better to parse these according to the grammar of the
626 /// appropriate macro, transcribe back into the grammar we just parsed from,
627 /// and then pretty-print the resulting AST nodes (so, e.g., we print
628 /// expression arguments as expressions). It can be done! I think.
629 fn print_tt(&mut self, tt: tokenstream::TokenTree, convert_dollar_crate: bool) {
631 TokenTree::Token(ref token) => {
632 self.word(token_to_string_ext(&token, convert_dollar_crate));
634 token::DocComment(..) => self.hardbreak(),
638 TokenTree::Delimited(dspan, delim, tts) => {
639 self.print_mac_common(
645 convert_dollar_crate,
652 fn print_tts(&mut self, tts: tokenstream::TokenStream, convert_dollar_crate: bool) {
653 for (i, tt) in tts.into_trees().enumerate() {
654 if i != 0 && tt_prepend_space(&tt) {
657 self.print_tt(tt, convert_dollar_crate);
663 header: Option<MacHeader<'_>>,
665 ident: Option<ast::Ident>,
668 convert_dollar_crate: bool,
671 if delim == DelimToken::Brace {
672 self.cbox(INDENT_UNIT);
675 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
676 Some(MacHeader::Keyword(kw)) => self.word(kw),
682 if let Some(ident) = ident {
684 self.print_ident(ident);
687 DelimToken::Brace => {
688 if header.is_some() || has_bang || ident.is_some() {
696 _ => self.word(token_kind_to_string(&token::OpenDelim(delim))),
699 self.print_tts(tts, convert_dollar_crate);
702 DelimToken::Brace => self.bclose(span),
703 _ => self.word(token_kind_to_string(&token::CloseDelim(delim))),
707 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
708 self.maybe_print_comment(path.span.lo());
710 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
714 self.print_path_segment(segment, colons_before_params);
718 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
719 if segment.ident.name != kw::PathRoot {
720 self.print_ident(segment.ident);
721 if let Some(ref args) = segment.args {
722 self.print_generic_args(args, colons_before_params);
727 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) {
729 // Outer-box is consistent.
730 self.cbox(INDENT_UNIT);
731 // Head-box is inconsistent.
732 self.ibox(w.len() + 1);
733 // Keyword that starts the head.
739 fn bopen(&mut self) {
741 self.end(); // Close the head-box.
744 fn bclose_maybe_open(&mut self, span: rustc_span::Span, close_box: bool) {
745 self.maybe_print_comment(span.hi());
746 self.break_offset_if_not_bol(1, -(INDENT_UNIT as isize));
749 self.end(); // Close the outer-box.
753 fn bclose(&mut self, span: rustc_span::Span) {
754 self.bclose_maybe_open(span, true)
757 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
758 if !self.is_beginning_of_line() {
759 self.break_offset(n, off)
761 if off != 0 && self.last_token().is_hardbreak_tok() {
762 // We do something pretty sketchy here: tuck the nonzero
763 // offset-adjustment we were going to deposit along with the
764 // break into the previous hardbreak.
765 self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
771 impl<'a> PrintState<'a> for State<'a> {
772 fn comments(&mut self) -> &mut Option<Comments<'a>> {
776 fn print_ident(&mut self, ident: ast::Ident) {
777 self.s.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string());
778 self.ann.post(self, AnnNode::Ident(&ident))
781 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
782 if colons_before_params {
787 ast::GenericArgs::AngleBracketed(ref data) => {
790 self.commasep(Inconsistent, &data.args, |s, generic_arg| {
791 s.print_generic_arg(generic_arg)
794 let mut comma = !data.args.is_empty();
796 for constraint in data.constraints.iter() {
800 self.print_ident(constraint.ident);
802 match constraint.kind {
803 ast::AssocTyConstraintKind::Equality { ref ty } => {
804 self.word_space("=");
807 ast::AssocTyConstraintKind::Bound { ref bounds } => {
808 self.print_type_bounds(":", &*bounds);
817 ast::GenericArgs::Parenthesized(ref data) => {
819 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
821 self.print_fn_ret_ty(&data.output);
828 // Synthesizes a comment that was not textually present in the original source
830 pub fn synth_comment(&mut self, text: String) {
838 crate fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
840 F: FnMut(&mut State<'_>, &T),
841 G: FnMut(&T) -> rustc_span::Span,
844 let len = elts.len();
847 self.maybe_print_comment(get_span(elt).hi());
852 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
853 self.space_if_not_bol();
859 crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P<ast::Expr>]) {
860 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span)
863 pub fn print_mod(&mut self, _mod: &ast::Mod, attrs: &[ast::Attribute]) {
864 self.print_inner_attributes(attrs);
865 for item in &_mod.items {
866 self.print_item(item);
870 crate fn print_foreign_mod(&mut self, nmod: &ast::ForeignMod, attrs: &[Attribute]) {
871 self.print_inner_attributes(attrs);
872 for item in &nmod.items {
873 self.print_foreign_item(item);
877 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
878 if let Some(lt) = *lifetime {
879 self.print_lifetime(lt);
884 crate fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
886 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
887 GenericArg::Type(ty) => self.print_type(ty),
888 GenericArg::Const(ct) => self.print_expr(&ct.value),
892 pub fn print_type(&mut self, ty: &ast::Ty) {
893 self.maybe_print_comment(ty.span.lo());
896 ast::TyKind::Slice(ref ty) => {
901 ast::TyKind::Ptr(ref mt) => {
903 self.print_mt(mt, true);
905 ast::TyKind::Rptr(ref lifetime, ref mt) => {
907 self.print_opt_lifetime(lifetime);
908 self.print_mt(mt, false);
910 ast::TyKind::Never => {
913 ast::TyKind::Tup(ref elts) => {
915 self.commasep(Inconsistent, &elts[..], |s, ty| s.print_type(ty));
921 ast::TyKind::Paren(ref typ) => {
923 self.print_type(typ);
926 ast::TyKind::BareFn(ref f) => {
927 self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params);
929 ast::TyKind::Path(None, ref path) => {
930 self.print_path(path, false, 0);
932 ast::TyKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, false),
933 ast::TyKind::TraitObject(ref bounds, syntax) => {
934 let prefix = if syntax == ast::TraitObjectSyntax::Dyn { "dyn" } else { "" };
935 self.print_type_bounds(prefix, &bounds[..]);
937 ast::TyKind::ImplTrait(_, ref bounds) => {
938 self.print_type_bounds("impl", &bounds[..]);
940 ast::TyKind::Array(ref ty, ref length) => {
944 self.print_expr(&length.value);
947 ast::TyKind::Typeof(ref e) => {
948 self.s.word("typeof(");
949 self.print_expr(&e.value);
952 ast::TyKind::Infer => {
955 ast::TyKind::Err => {
957 self.s.word("/*ERROR*/");
960 ast::TyKind::ImplicitSelf => {
963 ast::TyKind::Mac(ref m) => {
966 ast::TyKind::CVarArgs => {
973 crate fn print_foreign_item(&mut self, item: &ast::ForeignItem) {
974 let ast::Item { id, span, ident, attrs, kind, vis, tokens: _ } = item;
975 self.print_nested_item_kind(*id, *span, *ident, attrs, kind, vis);
978 fn print_nested_item_kind(
984 kind: &ast::AssocItemKind,
985 vis: &ast::Visibility,
987 self.ann.pre(self, AnnNode::SubItem(id));
988 self.hardbreak_if_not_bol();
989 self.maybe_print_comment(span.lo());
990 self.print_outer_attributes(attrs);
992 ast::ForeignItemKind::Fn(def, sig, gen, body) => {
993 self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
995 ast::ForeignItemKind::Const(def, ty, body) => {
996 self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
998 ast::ForeignItemKind::Static(ty, mutbl, body) => {
999 let def = ast::Defaultness::Final;
1000 self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
1002 ast::ForeignItemKind::TyAlias(def, generics, bounds, ty) => {
1003 self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
1005 ast::ForeignItemKind::Macro(m) => {
1007 if m.args.need_semicolon() {
1012 self.ann.post(self, AnnNode::SubItem(id))
1015 fn print_item_const(
1018 mutbl: Option<ast::Mutability>,
1020 body: Option<&ast::Expr>,
1021 vis: &ast::Visibility,
1022 defaultness: ast::Defaultness,
1025 self.print_visibility(vis);
1026 self.print_defaultness(defaultness);
1027 let leading = match mutbl {
1029 Some(ast::Mutability::Not) => "static",
1030 Some(ast::Mutability::Mut) => "static mut",
1032 self.word_space(leading);
1033 self.print_ident(ident);
1034 self.word_space(":");
1035 self.print_type(ty);
1037 self.end(); // end the head-ibox
1038 if let Some(body) = body {
1039 self.word_space("=");
1040 self.print_expr(body);
1043 self.end(); // end the outer cbox
1046 fn print_associated_type(
1049 generics: &ast::Generics,
1050 bounds: &ast::GenericBounds,
1051 ty: Option<&ast::Ty>,
1052 vis: &ast::Visibility,
1053 defaultness: ast::Defaultness,
1056 self.print_visibility(vis);
1057 self.print_defaultness(defaultness);
1058 self.word_space("type");
1059 self.print_ident(ident);
1060 self.print_generic_params(&generics.params);
1061 self.print_type_bounds(":", bounds);
1062 self.print_where_clause(&generics.where_clause);
1063 if let Some(ty) = ty {
1065 self.word_space("=");
1066 self.print_type(ty);
1069 self.end(); // end inner head-block
1070 self.end(); // end outer head-block
1073 /// Pretty-prints an item.
1074 crate fn print_item(&mut self, item: &ast::Item) {
1075 self.hardbreak_if_not_bol();
1076 self.maybe_print_comment(item.span.lo());
1077 self.print_outer_attributes(&item.attrs);
1078 self.ann.pre(self, AnnNode::Item(item));
1080 ast::ItemKind::ExternCrate(orig_name) => {
1081 self.head(visibility_qualified(&item.vis, "extern crate"));
1082 if let Some(orig_name) = orig_name {
1083 self.print_name(orig_name);
1088 self.print_ident(item.ident);
1090 self.end(); // end inner head-block
1091 self.end(); // end outer head-block
1093 ast::ItemKind::Use(ref tree) => {
1094 self.head(visibility_qualified(&item.vis, "use"));
1095 self.print_use_tree(tree);
1097 self.end(); // end inner head-block
1098 self.end(); // end outer head-block
1100 ast::ItemKind::Static(ref ty, mutbl, ref body) => {
1101 let def = ast::Defaultness::Final;
1102 self.print_item_const(item.ident, Some(mutbl), ty, body.as_deref(), &item.vis, def);
1104 ast::ItemKind::Const(def, ref ty, ref body) => {
1105 self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
1107 ast::ItemKind::Fn(def, ref sig, ref gen, ref body) => {
1108 let body = body.as_deref();
1109 self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
1111 ast::ItemKind::Mod(ref _mod) => {
1112 self.head(visibility_qualified(&item.vis, "mod"));
1113 self.print_ident(item.ident);
1115 if _mod.inline || self.is_expanded {
1118 self.print_mod(_mod, &item.attrs);
1119 self.bclose(item.span);
1122 self.end(); // end inner head-block
1123 self.end(); // end outer head-block
1126 ast::ItemKind::ForeignMod(ref nmod) => {
1127 self.head("extern");
1128 if let Some(abi) = nmod.abi {
1129 self.print_literal(&abi.as_lit());
1133 self.print_foreign_mod(nmod, &item.attrs);
1134 self.bclose(item.span);
1136 ast::ItemKind::GlobalAsm(ref ga) => {
1137 self.head(visibility_qualified(&item.vis, "global_asm!"));
1138 self.s.word(ga.asm.to_string());
1141 ast::ItemKind::TyAlias(def, ref generics, ref bounds, ref ty) => {
1142 let ty = ty.as_deref();
1143 self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
1145 ast::ItemKind::Enum(ref enum_definition, ref params) => {
1146 self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
1148 ast::ItemKind::Struct(ref struct_def, ref generics) => {
1149 self.head(visibility_qualified(&item.vis, "struct"));
1150 self.print_struct(struct_def, generics, item.ident, item.span, true);
1152 ast::ItemKind::Union(ref struct_def, ref generics) => {
1153 self.head(visibility_qualified(&item.vis, "union"));
1154 self.print_struct(struct_def, generics, item.ident, item.span, true);
1156 ast::ItemKind::Impl {
1167 self.print_visibility(&item.vis);
1168 self.print_defaultness(defaultness);
1169 self.print_unsafety(unsafety);
1170 self.word_nbsp("impl");
1171 self.print_constness(constness);
1173 if !generics.params.is_empty() {
1174 self.print_generic_params(&generics.params);
1178 if polarity == ast::ImplPolarity::Negative {
1182 if let Some(ref t) = *of_trait {
1183 self.print_trait_ref(t);
1185 self.word_space("for");
1188 self.print_type(self_ty);
1189 self.print_where_clause(&generics.where_clause);
1193 self.print_inner_attributes(&item.attrs);
1194 for impl_item in items {
1195 self.print_assoc_item(impl_item);
1197 self.bclose(item.span);
1199 ast::ItemKind::Trait(is_auto, unsafety, ref generics, ref bounds, ref trait_items) => {
1201 self.print_visibility(&item.vis);
1202 self.print_unsafety(unsafety);
1203 self.print_is_auto(is_auto);
1204 self.word_nbsp("trait");
1205 self.print_ident(item.ident);
1206 self.print_generic_params(&generics.params);
1207 let mut real_bounds = Vec::with_capacity(bounds.len());
1208 for b in bounds.iter() {
1209 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1211 self.word_space("for ?");
1212 self.print_trait_ref(&ptr.trait_ref);
1214 real_bounds.push(b.clone());
1217 self.print_type_bounds(":", &real_bounds[..]);
1218 self.print_where_clause(&generics.where_clause);
1221 self.print_inner_attributes(&item.attrs);
1222 for trait_item in trait_items {
1223 self.print_assoc_item(trait_item);
1225 self.bclose(item.span);
1227 ast::ItemKind::TraitAlias(ref generics, ref bounds) => {
1229 self.print_visibility(&item.vis);
1230 self.word_nbsp("trait");
1231 self.print_ident(item.ident);
1232 self.print_generic_params(&generics.params);
1233 let mut real_bounds = Vec::with_capacity(bounds.len());
1234 // FIXME(durka) this seems to be some quite outdated syntax
1235 for b in bounds.iter() {
1236 if let GenericBound::Trait(ref ptr, ast::TraitBoundModifier::Maybe) = *b {
1238 self.word_space("for ?");
1239 self.print_trait_ref(&ptr.trait_ref);
1241 real_bounds.push(b.clone());
1245 self.print_type_bounds("=", &real_bounds[..]);
1246 self.print_where_clause(&generics.where_clause);
1249 ast::ItemKind::Mac(ref mac) => {
1250 self.print_mac(mac);
1251 if mac.args.need_semicolon() {
1255 ast::ItemKind::MacroDef(ref macro_def) => {
1256 let (kw, has_bang) = if macro_def.legacy {
1257 ("macro_rules", true)
1259 self.print_visibility(&item.vis);
1262 self.print_mac_common(
1263 Some(MacHeader::Keyword(kw)),
1266 macro_def.body.delim(),
1267 macro_def.body.inner_tokens(),
1273 self.ann.post(self, AnnNode::Item(item))
1276 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1277 self.print_path(&t.path, false, 0)
1280 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1281 if !generic_params.is_empty() {
1283 self.print_generic_params(generic_params);
1288 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1289 self.print_formal_generic_params(&t.bound_generic_params);
1290 self.print_trait_ref(&t.trait_ref)
1293 crate fn print_enum_def(
1295 enum_definition: &ast::EnumDef,
1296 generics: &ast::Generics,
1298 span: rustc_span::Span,
1299 visibility: &ast::Visibility,
1301 self.head(visibility_qualified(visibility, "enum"));
1302 self.print_ident(ident);
1303 self.print_generic_params(&generics.params);
1304 self.print_where_clause(&generics.where_clause);
1306 self.print_variants(&enum_definition.variants, span)
1309 crate fn print_variants(&mut self, variants: &[ast::Variant], span: rustc_span::Span) {
1312 self.space_if_not_bol();
1313 self.maybe_print_comment(v.span.lo());
1314 self.print_outer_attributes(&v.attrs);
1315 self.ibox(INDENT_UNIT);
1316 self.print_variant(v);
1319 self.maybe_print_trailing_comment(v.span, None);
1324 crate fn print_visibility(&mut self, vis: &ast::Visibility) {
1326 ast::VisibilityKind::Public => self.word_nbsp("pub"),
1327 ast::VisibilityKind::Crate(sugar) => match sugar {
1328 ast::CrateSugar::PubCrate => self.word_nbsp("pub(crate)"),
1329 ast::CrateSugar::JustCrate => self.word_nbsp("crate"),
1331 ast::VisibilityKind::Restricted { ref path, .. } => {
1332 let path = to_string(|s| s.print_path(path, false, 0));
1333 if path == "self" || path == "super" {
1334 self.word_nbsp(format!("pub({})", path))
1336 self.word_nbsp(format!("pub(in {})", path))
1339 ast::VisibilityKind::Inherited => {}
1343 crate fn print_defaultness(&mut self, defaultness: ast::Defaultness) {
1344 if let ast::Defaultness::Default(_) = defaultness {
1345 self.word_nbsp("default");
1349 crate fn print_struct(
1351 struct_def: &ast::VariantData,
1352 generics: &ast::Generics,
1354 span: rustc_span::Span,
1355 print_finalizer: bool,
1357 self.print_ident(ident);
1358 self.print_generic_params(&generics.params);
1360 ast::VariantData::Tuple(..) | ast::VariantData::Unit(..) => {
1361 if let ast::VariantData::Tuple(..) = struct_def {
1363 self.commasep(Inconsistent, struct_def.fields(), |s, field| {
1364 s.maybe_print_comment(field.span.lo());
1365 s.print_outer_attributes(&field.attrs);
1366 s.print_visibility(&field.vis);
1367 s.print_type(&field.ty)
1371 self.print_where_clause(&generics.where_clause);
1372 if print_finalizer {
1376 self.end(); // Close the outer-box.
1378 ast::VariantData::Struct(..) => {
1379 self.print_where_clause(&generics.where_clause);
1382 self.hardbreak_if_not_bol();
1384 for field in struct_def.fields() {
1385 self.hardbreak_if_not_bol();
1386 self.maybe_print_comment(field.span.lo());
1387 self.print_outer_attributes(&field.attrs);
1388 self.print_visibility(&field.vis);
1389 self.print_ident(field.ident.unwrap());
1390 self.word_nbsp(":");
1391 self.print_type(&field.ty);
1400 crate fn print_variant(&mut self, v: &ast::Variant) {
1402 self.print_visibility(&v.vis);
1403 let generics = ast::Generics::default();
1404 self.print_struct(&v.data, &generics, v.ident, v.span, false);
1408 self.word_space("=");
1409 self.print_expr(&d.value)
1415 crate fn print_assoc_item(&mut self, item: &ast::AssocItem) {
1416 let ast::Item { id, span, ident, attrs, kind, vis, tokens: _ } = item;
1417 self.print_nested_item_kind(*id, *span, *ident, attrs, kind, vis);
1420 crate fn print_stmt(&mut self, st: &ast::Stmt) {
1421 self.maybe_print_comment(st.span.lo());
1423 ast::StmtKind::Local(ref loc) => {
1424 self.print_outer_attributes(&loc.attrs);
1425 self.space_if_not_bol();
1426 self.ibox(INDENT_UNIT);
1427 self.word_nbsp("let");
1429 self.ibox(INDENT_UNIT);
1430 self.print_local_decl(loc);
1432 if let Some(ref init) = loc.init {
1434 self.word_space("=");
1435 self.print_expr(init);
1440 ast::StmtKind::Item(ref item) => self.print_item(item),
1441 ast::StmtKind::Expr(ref expr) => {
1442 self.space_if_not_bol();
1443 self.print_expr_outer_attr_style(expr, false);
1444 if classify::expr_requires_semi_to_be_stmt(expr) {
1448 ast::StmtKind::Semi(ref expr) => {
1449 self.space_if_not_bol();
1450 self.print_expr_outer_attr_style(expr, false);
1453 ast::StmtKind::Empty => {
1454 self.space_if_not_bol();
1457 ast::StmtKind::Mac(ref mac) => {
1458 let (ref mac, style, ref attrs) = **mac;
1459 self.space_if_not_bol();
1460 self.print_outer_attributes(attrs);
1461 self.print_mac(mac);
1462 if style == ast::MacStmtStyle::Semicolon {
1467 self.maybe_print_trailing_comment(st.span, None)
1470 crate fn print_block(&mut self, blk: &ast::Block) {
1471 self.print_block_with_attrs(blk, &[])
1474 crate fn print_block_unclosed_indent(&mut self, blk: &ast::Block) {
1475 self.print_block_maybe_unclosed(blk, &[], false)
1478 crate fn print_block_with_attrs(&mut self, blk: &ast::Block, attrs: &[ast::Attribute]) {
1479 self.print_block_maybe_unclosed(blk, attrs, true)
1482 crate fn print_block_maybe_unclosed(
1485 attrs: &[ast::Attribute],
1489 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1490 BlockCheckMode::Default => (),
1492 self.maybe_print_comment(blk.span.lo());
1493 self.ann.pre(self, AnnNode::Block(blk));
1496 self.print_inner_attributes(attrs);
1498 for (i, st) in blk.stmts.iter().enumerate() {
1500 ast::StmtKind::Expr(ref expr) if i == blk.stmts.len() - 1 => {
1501 self.maybe_print_comment(st.span.lo());
1502 self.space_if_not_bol();
1503 self.print_expr_outer_attr_style(expr, false);
1504 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1506 _ => self.print_stmt(st),
1510 self.bclose_maybe_open(blk.span, close_box);
1511 self.ann.post(self, AnnNode::Block(blk))
1514 /// Print a `let pat = scrutinee` expression.
1515 crate fn print_let(&mut self, pat: &ast::Pat, scrutinee: &ast::Expr) {
1516 self.s.word("let ");
1518 self.print_pat(pat);
1521 self.word_space("=");
1522 self.print_expr_cond_paren(
1524 Self::cond_needs_par(scrutinee)
1525 || parser::needs_par_as_let_scrutinee(scrutinee.precedence().order()),
1529 fn print_else(&mut self, els: Option<&ast::Expr>) {
1530 if let Some(_else) = els {
1532 // Another `else if` block.
1533 ast::ExprKind::If(ref i, ref then, ref e) => {
1534 self.cbox(INDENT_UNIT - 1);
1536 self.s.word(" else if ");
1537 self.print_expr_as_cond(i);
1539 self.print_block(then);
1540 self.print_else(e.as_deref())
1542 // Final `else` block.
1543 ast::ExprKind::Block(ref b, _) => {
1544 self.cbox(INDENT_UNIT - 1);
1546 self.s.word(" else ");
1549 // Constraints would be great here!
1551 panic!("print_if saw if with weird alternative");
1557 crate fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
1560 self.print_expr_as_cond(test);
1563 self.print_block(blk);
1564 self.print_else(elseopt)
1567 crate fn print_mac(&mut self, m: &ast::Mac) {
1568 self.print_mac_common(
1569 Some(MacHeader::Path(&m.path)),
1573 m.args.inner_tokens(),
1579 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
1581 self.commasep_exprs(Inconsistent, args);
1585 crate fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
1586 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
1589 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
1590 /// `if cond { ... }`.
1591 crate fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
1592 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
1595 /// Does `expr` need parenthesis when printed in a condition position?
1596 fn cond_needs_par(expr: &ast::Expr) -> bool {
1598 // These cases need parens due to the parse error observed in #26461: `if return {}`
1599 // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
1600 ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) | ast::ExprKind::Break(..) => true,
1602 _ => parser::contains_exterior_struct_lit(expr),
1606 /// Prints `expr` or `(expr)` when `needs_par` holds.
1607 fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
1611 self.print_expr(expr);
1617 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1618 self.ibox(INDENT_UNIT);
1620 self.print_inner_attributes_inline(attrs);
1621 self.commasep_exprs(Inconsistent, &exprs[..]);
1626 fn print_expr_repeat(
1628 element: &ast::Expr,
1629 count: &ast::AnonConst,
1630 attrs: &[Attribute],
1632 self.ibox(INDENT_UNIT);
1634 self.print_inner_attributes_inline(attrs);
1635 self.print_expr(element);
1636 self.word_space(";");
1637 self.print_expr(&count.value);
1642 fn print_expr_struct(
1645 fields: &[ast::Field],
1646 wth: &Option<P<ast::Expr>>,
1647 attrs: &[Attribute],
1649 self.print_path(path, true, 0);
1651 self.print_inner_attributes_inline(attrs);
1656 s.print_outer_attributes(&field.attrs);
1657 s.ibox(INDENT_UNIT);
1658 if !field.is_shorthand {
1659 s.print_ident(field.ident);
1662 s.print_expr(&field.expr);
1669 self.ibox(INDENT_UNIT);
1670 if !fields.is_empty() {
1675 self.print_expr(expr);
1679 if !fields.is_empty() {
1687 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>], attrs: &[Attribute]) {
1689 self.print_inner_attributes_inline(attrs);
1690 self.commasep_exprs(Inconsistent, &exprs[..]);
1691 if exprs.len() == 1 {
1697 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
1698 let prec = match func.kind {
1699 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
1700 _ => parser::PREC_POSTFIX,
1703 self.print_expr_maybe_paren(func, prec);
1704 self.print_call_post(args)
1707 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
1708 let base_args = &args[1..];
1709 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
1711 self.print_ident(segment.ident);
1712 if let Some(ref args) = segment.args {
1713 self.print_generic_args(args, true);
1715 self.print_call_post(base_args)
1718 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
1719 let assoc_op = AssocOp::from_ast_binop(op.node);
1720 let prec = assoc_op.precedence() as i8;
1721 let fixity = assoc_op.fixity();
1723 let (left_prec, right_prec) = match fixity {
1724 Fixity::Left => (prec, prec + 1),
1725 Fixity::Right => (prec + 1, prec),
1726 Fixity::None => (prec + 1, prec + 1),
1729 let left_prec = match (&lhs.kind, op.node) {
1730 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
1731 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
1732 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
1733 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt)
1734 | (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Shl) => parser::PREC_FORCE_PAREN,
1735 // We are given `(let _ = a) OP b`.
1737 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
1738 // as the parser will interpret this as `(let _ = a) OP b`.
1740 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
1741 // parens are required since the parser would interpret `let a = b < c` as
1742 // `let a = (b < c)`. To achieve this, we force parens.
1743 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
1744 parser::PREC_FORCE_PAREN
1749 self.print_expr_maybe_paren(lhs, left_prec);
1751 self.word_space(op.node.to_string());
1752 self.print_expr_maybe_paren(rhs, right_prec)
1755 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
1756 self.s.word(ast::UnOp::to_string(op));
1757 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1760 fn print_expr_addr_of(
1762 kind: ast::BorrowKind,
1763 mutability: ast::Mutability,
1768 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
1769 ast::BorrowKind::Raw => {
1770 self.word_nbsp("raw");
1771 self.print_mutability(mutability, true);
1774 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
1777 pub fn print_expr(&mut self, expr: &ast::Expr) {
1778 self.print_expr_outer_attr_style(expr, true)
1781 fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
1782 self.maybe_print_comment(expr.span.lo());
1784 let attrs = &expr.attrs;
1786 self.print_outer_attributes_inline(attrs);
1788 self.print_outer_attributes(attrs);
1791 self.ibox(INDENT_UNIT);
1792 self.ann.pre(self, AnnNode::Expr(expr));
1794 ast::ExprKind::Box(ref expr) => {
1795 self.word_space("box");
1796 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
1798 ast::ExprKind::Array(ref exprs) => {
1799 self.print_expr_vec(&exprs[..], attrs);
1801 ast::ExprKind::Repeat(ref element, ref count) => {
1802 self.print_expr_repeat(element, count, attrs);
1804 ast::ExprKind::Struct(ref path, ref fields, ref wth) => {
1805 self.print_expr_struct(path, &fields[..], wth, attrs);
1807 ast::ExprKind::Tup(ref exprs) => {
1808 self.print_expr_tup(&exprs[..], attrs);
1810 ast::ExprKind::Call(ref func, ref args) => {
1811 self.print_expr_call(func, &args[..]);
1813 ast::ExprKind::MethodCall(ref segment, ref args) => {
1814 self.print_expr_method_call(segment, &args[..]);
1816 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
1817 self.print_expr_binary(op, lhs, rhs);
1819 ast::ExprKind::Unary(op, ref expr) => {
1820 self.print_expr_unary(op, expr);
1822 ast::ExprKind::AddrOf(k, m, ref expr) => {
1823 self.print_expr_addr_of(k, m, expr);
1825 ast::ExprKind::Lit(ref lit) => {
1826 self.print_literal(lit);
1828 ast::ExprKind::Cast(ref expr, ref ty) => {
1829 let prec = AssocOp::As.precedence() as i8;
1830 self.print_expr_maybe_paren(expr, prec);
1832 self.word_space("as");
1833 self.print_type(ty);
1835 ast::ExprKind::Type(ref expr, ref ty) => {
1836 let prec = AssocOp::Colon.precedence() as i8;
1837 self.print_expr_maybe_paren(expr, prec);
1838 self.word_space(":");
1839 self.print_type(ty);
1841 ast::ExprKind::Let(ref pat, ref scrutinee) => {
1842 self.print_let(pat, scrutinee);
1844 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
1845 self.print_if(test, blk, elseopt.as_deref())
1847 ast::ExprKind::While(ref test, ref blk, opt_label) => {
1848 if let Some(label) = opt_label {
1849 self.print_ident(label.ident);
1850 self.word_space(":");
1853 self.print_expr_as_cond(test);
1855 self.print_block_with_attrs(blk, attrs);
1857 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
1858 if let Some(label) = opt_label {
1859 self.print_ident(label.ident);
1860 self.word_space(":");
1863 self.print_pat(pat);
1865 self.word_space("in");
1866 self.print_expr_as_cond(iter);
1868 self.print_block_with_attrs(blk, attrs);
1870 ast::ExprKind::Loop(ref blk, opt_label) => {
1871 if let Some(label) = opt_label {
1872 self.print_ident(label.ident);
1873 self.word_space(":");
1877 self.print_block_with_attrs(blk, attrs);
1879 ast::ExprKind::Match(ref expr, ref arms) => {
1880 self.cbox(INDENT_UNIT);
1881 self.ibox(INDENT_UNIT);
1882 self.word_nbsp("match");
1883 self.print_expr_as_cond(expr);
1886 self.print_inner_attributes_no_trailing_hardbreak(attrs);
1888 self.print_arm(arm);
1890 self.bclose(expr.span);
1892 ast::ExprKind::Closure(
1900 self.print_movability(movability);
1901 self.print_asyncness(asyncness);
1902 self.print_capture_clause(capture_clause);
1904 self.print_fn_params_and_ret(decl, true);
1906 self.print_expr(body);
1907 self.end(); // need to close a box
1909 // a box will be closed by print_expr, but we didn't want an overall
1910 // wrapper so we closed the corresponding opening. so create an
1911 // empty box to satisfy the close.
1914 ast::ExprKind::Block(ref blk, opt_label) => {
1915 if let Some(label) = opt_label {
1916 self.print_ident(label.ident);
1917 self.word_space(":");
1919 // containing cbox, will be closed by print-block at }
1920 self.cbox(INDENT_UNIT);
1921 // head-box, will be closed by print-block after {
1923 self.print_block_with_attrs(blk, attrs);
1925 ast::ExprKind::Async(capture_clause, _, ref blk) => {
1926 self.word_nbsp("async");
1927 self.print_capture_clause(capture_clause);
1929 // cbox/ibox in analogy to the `ExprKind::Block` arm above
1930 self.cbox(INDENT_UNIT);
1932 self.print_block_with_attrs(blk, attrs);
1934 ast::ExprKind::Await(ref expr) => {
1935 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1936 self.s.word(".await");
1938 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
1939 let prec = AssocOp::Assign.precedence() as i8;
1940 self.print_expr_maybe_paren(lhs, prec + 1);
1942 self.word_space("=");
1943 self.print_expr_maybe_paren(rhs, prec);
1945 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
1946 let prec = AssocOp::Assign.precedence() as i8;
1947 self.print_expr_maybe_paren(lhs, prec + 1);
1949 self.s.word(op.node.to_string());
1950 self.word_space("=");
1951 self.print_expr_maybe_paren(rhs, prec);
1953 ast::ExprKind::Field(ref expr, ident) => {
1954 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1956 self.print_ident(ident);
1958 ast::ExprKind::Index(ref expr, ref index) => {
1959 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
1961 self.print_expr(index);
1964 ast::ExprKind::Range(ref start, ref end, limits) => {
1965 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
1966 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
1967 // Here we use a fake precedence value so that any child with lower precedence than
1968 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
1969 let fake_prec = AssocOp::LOr.precedence() as i8;
1970 if let Some(ref e) = *start {
1971 self.print_expr_maybe_paren(e, fake_prec);
1973 if limits == ast::RangeLimits::HalfOpen {
1978 if let Some(ref e) = *end {
1979 self.print_expr_maybe_paren(e, fake_prec);
1982 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
1983 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
1984 ast::ExprKind::Break(opt_label, ref opt_expr) => {
1985 self.s.word("break");
1987 if let Some(label) = opt_label {
1988 self.print_ident(label.ident);
1991 if let Some(ref expr) = *opt_expr {
1992 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
1996 ast::ExprKind::Continue(opt_label) => {
1997 self.s.word("continue");
1999 if let Some(label) = opt_label {
2000 self.print_ident(label.ident);
2004 ast::ExprKind::Ret(ref result) => {
2005 self.s.word("return");
2006 if let Some(ref expr) = *result {
2008 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2011 ast::ExprKind::InlineAsm(ref a) => {
2012 self.s.word("asm!");
2014 self.print_string(&a.asm.as_str(), a.asm_str_style);
2015 self.word_space(":");
2017 self.commasep(Inconsistent, &a.outputs, |s, out| {
2018 let constraint = out.constraint.as_str();
2019 let mut ch = constraint.chars();
2021 Some('=') if out.is_rw => {
2022 s.print_string(&format!("+{}", ch.as_str()), ast::StrStyle::Cooked)
2024 _ => s.print_string(&constraint, ast::StrStyle::Cooked),
2027 s.print_expr(&out.expr);
2031 self.word_space(":");
2033 self.commasep(Inconsistent, &a.inputs, |s, &(co, ref o)| {
2034 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2040 self.word_space(":");
2042 self.commasep(Inconsistent, &a.clobbers, |s, co| {
2043 s.print_string(&co.as_str(), ast::StrStyle::Cooked);
2046 let mut options = vec![];
2048 options.push("volatile");
2051 options.push("alignstack");
2053 if a.dialect == ast::AsmDialect::Intel {
2054 options.push("intel");
2057 if !options.is_empty() {
2059 self.word_space(":");
2060 self.commasep(Inconsistent, &options, |s, &co| {
2061 s.print_string(co, ast::StrStyle::Cooked);
2067 ast::ExprKind::Mac(ref m) => self.print_mac(m),
2068 ast::ExprKind::Paren(ref e) => {
2070 self.print_inner_attributes_inline(attrs);
2074 ast::ExprKind::Yield(ref e) => {
2075 self.s.word("yield");
2079 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
2084 ast::ExprKind::Try(ref e) => {
2085 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
2088 ast::ExprKind::TryBlock(ref blk) => {
2091 self.print_block_with_attrs(blk, attrs)
2093 ast::ExprKind::Err => {
2095 self.s.word("/*ERROR*/");
2099 self.ann.post(self, AnnNode::Expr(expr));
2103 crate fn print_local_decl(&mut self, loc: &ast::Local) {
2104 self.print_pat(&loc.pat);
2105 if let Some(ref ty) = loc.ty {
2106 self.word_space(":");
2107 self.print_type(ty);
2111 pub fn print_usize(&mut self, i: usize) {
2112 self.s.word(i.to_string())
2115 crate fn print_name(&mut self, name: ast::Name) {
2116 self.s.word(name.to_string());
2117 self.ann.post(self, AnnNode::Name(&name))
2120 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
2122 self.print_type(&qself.ty);
2123 if qself.position > 0 {
2125 self.word_space("as");
2126 let depth = path.segments.len() - qself.position;
2127 self.print_path(path, false, depth);
2131 let item_segment = path.segments.last().unwrap();
2132 self.print_ident(item_segment.ident);
2133 match item_segment.args {
2134 Some(ref args) => self.print_generic_args(args, colons_before_params),
2139 crate fn print_pat(&mut self, pat: &ast::Pat) {
2140 self.maybe_print_comment(pat.span.lo());
2141 self.ann.pre(self, AnnNode::Pat(pat));
2142 /* Pat isn't normalized, but the beauty of it
2143 is that it doesn't matter */
2145 PatKind::Wild => self.s.word("_"),
2146 PatKind::Ident(binding_mode, ident, ref sub) => {
2147 match binding_mode {
2148 ast::BindingMode::ByRef(mutbl) => {
2149 self.word_nbsp("ref");
2150 self.print_mutability(mutbl, false);
2152 ast::BindingMode::ByValue(ast::Mutability::Not) => {}
2153 ast::BindingMode::ByValue(ast::Mutability::Mut) => {
2154 self.word_nbsp("mut");
2157 self.print_ident(ident);
2158 if let Some(ref p) = *sub {
2160 self.s.word_space("@");
2164 PatKind::TupleStruct(ref path, ref elts) => {
2165 self.print_path(path, true, 0);
2167 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2170 PatKind::Or(ref pats) => {
2171 self.strsep("|", true, Inconsistent, &pats[..], |s, p| s.print_pat(p));
2173 PatKind::Path(None, ref path) => {
2174 self.print_path(path, true, 0);
2176 PatKind::Path(Some(ref qself), ref path) => {
2177 self.print_qpath(path, qself, false);
2179 PatKind::Struct(ref path, ref fields, etc) => {
2180 self.print_path(path, true, 0);
2182 self.word_space("{");
2187 s.cbox(INDENT_UNIT);
2188 if !f.is_shorthand {
2189 s.print_ident(f.ident);
2192 s.print_pat(&f.pat);
2198 if !fields.is_empty() {
2199 self.word_space(",");
2206 PatKind::Tuple(ref elts) => {
2208 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2209 if elts.len() == 1 {
2214 PatKind::Box(ref inner) => {
2215 self.s.word("box ");
2216 self.print_pat(inner);
2218 PatKind::Ref(ref inner, mutbl) => {
2220 if mutbl == ast::Mutability::Mut {
2221 self.s.word("mut ");
2223 self.print_pat(inner);
2225 PatKind::Lit(ref e) => self.print_expr(&**e),
2226 PatKind::Range(ref begin, ref end, Spanned { node: ref end_kind, .. }) => {
2227 if let Some(e) = begin {
2232 RangeEnd::Included(RangeSyntax::DotDotDot) => self.s.word("..."),
2233 RangeEnd::Included(RangeSyntax::DotDotEq) => self.s.word("..="),
2234 RangeEnd::Excluded => self.s.word(".."),
2236 if let Some(e) = end {
2240 PatKind::Slice(ref elts) => {
2242 self.commasep(Inconsistent, &elts[..], |s, p| s.print_pat(p));
2245 PatKind::Rest => self.s.word(".."),
2246 PatKind::Paren(ref inner) => {
2248 self.print_pat(inner);
2251 PatKind::Mac(ref m) => self.print_mac(m),
2253 self.ann.post(self, AnnNode::Pat(pat))
2256 fn print_arm(&mut self, arm: &ast::Arm) {
2257 // Note, I have no idea why this check is necessary, but here it is.
2258 if arm.attrs.is_empty() {
2261 self.cbox(INDENT_UNIT);
2263 self.maybe_print_comment(arm.pat.span.lo());
2264 self.print_outer_attributes(&arm.attrs);
2265 self.print_pat(&arm.pat);
2267 if let Some(ref e) = arm.guard {
2268 self.word_space("if");
2272 self.word_space("=>");
2274 match arm.body.kind {
2275 ast::ExprKind::Block(ref blk, opt_label) => {
2276 if let Some(label) = opt_label {
2277 self.print_ident(label.ident);
2278 self.word_space(":");
2281 // The block will close the pattern's ibox.
2282 self.print_block_unclosed_indent(blk);
2284 // If it is a user-provided unsafe block, print a comma after it.
2285 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
2290 self.end(); // Close the ibox for the pattern.
2291 self.print_expr(&arm.body);
2295 self.end(); // Close enclosing cbox.
2298 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2299 match explicit_self.node {
2300 SelfKind::Value(m) => {
2301 self.print_mutability(m, false);
2304 SelfKind::Region(ref lt, m) => {
2306 self.print_opt_lifetime(lt);
2307 self.print_mutability(m, false);
2310 SelfKind::Explicit(ref typ, m) => {
2311 self.print_mutability(m, false);
2312 self.s.word("self");
2313 self.word_space(":");
2314 self.print_type(typ)
2323 generics: &ast::Generics,
2324 vis: &ast::Visibility,
2325 defaultness: ast::Defaultness,
2326 body: Option<&ast::Block>,
2327 attrs: &[ast::Attribute],
2332 self.print_visibility(vis);
2333 self.print_defaultness(defaultness);
2334 self.print_fn(&sig.decl, sig.header, Some(name), generics);
2335 if let Some(body) = body {
2337 self.print_block_with_attrs(body, attrs);
2346 header: ast::FnHeader,
2347 name: Option<ast::Ident>,
2348 generics: &ast::Generics,
2350 self.print_fn_header_info(header);
2351 if let Some(name) = name {
2353 self.print_ident(name);
2355 self.print_generic_params(&generics.params);
2356 self.print_fn_params_and_ret(decl, false);
2357 self.print_where_clause(&generics.where_clause)
2360 crate fn print_fn_params_and_ret(&mut self, decl: &ast::FnDecl, is_closure: bool) {
2361 let (open, close) = if is_closure { ("|", "|") } else { ("(", ")") };
2363 self.commasep(Inconsistent, &decl.inputs, |s, param| s.print_param(param, is_closure));
2365 self.print_fn_ret_ty(&decl.output)
2368 crate fn print_movability(&mut self, movability: ast::Movability) {
2370 ast::Movability::Static => self.word_space("static"),
2371 ast::Movability::Movable => {}
2375 crate fn print_asyncness(&mut self, asyncness: ast::Async) {
2376 if asyncness.is_async() {
2377 self.word_nbsp("async");
2381 crate fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
2382 match capture_clause {
2383 ast::CaptureBy::Value => self.word_space("move"),
2384 ast::CaptureBy::Ref => {}
2388 pub fn print_type_bounds(&mut self, prefix: &'static str, bounds: &[ast::GenericBound]) {
2389 if !bounds.is_empty() {
2390 self.s.word(prefix);
2391 let mut first = true;
2392 for bound in bounds {
2393 if !(first && prefix.is_empty()) {
2399 self.word_space("+");
2403 GenericBound::Trait(tref, modifier) => {
2404 if modifier == &TraitBoundModifier::Maybe {
2407 self.print_poly_trait_ref(tref);
2409 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2415 crate fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2416 self.print_name(lifetime.ident.name)
2419 crate fn print_lifetime_bounds(
2421 lifetime: ast::Lifetime,
2422 bounds: &ast::GenericBounds,
2424 self.print_lifetime(lifetime);
2425 if !bounds.is_empty() {
2427 for (i, bound) in bounds.iter().enumerate() {
2432 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2439 crate fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2440 if generic_params.is_empty() {
2446 self.commasep(Inconsistent, &generic_params, |s, param| {
2447 s.print_outer_attributes_inline(¶m.attrs);
2450 ast::GenericParamKind::Lifetime => {
2451 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2452 s.print_lifetime_bounds(lt, ¶m.bounds)
2454 ast::GenericParamKind::Type { ref default } => {
2455 s.print_ident(param.ident);
2456 s.print_type_bounds(":", ¶m.bounds);
2457 if let Some(ref default) = default {
2460 s.print_type(default)
2463 ast::GenericParamKind::Const { ref ty } => {
2464 s.word_space("const");
2465 s.print_ident(param.ident);
2469 s.print_type_bounds(":", ¶m.bounds)
2477 crate fn print_where_clause(&mut self, where_clause: &ast::WhereClause) {
2478 if where_clause.predicates.is_empty() {
2483 self.word_space("where");
2485 for (i, predicate) in where_clause.predicates.iter().enumerate() {
2487 self.word_space(",");
2491 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
2492 ref bound_generic_params,
2497 self.print_formal_generic_params(bound_generic_params);
2498 self.print_type(bounded_ty);
2499 self.print_type_bounds(":", bounds);
2501 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
2506 self.print_lifetime_bounds(*lifetime, bounds);
2508 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
2513 self.print_type(lhs_ty);
2515 self.word_space("=");
2516 self.print_type(rhs_ty);
2522 crate fn print_use_tree(&mut self, tree: &ast::UseTree) {
2524 ast::UseTreeKind::Simple(rename, ..) => {
2525 self.print_path(&tree.prefix, false, 0);
2526 if let Some(rename) = rename {
2528 self.word_space("as");
2529 self.print_ident(rename);
2532 ast::UseTreeKind::Glob => {
2533 if !tree.prefix.segments.is_empty() {
2534 self.print_path(&tree.prefix, false, 0);
2539 ast::UseTreeKind::Nested(ref items) => {
2540 if tree.prefix.segments.is_empty() {
2543 self.print_path(&tree.prefix, false, 0);
2546 self.commasep(Inconsistent, &items[..], |this, &(ref tree, _)| {
2547 this.print_use_tree(tree)
2554 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2556 ast::Mutability::Mut => self.word_nbsp("mut"),
2557 ast::Mutability::Not => {
2559 self.word_nbsp("const");
2565 crate fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2566 self.print_mutability(mt.mutbl, print_const);
2567 self.print_type(&mt.ty)
2570 crate fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2571 self.ibox(INDENT_UNIT);
2573 self.print_outer_attributes_inline(&input.attrs);
2575 match input.ty.kind {
2576 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2578 if let Some(eself) = input.to_self() {
2579 self.print_explicit_self(&eself);
2581 let invalid = if let PatKind::Ident(_, ident, _) = input.pat.kind {
2582 ident.name == kw::Invalid
2587 self.print_pat(&input.pat);
2591 self.print_type(&input.ty);
2598 crate fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2599 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2600 self.space_if_not_bol();
2601 self.ibox(INDENT_UNIT);
2602 self.word_space("->");
2603 self.print_type(ty);
2605 self.maybe_print_comment(ty.span.lo());
2609 crate fn print_ty_fn(
2612 unsafety: ast::Unsafe,
2614 name: Option<ast::Ident>,
2615 generic_params: &[ast::GenericParam],
2617 self.ibox(INDENT_UNIT);
2618 if !generic_params.is_empty() {
2620 self.print_generic_params(generic_params);
2622 let generics = ast::Generics {
2624 where_clause: ast::WhereClause { predicates: Vec::new(), span: rustc_span::DUMMY_SP },
2625 span: rustc_span::DUMMY_SP,
2627 let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() };
2628 self.print_fn(decl, header, name, &generics);
2632 crate fn maybe_print_trailing_comment(
2634 span: rustc_span::Span,
2635 next_pos: Option<BytePos>,
2637 if let Some(cmnts) = self.comments() {
2638 if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) {
2639 self.print_comment(&cmnt);
2644 crate fn print_remaining_comments(&mut self) {
2645 // If there aren't any remaining comments, then we need to manually
2646 // make sure there is a line break at the end.
2647 if self.next_comment().is_none() {
2650 while let Some(ref cmnt) = self.next_comment() {
2651 self.print_comment(cmnt);
2655 crate fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2656 self.print_constness(header.constness);
2657 self.print_asyncness(header.asyncness);
2658 self.print_unsafety(header.unsafety);
2661 ast::Extern::None => {}
2662 ast::Extern::Implicit => {
2663 self.word_nbsp("extern");
2665 ast::Extern::Explicit(abi) => {
2666 self.word_nbsp("extern");
2667 self.print_literal(&abi.as_lit());
2675 crate fn print_unsafety(&mut self, s: ast::Unsafe) {
2677 ast::Unsafe::No => {}
2678 ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"),
2682 crate fn print_constness(&mut self, s: ast::Const) {
2684 ast::Const::No => {}
2685 ast::Const::Yes(_) => self.word_nbsp("const"),
2689 crate fn print_is_auto(&mut self, s: ast::IsAuto) {
2691 ast::IsAuto::Yes => self.word_nbsp("auto"),
2692 ast::IsAuto::No => {}