1mod expr;
6mod fixup;
7mod item;
8
9use std::borrow::Cow;
10use std::sync::Arc;
11
12use rustc_ast::attr::AttrIdGenerator;
13use rustc_ast::token::{self, CommentKind, Delimiter, DocFragmentKind, Token, TokenKind};
14use rustc_ast::tokenstream::{Spacing, TokenStream, TokenTree};
15use rustc_ast::util::classify;
16use rustc_ast::util::comments::{Comment, CommentStyle};
17use rustc_ast::{
18 self as ast, AttrArgs, AttrKind, BindingMode, BlockCheckMode, ByRef, DelimArgs, GenericArg,
19 GenericBound, InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass,
20 InlineAsmTemplatePiece, PatKind, RangeEnd, RangeSyntax, SelfKind, Term, attr,
21};
22use rustc_span::edition::Edition;
23use rustc_span::source_map::SourceMap;
24use rustc_span::symbol::IdentPrinter;
25use rustc_span::{
26 BytePos, CharPos, DUMMY_SP, FileName, Ident, Pos, Span, Spanned, Symbol, kw, sym,
27};
28
29use crate::pp::Breaks::{Consistent, Inconsistent};
30use crate::pp::{self, BoxMarker, Breaks};
31use crate::pprust::state::fixup::FixupContext;
32
33pub enum MacHeader<'a> {
34 Path(&'a ast::Path),
35 Keyword(&'static str),
36}
37
38pub enum AnnNode<'a> {
39 Ident(&'a Ident),
40 Name(&'a Symbol),
41 Block(&'a ast::Block),
42 Item(&'a ast::Item),
43 SubItem(ast::NodeId),
44 Expr(&'a ast::Expr),
45 Pat(&'a ast::Pat),
46 Crate(&'a ast::Crate),
47}
48
49pub trait PpAnn {
50 fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
51 fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
52}
53
54struct NoAnn;
55
56impl PpAnn for NoAnn {}
57
58pub struct Comments<'a> {
59 sm: &'a SourceMap,
60 reversed_comments: Vec<Comment>,
62}
63
64fn all_whitespace(s: &str, col: CharPos) -> Option<usize> {
68 let mut idx = 0;
69 for (i, ch) in s.char_indices().take(col.to_usize()) {
70 if !ch.is_whitespace() {
71 return None;
72 }
73 idx = i + ch.len_utf8();
74 }
75 Some(idx)
76}
77
78fn trim_whitespace_prefix(s: &str, col: CharPos) -> &str {
79 let len = s.len();
80 match all_whitespace(s, col) {
81 Some(col) => {
82 if col < len {
83 &s[col..]
84 } else {
85 ""
86 }
87 }
88 None => s,
89 }
90}
91
92fn split_block_comment_into_lines(text: &str, col: CharPos) -> Vec<String> {
93 let mut res: Vec<String> = ::alloc::vec::Vec::new()vec![];
94 let mut lines = text.lines();
95 res.extend(lines.next().map(|it| it.to_string()));
97 for line in lines {
99 res.push(trim_whitespace_prefix(line, col).to_string())
100 }
101 res
102}
103
104fn gather_comments(sm: &SourceMap, path: FileName, src: String) -> Vec<Comment> {
105 let sm = SourceMap::new(sm.path_mapping().clone());
106 let source_file = sm.new_source_file(path, src);
107 let text = Arc::clone(&(*source_file.src.as_ref().unwrap()));
108
109 let text: &str = text.as_str();
110 let start_bpos = source_file.start_pos;
111 let mut pos = 0;
112 let mut comments: Vec<Comment> = Vec::new();
113 let mut code_to_the_left = false;
114
115 if let Some(shebang_len) = rustc_lexer::strip_shebang(text) {
116 comments.push(Comment {
117 style: CommentStyle::Isolated,
118 lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[text[..shebang_len].to_string()]))vec![text[..shebang_len].to_string()],
119 pos: start_bpos,
120 });
121 pos += shebang_len;
122 }
123
124 for token in rustc_lexer::tokenize(&text[pos..], rustc_lexer::FrontmatterAllowed::Yes) {
125 let token_text = &text[pos..pos + token.len as usize];
126 match token.kind {
127 rustc_lexer::TokenKind::Whitespace => {
128 if let Some(mut idx) = token_text.find('\n') {
129 code_to_the_left = false;
130 while let Some(next_newline) = &token_text[idx + 1..].find('\n') {
131 idx += 1 + next_newline;
132 comments.push(Comment {
133 style: CommentStyle::BlankLine,
134 lines: ::alloc::vec::Vec::new()vec![],
135 pos: start_bpos + BytePos((pos + idx) as u32),
136 });
137 }
138 }
139 }
140 rustc_lexer::TokenKind::BlockComment { doc_style, .. } => {
141 if doc_style.is_none() {
142 let code_to_the_right = !#[allow(non_exhaustive_omitted_patterns)] match text[pos +
token.len as usize..].chars().next() {
Some('\r' | '\n') => true,
_ => false,
}matches!(
143 text[pos + token.len as usize..].chars().next(),
144 Some('\r' | '\n')
145 );
146 let style = match (code_to_the_left, code_to_the_right) {
147 (_, true) => CommentStyle::Mixed,
148 (false, false) => CommentStyle::Isolated,
149 (true, false) => CommentStyle::Trailing,
150 };
151
152 let pos_in_file = start_bpos + BytePos(pos as u32);
154 let line_begin_in_file = source_file.line_begin_pos(pos_in_file);
155 let line_begin_pos = (line_begin_in_file - start_bpos).to_usize();
156 let col = CharPos(text[line_begin_pos..pos].chars().count());
157
158 let lines = split_block_comment_into_lines(token_text, col);
159 comments.push(Comment { style, lines, pos: pos_in_file })
160 }
161 }
162 rustc_lexer::TokenKind::LineComment { doc_style } => {
163 if doc_style.is_none() {
164 comments.push(Comment {
165 style: if code_to_the_left {
166 CommentStyle::Trailing
167 } else {
168 CommentStyle::Isolated
169 },
170 lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[token_text.to_string()]))vec![token_text.to_string()],
171 pos: start_bpos + BytePos(pos as u32),
172 })
173 }
174 }
175 rustc_lexer::TokenKind::Frontmatter { .. } => {
176 code_to_the_left = false;
177 comments.push(Comment {
178 style: CommentStyle::Isolated,
179 lines: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[token_text.to_string()]))vec![token_text.to_string()],
180 pos: start_bpos + BytePos(pos as u32),
181 });
182 }
183 _ => {
184 code_to_the_left = true;
185 }
186 }
187 pos += token.len as usize;
188 }
189
190 comments
191}
192
193impl<'a> Comments<'a> {
194 pub fn new(sm: &'a SourceMap, filename: FileName, input: String) -> Comments<'a> {
195 let mut comments = gather_comments(sm, filename, input);
196 comments.reverse();
197 Comments { sm, reversed_comments: comments }
198 }
199
200 fn peek(&self) -> Option<&Comment> {
201 self.reversed_comments.last()
202 }
203
204 fn next(&mut self) -> Option<Comment> {
205 self.reversed_comments.pop()
206 }
207
208 fn trailing_comment(
209 &mut self,
210 span: rustc_span::Span,
211 next_pos: Option<BytePos>,
212 ) -> Option<Comment> {
213 if let Some(cmnt) = self.peek() {
214 if cmnt.style != CommentStyle::Trailing {
215 return None;
216 }
217 let span_line = self.sm.lookup_char_pos(span.hi());
218 let comment_line = self.sm.lookup_char_pos(cmnt.pos);
219 let next = next_pos.unwrap_or_else(|| cmnt.pos + BytePos(1));
220 if span.hi() < cmnt.pos && cmnt.pos < next && span_line.line == comment_line.line {
221 return Some(self.next().unwrap());
222 }
223 }
224
225 None
226 }
227}
228
229pub struct State<'a> {
230 pub s: pp::Printer,
231 comments: Option<Comments<'a>>,
232 ann: &'a (dyn PpAnn + 'a),
233 is_sdylib_interface: bool,
234}
235
236const INDENT_UNIT: isize = 4;
237
238pub fn print_crate<'a>(
241 sm: &'a SourceMap,
242 krate: &ast::Crate,
243 filename: FileName,
244 input: String,
245 ann: &'a dyn PpAnn,
246 is_expanded: bool,
247 edition: Edition,
248 g: &AttrIdGenerator,
249) -> String {
250 let mut s = State {
251 s: pp::Printer::new(),
252 comments: Some(Comments::new(sm, filename, input)),
253 ann,
254 is_sdylib_interface: false,
255 };
256
257 print_crate_inner(&mut s, krate, is_expanded, edition, g);
258 s.s.eof()
259}
260
261pub fn print_crate_as_interface(
262 krate: &ast::Crate,
263 edition: Edition,
264 g: &AttrIdGenerator,
265) -> String {
266 let mut s =
267 State { s: pp::Printer::new(), comments: None, ann: &NoAnn, is_sdylib_interface: true };
268
269 print_crate_inner(&mut s, krate, false, edition, g);
270 s.s.eof()
271}
272
273fn print_crate_inner<'a>(
274 s: &mut State<'a>,
275 krate: &ast::Crate,
276 is_expanded: bool,
277 edition: Edition,
278 g: &AttrIdGenerator,
279) {
280 s.maybe_print_shebang();
284
285 if is_expanded && !krate.attrs.iter().any(|attr| attr.has_name(sym::no_core)) {
286 let fake_attr = attr::mk_attr_nested_word(
293 g,
294 ast::AttrStyle::Inner,
295 sym::feature,
296 sym::prelude_import,
297 DUMMY_SP,
298 );
299 s.print_attribute(&fake_attr);
300
301 if edition.is_rust_2015() {
304 let fake_attr = attr::mk_attr_word(g, ast::AttrStyle::Inner, sym::no_std, DUMMY_SP);
306 s.print_attribute(&fake_attr);
307 }
308 }
309
310 s.print_inner_attributes(&krate.attrs);
311 for item in &krate.items {
312 s.print_item(item);
313 }
314 s.print_remaining_comments();
315 s.ann.post(s, AnnNode::Crate(krate));
316}
317
318fn idents_would_merge(tt1: &TokenTree, tt2: &TokenTree) -> bool {
329 fn is_ident_like(tt: &TokenTree) -> bool {
330 #[allow(non_exhaustive_omitted_patterns)] match tt {
TokenTree::Token(Token { kind: token::Ident(..) | token::NtIdent(..), ..
}, _) => true,
_ => false,
}matches!(
331 tt,
332 TokenTree::Token(Token { kind: token::Ident(..) | token::NtIdent(..), .. }, _,)
333 )
334 }
335 is_ident_like(tt1) && is_ident_like(tt2)
336}
337
338fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool {
339 use Delimiter::*;
340 use TokenTree::{Delimited as Del, Token as Tok};
341 use token::*;
342
343 fn is_punct(tt: &TokenTree) -> bool {
344 #[allow(non_exhaustive_omitted_patterns)] match tt {
TokenTree::Token(tok, _) if tok.is_punct() => true,
_ => false,
}matches!(tt, TokenTree::Token(tok, _) if tok.is_punct())
345 }
346
347 match (tt1, tt2) {
351 (Tok(Token { kind: DocComment(CommentKind::Line, ..), .. }, _), _) => false,
353
354 (Tok(Token { kind: Dot, .. }, _), tt2) if !is_punct(tt2) => false,
356
357 (Tok(Token { kind: Dollar, .. }, _), Tok(Token { kind: Ident(..), .. }, _)) => false,
359
360 (tt1, Tok(Token { kind: Comma | Semi | Dot, .. }, _)) if !is_punct(tt1) => false,
364
365 (Tok(Token { kind: Ident(sym, is_raw), span }, _), Tok(Token { kind: Bang, .. }, _))
367 if !Ident::new(*sym, *span).is_reserved() || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::Yes => true,
_ => false,
}matches!(is_raw, IdentIsRaw::Yes) =>
368 {
369 false
370 }
371
372 (Tok(Token { kind: Ident(sym, is_raw), span }, _), Del(_, _, Parenthesis, _))
375 if !Ident::new(*sym, *span).is_reserved()
376 || *sym == kw::Fn
377 || *sym == kw::SelfUpper
378 || *sym == kw::Pub
379 || #[allow(non_exhaustive_omitted_patterns)] match is_raw {
IdentIsRaw::Yes => true,
_ => false,
}matches!(is_raw, IdentIsRaw::Yes) =>
380 {
381 false
382 }
383
384 (Tok(Token { kind: Pound, .. }, _), Del(_, _, Bracket, _)) => false,
386
387 _ => true,
388 }
389}
390
391pub fn doc_comment_to_string(
392 fragment_kind: DocFragmentKind,
393 attr_style: ast::AttrStyle,
394 data: Symbol,
395) -> String {
396 match fragment_kind {
397 DocFragmentKind::Sugared(comment_kind) => match (comment_kind, attr_style) {
398 (CommentKind::Line, ast::AttrStyle::Outer) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("///{0}", data))
})format!("///{data}"),
399 (CommentKind::Line, ast::AttrStyle::Inner) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("//!{0}", data))
})format!("//!{data}"),
400 (CommentKind::Block, ast::AttrStyle::Outer) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/**{0}*/", data))
})format!("/**{data}*/"),
401 (CommentKind::Block, ast::AttrStyle::Inner) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("/*!{0}*/", data))
})format!("/*!{data}*/"),
402 },
403 DocFragmentKind::Raw(_) => {
404 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("#{0}[doc = {1:?}]",
if attr_style == ast::AttrStyle::Inner { "!" } else { "" },
data.to_string()))
})format!(
405 "#{}[doc = {:?}]",
406 if attr_style == ast::AttrStyle::Inner { "!" } else { "" },
407 data.to_string(),
408 )
409 }
410 }
411}
412
413fn literal_to_string(lit: token::Lit) -> String {
414 let token::Lit { kind, symbol, suffix } = lit;
415 let mut out = match kind {
416 token::Byte => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("b\'{0}\'", symbol))
})format!("b'{symbol}'"),
417 token::Char => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\'{0}\'", symbol))
})format!("'{symbol}'"),
418 token::Str => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", symbol))
})format!("\"{symbol}\""),
419 token::StrRaw(n) => {
420 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("r{0}\"{1}\"{0}",
"#".repeat(n as usize), symbol))
})format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
421 }
422 token::ByteStr => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("b\"{0}\"", symbol))
})format!("b\"{symbol}\""),
423 token::ByteStrRaw(n) => {
424 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("br{0}\"{1}\"{0}",
"#".repeat(n as usize), symbol))
})format!("br{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = symbol)
425 }
426 token::CStr => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("c\"{0}\"", symbol))
})format!("c\"{symbol}\""),
427 token::CStrRaw(n) => {
428 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cr{0}\"{1}\"{0}",
"#".repeat(n as usize), symbol))
})format!("cr{delim}\"{symbol}\"{delim}", delim = "#".repeat(n as usize))
429 }
430 token::Integer | token::Float | token::Bool | token::Err(_) => symbol.to_string(),
431 };
432
433 if let Some(suffix) = suffix {
434 out.push_str(suffix.as_str())
435 }
436
437 out
438}
439
440impl std::ops::Deref for State<'_> {
441 type Target = pp::Printer;
442 fn deref(&self) -> &Self::Target {
443 &self.s
444 }
445}
446
447impl std::ops::DerefMut for State<'_> {
448 fn deref_mut(&mut self) -> &mut Self::Target {
449 &mut self.s
450 }
451}
452
453pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::DerefMut {
455 fn comments(&self) -> Option<&Comments<'a>>;
456 fn comments_mut(&mut self) -> Option<&mut Comments<'a>>;
457 fn ann_post(&mut self, ident: Ident);
458 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool);
459
460 fn print_ident(&mut self, ident: Ident) {
461 self.word(IdentPrinter::for_ast_ident(ident, ident.guess_print_mode()).to_string());
462 self.ann_post(ident)
463 }
464
465 fn strsep<'x, T: 'x, F, I>(
466 &mut self,
467 sep: &'static str,
468 space_before: bool,
469 b: Breaks,
470 elts: I,
471 mut op: F,
472 ) where
473 F: FnMut(&mut Self, &T),
474 I: IntoIterator<Item = &'x T>,
475 {
476 let mut it = elts.into_iter();
477
478 let rb = self.rbox(0, b);
479 if let Some(first) = it.next() {
480 op(self, first);
481 for elt in it {
482 if space_before {
483 self.space();
484 }
485 self.word_space(sep);
486 op(self, elt);
487 }
488 }
489 self.end(rb);
490 }
491
492 fn commasep<'x, T: 'x, F, I>(&mut self, b: Breaks, elts: I, op: F)
493 where
494 F: FnMut(&mut Self, &T),
495 I: IntoIterator<Item = &'x T>,
496 {
497 self.strsep(",", false, b, elts, op)
498 }
499
500 fn maybe_print_comment(&mut self, pos: BytePos) -> bool {
501 let mut has_comment = false;
502 while let Some(cmnt) = self.peek_comment() {
503 if cmnt.pos >= pos {
504 break;
505 }
506 has_comment = true;
507 let cmnt = self.next_comment().unwrap();
508 self.print_comment(cmnt);
509 }
510 has_comment
511 }
512
513 fn print_comment(&mut self, cmnt: Comment) {
514 match cmnt.style {
515 CommentStyle::Mixed => {
516 if !self.is_beginning_of_line() {
517 self.zerobreak();
518 }
519 if let Some((last, lines)) = cmnt.lines.split_last() {
520 let ib = self.ibox(0);
521
522 for line in lines {
523 self.word(line.clone());
524 self.hardbreak()
525 }
526
527 self.word(last.clone());
528 self.space();
529
530 self.end(ib);
531 }
532 self.zerobreak()
533 }
534 CommentStyle::Isolated => {
535 self.hardbreak_if_not_bol();
536 for line in &cmnt.lines {
537 if !line.is_empty() {
540 self.word(line.clone());
541 }
542 self.hardbreak();
543 }
544 }
545 CommentStyle::Trailing => {
546 if !self.is_beginning_of_line() {
547 self.word(" ");
548 }
549 if let [line] = cmnt.lines.as_slice() {
550 self.word(line.clone());
551 self.hardbreak()
552 } else {
553 let vb = self.visual_align();
554 for line in &cmnt.lines {
555 if !line.is_empty() {
556 self.word(line.clone());
557 }
558 self.hardbreak();
559 }
560 self.end(vb);
561 }
562 }
563 CommentStyle::BlankLine => {
564 let twice = match self.last_token() {
566 Some(pp::Token::String(s)) => ";" == s,
567 Some(pp::Token::Begin(_)) => true,
568 Some(pp::Token::End) => true,
569 _ => false,
570 };
571 if twice {
572 self.hardbreak();
573 }
574 self.hardbreak();
575 }
576 }
577 }
578
579 fn peek_comment<'b>(&'b self) -> Option<&'b Comment>
580 where
581 'a: 'b,
582 {
583 self.comments().and_then(|c| c.peek())
584 }
585
586 fn next_comment(&mut self) -> Option<Comment> {
587 self.comments_mut().and_then(|c| c.next())
588 }
589
590 fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option<BytePos>) {
591 if let Some(cmnts) = self.comments_mut()
592 && let Some(cmnt) = cmnts.trailing_comment(span, next_pos)
593 {
594 self.print_comment(cmnt);
595 }
596 }
597
598 fn print_remaining_comments(&mut self) {
599 if self.peek_comment().is_none() {
602 self.hardbreak();
603 }
604 while let Some(cmnt) = self.next_comment() {
605 self.print_comment(cmnt)
606 }
607 }
608
609 fn print_string(&mut self, st: &str, style: ast::StrStyle) {
610 let st = match style {
611 ast::StrStyle::Cooked => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\"{0}\"", st.escape_debug()))
})format!("\"{}\"", st.escape_debug()),
612 ast::StrStyle::Raw(n) => {
613 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("r{0}\"{1}\"{0}",
"#".repeat(n as usize), st))
})format!("r{delim}\"{string}\"{delim}", delim = "#".repeat(n as usize), string = st)
614 }
615 };
616 self.word(st)
617 }
618
619 fn maybe_print_shebang(&mut self) {
620 if let Some(cmnt) = self.peek_comment() {
621 if cmnt.style == CommentStyle::Isolated
625 && cmnt.lines.first().map_or(false, |l| l.starts_with("#!"))
626 {
627 let cmnt = self.next_comment().unwrap();
628 self.print_comment(cmnt);
629 }
630 }
631 }
632
633 fn print_inner_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
634 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true)
635 }
636
637 fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> bool {
638 self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true)
639 }
640
641 fn print_either_attributes(
642 &mut self,
643 attrs: &[ast::Attribute],
644 kind: ast::AttrStyle,
645 is_inline: bool,
646 trailing_hardbreak: bool,
647 ) -> bool {
648 let mut printed = false;
649 for attr in attrs {
650 if attr.style == kind {
651 if self.print_attribute_inline(attr, is_inline) {
652 if is_inline {
653 self.nbsp();
654 }
655 printed = true;
656 }
657 }
658 }
659 if printed && trailing_hardbreak && !is_inline {
660 self.hardbreak_if_not_bol();
661 }
662 printed
663 }
664
665 fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) -> bool {
666 use ast::SyntheticAttr::*;
667 match attr.kind {
668 AttrKind::Synthetic(CfgTrace(_) | CfgAttrTrace(_)) => {
669 return false;
672 }
673 AttrKind::Normal(_) | AttrKind::DocComment(..) => {}
674 }
675 if !is_inline {
676 self.hardbreak_if_not_bol();
677 }
678 self.maybe_print_comment(attr.span.lo());
679 match &attr.kind {
680 ast::AttrKind::Normal(normal) => {
681 match attr.style {
682 ast::AttrStyle::Inner => self.word("#!["),
683 ast::AttrStyle::Outer => self.word("#["),
684 }
685 self.print_attr_item(&normal.item, attr.span);
686 self.word("]");
687 }
688 ast::AttrKind::Synthetic(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(), ast::AttrKind::DocComment(comment_kind, data) => {
690 self.word(doc_comment_to_string(
691 DocFragmentKind::Sugared(*comment_kind),
692 attr.style,
693 *data,
694 ));
695 self.hardbreak()
696 }
697 }
698 true
699 }
700
701 fn print_attr_item(&mut self, item: &ast::AttrItem, span: Span) {
702 let ib = self.ibox(0);
703 match item.unsafety {
704 ast::Safety::Unsafe(_) => {
705 self.word("unsafe");
706 self.popen();
707 }
708 ast::Safety::Default | ast::Safety::Safe(_) => {}
709 }
710 match &item.args {
711 AttrArgs::Delimited(DelimArgs { dspan: _, delim, tokens }) => self.print_mac_common(
712 Some(MacHeader::Path(&item.path)),
713 false,
714 None,
715 *delim,
716 None,
717 tokens,
718 true,
719 span,
720 ),
721 AttrArgs::Empty => {
722 self.print_path(&item.path, false, 0);
723 }
724 AttrArgs::Eq { expr, .. } => {
725 self.print_path(&item.path, false, 0);
726 self.space();
727 self.word_space("=");
728 let token_str = self.expr_to_string(expr);
729 self.word(token_str);
730 }
731 }
732 match item.unsafety {
733 ast::Safety::Unsafe(_) => self.pclose(),
734 ast::Safety::Default | ast::Safety::Safe(_) => {}
735 }
736 self.end(ib);
737 }
738
739 fn print_tt(&mut self, tt: &TokenTree, convert_dollar_crate: bool) -> Spacing {
747 match tt {
748 TokenTree::Token(token, spacing) => {
749 let token_str = self.token_to_string_ext(token, convert_dollar_crate);
750 self.word(token_str);
751 match token.kind {
754 token::Ident(name, _) => {
755 self.ann_post(Ident::new(name, token.span));
756 }
757 token::NtIdent(ident, _) => {
758 self.ann_post(ident);
759 }
760 token::Lifetime(name, _) => {
761 self.ann_post(Ident::new(name, token.span));
762 }
763 token::NtLifetime(ident, _) => {
764 self.ann_post(ident);
765 }
766 _ => {}
767 }
768 if let token::DocComment(..) = token.kind {
769 self.hardbreak()
770 }
771 *spacing
772 }
773 TokenTree::Delimited(dspan, spacing, delim, tts) => {
774 self.print_mac_common(
775 None,
776 false,
777 None,
778 *delim,
779 Some(spacing.open),
780 tts,
781 convert_dollar_crate,
782 dspan.entire(),
783 );
784 spacing.close
785 }
786 }
787 }
788
789 fn print_tts(&mut self, tts: &TokenStream, convert_dollar_crate: bool) {
819 let mut iter = tts.iter().peekable();
820 while let Some(tt) = iter.next() {
821 let spacing = self.print_tt(tt, convert_dollar_crate);
822 if let Some(next) = iter.peek() {
823 if spacing == Spacing::Alone && space_between(tt, next) {
824 self.space();
825 } else if spacing != Spacing::Alone && idents_would_merge(tt, next) {
826 self.space();
832 }
833 }
834 }
835 }
836
837 fn print_mac_common(
838 &mut self,
839 header: Option<MacHeader<'_>>,
840 has_bang: bool,
841 ident: Option<Ident>,
842 delim: Delimiter,
843 open_spacing: Option<Spacing>,
844 tts: &TokenStream,
845 convert_dollar_crate: bool,
846 span: Span,
847 ) {
848 let cb = (delim == Delimiter::Brace).then(|| self.cbox(INDENT_UNIT));
849 match header {
850 Some(MacHeader::Path(path)) => self.print_path(path, false, 0),
851 Some(MacHeader::Keyword(kw)) => self.word(kw),
852 None => {}
853 }
854 if has_bang {
855 self.word("!");
856 }
857 if let Some(ident) = ident {
858 self.nbsp();
859 self.print_ident(ident);
860 }
861 match delim {
862 Delimiter::Brace => {
863 if header.is_some() || has_bang || ident.is_some() {
864 self.nbsp();
865 }
866 self.word("{");
867
868 let open_space = (open_spacing == None || open_spacing == Some(Spacing::Alone))
870 && !tts.is_empty();
871 if open_space {
872 self.space();
873 }
874 let ib = self.ibox(0);
875 self.print_tts(tts, convert_dollar_crate);
876 self.end(ib);
877
878 self.bclose(span, !open_space, cb.unwrap());
883 }
884 delim => {
885 let token_str = self.token_kind_to_string(&delim.as_open_token_kind());
888 self.word(token_str);
889 let ib = self.ibox(0);
890 self.print_tts(tts, convert_dollar_crate);
891 self.end(ib);
892 let token_str = self.token_kind_to_string(&delim.as_close_token_kind());
893 self.word(token_str);
894 }
895 }
896 }
897
898 fn print_mac_def(
899 &mut self,
900 macro_def: &ast::MacroDef,
901 ident: &Ident,
902 sp: Span,
903 print_visibility: impl FnOnce(&mut Self),
904 ) {
905 if let Some(eii_decl) = ¯o_def.eii_declaration {
906 self.word("#[eii_declaration(");
907 self.print_path(&eii_decl.foreign_item, false, 0);
908 if eii_decl.impl_unsafe {
909 self.word(",");
910 self.space();
911 self.word("unsafe");
912 }
913 self.word(")]");
914 self.hardbreak();
915 }
916 let (kw, has_bang) = if macro_def.macro_rules {
917 ("macro_rules", true)
918 } else {
919 print_visibility(self);
920 ("macro", false)
921 };
922 self.print_mac_common(
923 Some(MacHeader::Keyword(kw)),
924 has_bang,
925 Some(*ident),
926 macro_def.body.delim,
927 None,
928 ¯o_def.body.tokens,
929 true,
930 sp,
931 );
932 if macro_def.body.need_semicolon() {
933 self.word(";");
934 }
935 }
936
937 fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) {
938 self.maybe_print_comment(path.span.lo());
939
940 for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() {
941 if i > 0 {
942 self.word("::")
943 }
944 self.print_path_segment(segment, colons_before_params);
945 }
946 }
947
948 fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) {
949 if segment.ident.name != kw::PathRoot {
950 self.print_ident(segment.ident);
951 if let Some(args) = &segment.args {
952 self.print_generic_args(args, colons_before_params);
953 }
954 }
955 }
956
957 fn head<S: Into<Cow<'static, str>>>(&mut self, w: S) -> (BoxMarker, BoxMarker) {
958 let w = w.into();
959 let cb = self.cbox(INDENT_UNIT);
961 let ib = self.ibox(0);
963 if !w.is_empty() {
965 self.word_nbsp(w);
966 }
967 (cb, ib)
968 }
969
970 fn bopen(&mut self, ib: BoxMarker) {
971 self.word("{");
972 self.end(ib);
973 }
974
975 fn bclose_maybe_open(&mut self, span: rustc_span::Span, no_space: bool, cb: Option<BoxMarker>) {
976 let has_comment = self.maybe_print_comment(span.hi());
977 if !no_space || has_comment {
978 self.break_offset_if_not_bol(1, -INDENT_UNIT);
979 }
980 self.word("}");
981 if let Some(cb) = cb {
982 self.end(cb);
983 }
984 }
985
986 fn bclose(&mut self, span: rustc_span::Span, no_space: bool, cb: BoxMarker) {
987 let cb = Some(cb);
988 self.bclose_maybe_open(span, no_space, cb)
989 }
990
991 fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
992 if !self.is_beginning_of_line() {
993 self.break_offset(n, off)
994 } else if off != 0 {
995 if let Some(last_token) = self.last_token_still_buffered() {
996 if last_token.is_hardbreak_tok() {
997 self.replace_last_token_still_buffered(pp::Printer::hardbreak_tok_offset(off));
1001 }
1002 }
1003 }
1004 }
1005
1006 fn token_kind_to_string(&self, tok: &TokenKind) -> Cow<'static, str> {
1008 self.token_kind_to_string_ext(tok, None)
1009 }
1010
1011 fn token_kind_to_string_ext(
1012 &self,
1013 tok: &TokenKind,
1014 convert_dollar_crate: Option<Span>,
1015 ) -> Cow<'static, str> {
1016 match *tok {
1017 token::Eq => "=".into(),
1018 token::Lt => "<".into(),
1019 token::Le => "<=".into(),
1020 token::EqEq => "==".into(),
1021 token::Ne => "!=".into(),
1022 token::Ge => ">=".into(),
1023 token::Gt => ">".into(),
1024 token::Bang => "!".into(),
1025 token::Tilde => "~".into(),
1026 token::OrOr => "||".into(),
1027 token::AndAnd => "&&".into(),
1028 token::Plus => "+".into(),
1029 token::Minus => "-".into(),
1030 token::Star => "*".into(),
1031 token::Slash => "/".into(),
1032 token::Percent => "%".into(),
1033 token::Caret => "^".into(),
1034 token::And => "&".into(),
1035 token::Or => "|".into(),
1036 token::Shl => "<<".into(),
1037 token::Shr => ">>".into(),
1038 token::PlusEq => "+=".into(),
1039 token::MinusEq => "-=".into(),
1040 token::StarEq => "*=".into(),
1041 token::SlashEq => "/=".into(),
1042 token::PercentEq => "%=".into(),
1043 token::CaretEq => "^=".into(),
1044 token::AndEq => "&=".into(),
1045 token::OrEq => "|=".into(),
1046 token::ShlEq => "<<=".into(),
1047 token::ShrEq => ">>=".into(),
1048
1049 token::At => "@".into(),
1051 token::Dot => ".".into(),
1052 token::DotDot => "..".into(),
1053 token::DotDotDot => "...".into(),
1054 token::DotDotEq => "..=".into(),
1055 token::Comma => ",".into(),
1056 token::Semi => ";".into(),
1057 token::Colon => ":".into(),
1058 token::PathSep => "::".into(),
1059 token::RArrow => "->".into(),
1060 token::LArrow => "<-".into(),
1061 token::FatArrow => "=>".into(),
1062 token::OpenParen => "(".into(),
1063 token::CloseParen => ")".into(),
1064 token::OpenBracket => "[".into(),
1065 token::CloseBracket => "]".into(),
1066 token::OpenBrace => "{".into(),
1067 token::CloseBrace => "}".into(),
1068 token::OpenInvisible(_) | token::CloseInvisible(_) => "".into(),
1069 token::Pound => "#".into(),
1070 token::Dollar => "$".into(),
1071 token::Question => "?".into(),
1072 token::SingleQuote => "'".into(),
1073
1074 token::Literal(lit) => literal_to_string(lit).into(),
1076
1077 token::Ident(name, is_raw) => {
1079 IdentPrinter::new(name, is_raw.to_print_mode_ident(), convert_dollar_crate)
1080 .to_string()
1081 .into()
1082 }
1083 token::NtIdent(ident, is_raw) => {
1084 IdentPrinter::for_ast_ident(ident, is_raw.to_print_mode_ident()).to_string().into()
1085 }
1086
1087 token::Lifetime(name, is_raw) | token::NtLifetime(Ident { name, .. }, is_raw) => {
1088 IdentPrinter::new(name, is_raw.to_print_mode_lifetime(), None).to_string().into()
1089 }
1090
1091 token::DocComment(comment_kind, attr_style, data) => {
1093 doc_comment_to_string(DocFragmentKind::Sugared(comment_kind), attr_style, data)
1094 .into()
1095 }
1096 token::Eof => "<eof>".into(),
1097 }
1098 }
1099
1100 fn token_to_string(&self, token: &Token) -> Cow<'static, str> {
1102 self.token_to_string_ext(token, false)
1103 }
1104
1105 fn token_to_string_ext(&self, token: &Token, convert_dollar_crate: bool) -> Cow<'static, str> {
1106 let convert_dollar_crate = convert_dollar_crate.then_some(token.span);
1107 self.token_kind_to_string_ext(&token.kind, convert_dollar_crate)
1108 }
1109
1110 fn ty_to_string(&self, ty: &ast::Ty) -> String {
1111 Self::to_string(|s| s.print_type(ty))
1112 }
1113
1114 fn pat_to_string(&self, pat: &ast::Pat) -> String {
1115 Self::to_string(|s| s.print_pat(pat))
1116 }
1117
1118 fn expr_to_string(&self, e: &ast::Expr) -> String {
1119 Self::to_string(|s| s.print_expr(e, FixupContext::default()))
1120 }
1121
1122 fn meta_item_lit_to_string(&self, lit: &ast::MetaItemLit) -> String {
1123 Self::to_string(|s| s.print_meta_item_lit(lit))
1124 }
1125
1126 fn stmt_to_string(&self, stmt: &ast::Stmt) -> String {
1127 Self::to_string(|s| s.print_stmt(stmt))
1128 }
1129
1130 fn item_to_string(&self, i: &ast::Item) -> String {
1131 Self::to_string(|s| s.print_item(i))
1132 }
1133
1134 fn assoc_item_to_string(&self, i: &ast::AssocItem) -> String {
1135 Self::to_string(|s| s.print_assoc_item(i))
1136 }
1137
1138 fn foreign_item_to_string(&self, i: &ast::ForeignItem) -> String {
1139 Self::to_string(|s| s.print_foreign_item(i))
1140 }
1141
1142 fn path_to_string(&self, p: &ast::Path) -> String {
1143 Self::to_string(|s| s.print_path(p, false, 0))
1144 }
1145
1146 fn vis_to_string(&self, v: &ast::Visibility) -> String {
1147 Self::to_string(|s| s.print_visibility(v))
1148 }
1149
1150 fn impl_restriction_to_string(&self, r: &ast::ImplRestriction) -> String {
1151 Self::to_string(|s| s.print_impl_restriction(r))
1152 }
1153
1154 fn mut_restriction_to_string(&self, r: &ast::MutRestriction) -> String {
1155 Self::to_string(|s| s.print_mut_restriction(r))
1156 }
1157
1158 fn block_to_string(&self, blk: &ast::Block) -> String {
1159 Self::to_string(|s| {
1160 let (cb, ib) = s.head("");
1161 s.print_block(blk, cb, ib)
1162 })
1163 }
1164
1165 fn attr_item_to_string(&self, ai: &ast::AttrItem) -> String {
1166 Self::to_string(|s| s.print_attr_item(ai, ai.path.span))
1167 }
1168
1169 fn tts_to_string(&self, tokens: &TokenStream) -> String {
1170 Self::to_string(|s| s.print_tts(tokens, false))
1171 }
1172
1173 fn to_string(f: impl FnOnce(&mut State<'_>)) -> String {
1174 let mut printer = State::new();
1175 f(&mut printer);
1176 printer.s.eof()
1177 }
1178}
1179
1180impl<'a> PrintState<'a> for State<'a> {
1181 fn comments(&self) -> Option<&Comments<'a>> {
1182 self.comments.as_ref()
1183 }
1184
1185 fn comments_mut(&mut self) -> Option<&mut Comments<'a>> {
1186 self.comments.as_mut()
1187 }
1188
1189 fn ann_post(&mut self, ident: Ident) {
1190 self.ann.post(self, AnnNode::Ident(&ident));
1191 }
1192
1193 fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) {
1194 if colons_before_params {
1195 self.word("::")
1196 }
1197
1198 match args {
1199 ast::GenericArgs::AngleBracketed(data) => {
1200 self.word("<");
1201 self.commasep(Inconsistent, &data.args, |s, arg| match arg {
1202 ast::AngleBracketedArg::Arg(a) => s.print_generic_arg(a),
1203 ast::AngleBracketedArg::Constraint(c) => s.print_assoc_item_constraint(c),
1204 });
1205 self.word(">")
1206 }
1207
1208 ast::GenericArgs::Parenthesized(data) => {
1209 self.word("(");
1210 self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(ty));
1211 self.word(")");
1212 self.print_fn_ret_ty(&data.output);
1213 }
1214 ast::GenericArgs::ParenthesizedElided(_) => {
1215 self.word("(");
1216 self.word("..");
1217 self.word(")");
1218 }
1219 }
1220 }
1221}
1222
1223impl<'a> State<'a> {
1224 pub fn new() -> State<'a> {
1225 State { s: pp::Printer::new(), comments: None, ann: &NoAnn, is_sdylib_interface: false }
1226 }
1227
1228 fn commasep_cmnt<T, F, G>(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G)
1229 where
1230 F: FnMut(&mut State<'_>, &T),
1231 G: FnMut(&T) -> rustc_span::Span,
1232 {
1233 let rb = self.rbox(0, b);
1234 let len = elts.len();
1235 let mut i = 0;
1236 for elt in elts {
1237 self.maybe_print_comment(get_span(elt).hi());
1238 op(self, elt);
1239 i += 1;
1240 if i < len {
1241 self.word(",");
1242 self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi()));
1243 self.space_if_not_bol();
1244 }
1245 }
1246 self.end(rb);
1247 }
1248
1249 fn commasep_exprs(&mut self, b: Breaks, exprs: &[Box<ast::Expr>]) {
1250 self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e, FixupContext::default()), |e| e.span)
1251 }
1252
1253 pub fn print_opt_lifetime(&mut self, lifetime: &Option<ast::Lifetime>) {
1254 if let Some(lt) = *lifetime {
1255 self.print_lifetime(lt);
1256 self.nbsp();
1257 }
1258 }
1259
1260 fn print_view(&mut self, fields: &[Ident]) {
1261 self.word(".{");
1262
1263 if !fields.is_empty() {
1264 self.space();
1265 self.commasep(Consistent, fields, |s, field| {
1266 s.print_ident(*field);
1267 });
1268 self.space();
1269 }
1270
1271 self.word("}");
1272 }
1273
1274 pub fn print_assoc_item_constraint(&mut self, constraint: &ast::AssocItemConstraint) {
1275 self.print_ident(constraint.ident);
1276 if let Some(args) = constraint.gen_args.as_ref() {
1277 self.print_generic_args(args, false)
1278 }
1279 self.space();
1280 match &constraint.kind {
1281 ast::AssocItemConstraintKind::Equality { term } => {
1282 self.word_space("=");
1283 match term {
1284 Term::Ty(ty) => self.print_type(ty),
1285 Term::Const(c) => self.print_expr_anon_const(c, &[]),
1286 }
1287 }
1288 ast::AssocItemConstraintKind::Bound { bounds } => {
1289 if !bounds.is_empty() {
1290 self.word_nbsp(":");
1291 self.print_type_bounds(bounds);
1292 }
1293 }
1294 }
1295 }
1296
1297 pub fn print_generic_arg(&mut self, generic_arg: &GenericArg) {
1298 match generic_arg {
1299 GenericArg::Lifetime(lt) => self.print_lifetime(*lt),
1300 GenericArg::Type(ty) => self.print_type(ty),
1301 GenericArg::Const(ct) => self.print_expr(&ct.value, FixupContext::default()),
1302 }
1303 }
1304
1305 pub fn print_ty_pat(&mut self, pat: &ast::TyPat) {
1306 match &pat.kind {
1307 rustc_ast::TyPatKind::Range(start, end, include_end) => {
1308 if let Some(start) = start {
1309 self.print_expr_anon_const(start, &[]);
1310 }
1311 self.word("..");
1312 if let Some(end) = end {
1313 if let RangeEnd::Included(_) = include_end.node {
1314 self.word("=");
1315 }
1316 self.print_expr_anon_const(end, &[]);
1317 }
1318 }
1319 rustc_ast::TyPatKind::NotNull => self.word("!null"),
1320 rustc_ast::TyPatKind::Or(variants) => {
1321 let mut first = true;
1322 for pat in variants {
1323 if first {
1324 first = false
1325 } else {
1326 self.word(" | ");
1327 }
1328 self.print_ty_pat(pat);
1329 }
1330 }
1331 rustc_ast::TyPatKind::Err(_) => {
1332 self.popen();
1333 self.word("/*ERROR*/");
1334 self.pclose();
1335 }
1336 }
1337 }
1338
1339 pub fn print_type(&mut self, ty: &ast::Ty) {
1340 self.maybe_print_comment(ty.span.lo());
1341 let ib = self.ibox(0);
1342 match &ty.kind {
1343 ast::TyKind::Slice(ty) => {
1344 self.word("[");
1345 self.print_type(ty);
1346 self.word("]");
1347 }
1348 ast::TyKind::Ptr(mt) => {
1349 self.word("*");
1350 self.print_mt(mt, true);
1351 }
1352 ast::TyKind::Ref(lifetime, mt) => {
1353 self.word("&");
1354 self.print_opt_lifetime(lifetime);
1355 self.print_mt(mt, false);
1356 }
1357 ast::TyKind::PinnedRef(lifetime, mt) => {
1358 self.word("&");
1359 self.print_opt_lifetime(lifetime);
1360 self.word("pin ");
1361 self.print_mt(mt, true);
1362 }
1363 ast::TyKind::Never => {
1364 self.word("!");
1365 }
1366 ast::TyKind::Tup(elts) => {
1367 self.popen();
1368 self.commasep(Inconsistent, elts, |s, ty| s.print_type(ty));
1369 if elts.len() == 1 {
1370 self.word(",");
1371 }
1372 self.pclose();
1373 }
1374 ast::TyKind::Paren(typ) => {
1375 self.popen();
1376 self.print_type(typ);
1377 self.pclose();
1378 }
1379 ast::TyKind::FnPtr(f) => {
1380 self.print_ty_fn(f.ext, f.safety, &f.decl, None, &f.generic_params);
1381 }
1382 ast::TyKind::UnsafeBinder(f) => {
1383 let ib = self.ibox(INDENT_UNIT);
1384 self.word("unsafe");
1385 self.print_generic_params(&f.generic_params);
1386 self.nbsp();
1387 self.print_type(&f.inner_ty);
1388 self.end(ib);
1389 }
1390 ast::TyKind::Path(None, path) => {
1391 self.print_path(path, false, 0);
1392 }
1393 ast::TyKind::Path(Some(qself), path) => self.print_qpath(path, qself, false),
1394 ast::TyKind::TraitObject(bounds, syntax) => {
1395 match syntax {
1396 ast::TraitObjectSyntax::Dyn => self.word_nbsp("dyn"),
1397 ast::TraitObjectSyntax::None => {}
1398 }
1399 self.print_type_bounds(bounds);
1400 }
1401 ast::TyKind::ImplTrait(_, bounds) => {
1402 self.word_nbsp("impl");
1403 self.print_type_bounds(bounds);
1404 }
1405 ast::TyKind::Array(ty, length) => {
1406 self.word("[");
1407 self.print_type(ty);
1408 self.word("; ");
1409 self.print_expr(&length.value, FixupContext::default());
1410 self.word("]");
1411 }
1412 ast::TyKind::Infer => {
1413 self.word("_");
1414 }
1415 ast::TyKind::Err(_) => {
1416 self.popen();
1417 self.word("/*ERROR*/");
1418 self.pclose();
1419 }
1420 ast::TyKind::Dummy => {
1421 self.popen();
1422 self.word("/*DUMMY*/");
1423 self.pclose();
1424 }
1425 ast::TyKind::ImplicitSelf => {
1426 self.word("Self");
1427 }
1428 ast::TyKind::MacCall(m) => {
1429 self.print_mac(m);
1430 }
1431 ast::TyKind::CVarArgs => {
1432 self.word("...");
1433 }
1434 ast::TyKind::Pat(ty, pat) => {
1435 self.print_type(ty);
1436 self.word(" is ");
1437 self.print_ty_pat(pat);
1438 }
1439 ast::TyKind::FieldOf(ty, variant, field) => {
1440 self.word("builtin # field_of");
1441 self.popen();
1442 let ib = self.ibox(0);
1443 self.print_type(ty);
1444 self.word(",");
1445 self.space();
1446
1447 if let Some(variant) = variant {
1448 self.print_ident(*variant);
1449 self.word(".");
1450 }
1451 self.print_ident(*field);
1452
1453 self.end(ib);
1454 self.pclose();
1455 }
1456 ast::TyKind::View(ty, fields) => {
1457 self.print_type(ty);
1458 self.print_view(fields);
1459 }
1460 ast::TyKind::DirectConstArg(expr) => {
1461 self.word_nbsp("core::direct_const_arg!");
1462 self.popen();
1463 self.print_expr(expr, FixupContext::default());
1464 self.pclose();
1465 }
1466 }
1467 self.end(ib);
1468 }
1469
1470 fn print_trait_ref(&mut self, t: &ast::TraitRef) {
1471 self.print_path(&t.path, false, 0)
1472 }
1473
1474 fn print_formal_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
1475 if !generic_params.is_empty() {
1476 self.word("for");
1477 self.print_generic_params(generic_params);
1478 self.nbsp();
1479 }
1480 }
1481
1482 fn print_poly_trait_ref(&mut self, t: &ast::PolyTraitRef) {
1483 if let ast::Parens::Yes = t.parens {
1484 self.popen();
1485 }
1486 self.print_formal_generic_params(&t.bound_generic_params);
1487
1488 let ast::TraitBoundModifiers { constness, asyncness, polarity } = t.modifiers;
1489 match constness {
1490 ast::BoundConstness::Never => {}
1491 ast::BoundConstness::Always(_) | ast::BoundConstness::Maybe(_) => {
1492 self.word_space(constness.as_str());
1493 }
1494 }
1495 match asyncness {
1496 ast::BoundAsyncness::Normal => {}
1497 ast::BoundAsyncness::Async(_) => {
1498 self.word_space(asyncness.as_str());
1499 }
1500 }
1501 match polarity {
1502 ast::BoundPolarity::Positive => {}
1503 ast::BoundPolarity::Negative(_) | ast::BoundPolarity::Maybe(_) => {
1504 self.word(polarity.as_str());
1505 }
1506 }
1507
1508 self.print_trait_ref(&t.trait_ref);
1509 if let ast::Parens::Yes = t.parens {
1510 self.pclose();
1511 }
1512 }
1513
1514 fn print_stmt(&mut self, st: &ast::Stmt) {
1515 self.maybe_print_comment(st.span.lo());
1516 match &st.kind {
1517 ast::StmtKind::Let(loc) => {
1518 self.print_outer_attributes(&loc.attrs);
1519 self.space_if_not_bol();
1520 let ib1 = self.ibox(INDENT_UNIT);
1521 if loc.super_.is_some() {
1522 self.word_nbsp("super");
1523 }
1524 self.word_nbsp("let");
1525
1526 let ib2 = self.ibox(INDENT_UNIT);
1527 self.print_local_decl(loc);
1528 self.end(ib2);
1529 if let Some((init, els)) = loc.kind.init_else_opt() {
1530 self.nbsp();
1531 self.word_space("=");
1532 self.print_expr_cond_paren(
1533 init,
1534 els.is_some() && classify::expr_trailing_brace(init).is_some(),
1535 FixupContext::default(),
1536 );
1537 if let Some(els) = els {
1538 let cb = self.cbox(INDENT_UNIT);
1539 let ib = self.ibox(INDENT_UNIT);
1540 self.word(" else ");
1541 self.print_block(els, cb, ib);
1542 }
1543 }
1544 self.word(";");
1545 self.end(ib1);
1546 }
1547 ast::StmtKind::Item(item) => self.print_item(item),
1548 ast::StmtKind::Expr(expr) => {
1549 self.space_if_not_bol();
1550 self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1551 if classify::expr_requires_semi_to_be_stmt(expr) {
1552 self.word(";");
1553 }
1554 }
1555 ast::StmtKind::Semi(expr) => {
1556 self.space_if_not_bol();
1557 self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1558 self.word(";");
1559 }
1560 ast::StmtKind::Empty => {
1561 self.space_if_not_bol();
1562 self.word(";");
1563 }
1564 ast::StmtKind::MacCall(mac) => {
1565 self.space_if_not_bol();
1566 self.print_outer_attributes(&mac.attrs);
1567 self.print_mac(&mac.mac);
1568 if mac.style == ast::MacStmtStyle::Semicolon {
1569 self.word(";");
1570 }
1571 }
1572 }
1573 self.maybe_print_trailing_comment(st.span, None)
1574 }
1575
1576 fn print_block(&mut self, blk: &ast::Block, cb: BoxMarker, ib: BoxMarker) {
1577 self.print_block_with_attrs(blk, &[], cb, ib)
1578 }
1579
1580 fn print_block_unclosed_indent(&mut self, blk: &ast::Block, ib: BoxMarker) {
1581 self.print_block_maybe_unclosed(blk, &[], None, ib)
1582 }
1583
1584 fn print_block_with_attrs(
1585 &mut self,
1586 blk: &ast::Block,
1587 attrs: &[ast::Attribute],
1588 cb: BoxMarker,
1589 ib: BoxMarker,
1590 ) {
1591 self.print_block_maybe_unclosed(blk, attrs, Some(cb), ib)
1592 }
1593
1594 fn print_block_maybe_unclosed(
1595 &mut self,
1596 blk: &ast::Block,
1597 attrs: &[ast::Attribute],
1598 cb: Option<BoxMarker>,
1599 ib: BoxMarker,
1600 ) {
1601 match blk.rules {
1602 BlockCheckMode::Unsafe(..) => self.word_space("unsafe"),
1603 BlockCheckMode::Default => (),
1604 }
1605 self.maybe_print_comment(blk.span.lo());
1606 self.ann.pre(self, AnnNode::Block(blk));
1607 self.bopen(ib);
1608
1609 let has_attrs = self.print_inner_attributes(attrs);
1610
1611 for (i, st) in blk.stmts.iter().enumerate() {
1612 match &st.kind {
1613 ast::StmtKind::Expr(expr) if i == blk.stmts.len() - 1 => {
1614 self.maybe_print_comment(st.span.lo());
1615 self.space_if_not_bol();
1616 self.print_expr_outer_attr_style(expr, false, FixupContext::new_stmt());
1617 self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()));
1618 }
1619 _ => self.print_stmt(st),
1620 }
1621 }
1622
1623 let no_space = !has_attrs && blk.stmts.is_empty();
1624 self.bclose_maybe_open(blk.span, no_space, cb);
1625 self.ann.post(self, AnnNode::Block(blk))
1626 }
1627
1628 fn print_let(&mut self, pat: &ast::Pat, expr: &ast::Expr, fixup: FixupContext) {
1654 self.word("let ");
1655 self.print_pat(pat);
1656 self.space();
1657 self.word_space("=");
1658 self.print_expr_cond_paren(
1659 expr,
1660 fixup.needs_par_as_let_scrutinee(expr),
1661 FixupContext::default(),
1662 );
1663 }
1664
1665 fn print_mac(&mut self, m: &ast::MacCall) {
1666 self.print_mac_common(
1667 Some(MacHeader::Path(&m.path)),
1668 true,
1669 None,
1670 m.args.delim,
1671 None,
1672 &m.args.tokens,
1673 true,
1674 m.span(),
1675 );
1676 }
1677
1678 fn inline_asm_template_and_operands<'asm>(
1679 asm: &'asm ast::InlineAsm,
1680 ) -> (String, Vec<&'asm InlineAsmOperand>) {
1681 fn is_explicit_reg(op: &InlineAsmOperand) -> bool {
1682 match op {
1683 InlineAsmOperand::In { reg, .. }
1684 | InlineAsmOperand::Out { reg, .. }
1685 | InlineAsmOperand::InOut { reg, .. }
1686 | InlineAsmOperand::SplitInOut { reg, .. } => {
1687 #[allow(non_exhaustive_omitted_patterns)] match reg {
InlineAsmRegOrRegClass::Reg(_) => true,
_ => false,
}matches!(reg, InlineAsmRegOrRegClass::Reg(_))
1688 }
1689 InlineAsmOperand::Const { .. }
1690 | InlineAsmOperand::Sym { .. }
1691 | InlineAsmOperand::Label { .. } => false,
1692 }
1693 }
1694
1695 let needs_reorder = {
1702 let mut seen_explicit = false;
1703 asm.operands.iter().any(|(op, _)| {
1704 if is_explicit_reg(op) {
1705 seen_explicit = true;
1706 false
1707 } else {
1708 seen_explicit
1709 }
1710 })
1711 };
1712
1713 if !needs_reorder {
1714 let template = InlineAsmTemplatePiece::to_string(&asm.template);
1715 let operands = asm.operands.iter().map(|(op, _)| op).collect();
1716 return (template, operands);
1717 }
1718
1719 let mut non_explicit = Vec::new();
1720 let mut explicit = Vec::new();
1721 for (i, (op, _)) in asm.operands.iter().enumerate() {
1722 if is_explicit_reg(op) {
1723 explicit.push(i);
1724 } else {
1725 non_explicit.push(i);
1726 }
1727 }
1728 let order = non_explicit.into_iter().chain(explicit).collect::<Vec<_>>();
1729
1730 let mut old_to_new = ::alloc::vec::from_elem(0usize, asm.operands.len())vec![0usize; asm.operands.len()];
1732 for (new_idx, old_idx) in order.iter().copied().enumerate() {
1733 old_to_new[old_idx] = new_idx;
1734 }
1735
1736 let remapped = asm
1739 .template
1740 .iter()
1741 .map(|piece| match piece {
1742 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } => {
1743 InlineAsmTemplatePiece::Placeholder {
1744 operand_idx: old_to_new[*operand_idx],
1745 modifier: *modifier,
1746 span: *span,
1747 }
1748 }
1749 other => other.clone(),
1750 })
1751 .collect::<Vec<_>>();
1752 let template = InlineAsmTemplatePiece::to_string(&remapped);
1753 let operands = order.iter().map(|&idx| &asm.operands[idx].0).collect();
1754 (template, operands)
1755 }
1756
1757 fn print_inline_asm(&mut self, asm: &ast::InlineAsm) {
1758 enum AsmArg<'a> {
1759 Template(String),
1760 Operand(&'a InlineAsmOperand),
1761 ClobberAbi(Symbol),
1762 Options(InlineAsmOptions),
1763 }
1764
1765 let (template, operands) = Self::inline_asm_template_and_operands(asm);
1766 let mut args = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[AsmArg::Template(template)]))vec![AsmArg::Template(template)];
1767 args.extend(operands.into_iter().map(AsmArg::Operand));
1768 for (abi, _) in &asm.clobber_abis {
1769 args.push(AsmArg::ClobberAbi(*abi));
1770 }
1771 if !asm.options.is_empty() {
1772 args.push(AsmArg::Options(asm.options));
1773 }
1774
1775 self.popen();
1776 self.commasep(Consistent, &args, |s, arg| match arg {
1777 AsmArg::Template(template) => s.print_string(template, ast::StrStyle::Cooked),
1778 AsmArg::Operand(op) => {
1779 let print_reg_or_class = |s: &mut Self, r: &InlineAsmRegOrRegClass| match r {
1780 InlineAsmRegOrRegClass::Reg(r) => s.print_symbol(*r, ast::StrStyle::Cooked),
1781 InlineAsmRegOrRegClass::RegClass(r) => s.word(r.to_string()),
1782 };
1783 match op {
1784 InlineAsmOperand::In { reg, expr } => {
1785 s.word("in");
1786 s.popen();
1787 print_reg_or_class(s, reg);
1788 s.pclose();
1789 s.space();
1790 s.print_expr(expr, FixupContext::default());
1791 }
1792 InlineAsmOperand::Out { reg, late, expr } => {
1793 s.word(if *late { "lateout" } else { "out" });
1794 s.popen();
1795 print_reg_or_class(s, reg);
1796 s.pclose();
1797 s.space();
1798 match expr {
1799 Some(expr) => s.print_expr(expr, FixupContext::default()),
1800 None => s.word("_"),
1801 }
1802 }
1803 InlineAsmOperand::InOut { reg, late, expr } => {
1804 s.word(if *late { "inlateout" } else { "inout" });
1805 s.popen();
1806 print_reg_or_class(s, reg);
1807 s.pclose();
1808 s.space();
1809 s.print_expr(expr, FixupContext::default());
1810 }
1811 InlineAsmOperand::SplitInOut { reg, late, in_expr, out_expr } => {
1812 s.word(if *late { "inlateout" } else { "inout" });
1813 s.popen();
1814 print_reg_or_class(s, reg);
1815 s.pclose();
1816 s.space();
1817 s.print_expr(in_expr, FixupContext::default());
1818 s.space();
1819 s.word_space("=>");
1820 match out_expr {
1821 Some(out_expr) => s.print_expr(out_expr, FixupContext::default()),
1822 None => s.word("_"),
1823 }
1824 }
1825 InlineAsmOperand::Const { anon_const } => {
1826 s.word("const");
1827 s.space();
1828 s.print_expr(&anon_const.value, FixupContext::default());
1829 }
1830 InlineAsmOperand::Sym { sym } => {
1831 s.word("sym");
1832 s.space();
1833 if let Some(qself) = &sym.qself {
1834 s.print_qpath(&sym.path, qself, true);
1835 } else {
1836 s.print_path(&sym.path, true, 0);
1837 }
1838 }
1839 InlineAsmOperand::Label { block } => {
1840 let (cb, ib) = s.head("label");
1841 s.print_block(block, cb, ib);
1842 }
1843 }
1844 }
1845 AsmArg::ClobberAbi(abi) => {
1846 s.word("clobber_abi");
1847 s.popen();
1848 s.print_symbol(*abi, ast::StrStyle::Cooked);
1849 s.pclose();
1850 }
1851 AsmArg::Options(opts) => {
1852 s.word("options");
1853 s.popen();
1854 s.commasep(Inconsistent, &opts.human_readable_names(), |s, &opt| {
1855 s.word(opt);
1856 });
1857 s.pclose();
1858 }
1859 });
1860 self.pclose();
1861 }
1862
1863 fn print_local_decl(&mut self, loc: &ast::Local) {
1864 self.print_pat(&loc.pat);
1865 if let Some(ty) = &loc.ty {
1866 self.word_space(":");
1867 self.print_type(ty);
1868 }
1869 }
1870
1871 fn print_name(&mut self, name: Symbol) {
1872 self.word(name.to_string());
1873 self.ann.post(self, AnnNode::Name(&name))
1874 }
1875
1876 fn print_qpath(&mut self, path: &ast::Path, qself: &ast::QSelf, colons_before_params: bool) {
1877 self.word("<");
1878 self.print_type(&qself.ty);
1879 if qself.position > 0 {
1880 self.space();
1881 self.word_space("as");
1882 let depth = path.segments.len() - qself.position;
1883 self.print_path(path, false, depth);
1884 }
1885 self.word(">");
1886 for item_segment in &path.segments[qself.position..] {
1887 self.word("::");
1888 self.print_ident(item_segment.ident);
1889 if let Some(args) = &item_segment.args {
1890 self.print_generic_args(args, colons_before_params)
1891 }
1892 }
1893 }
1894
1895 fn print_pat_paren_if_or(&mut self, pat: &ast::Pat) {
1902 let needs_paren = #[allow(non_exhaustive_omitted_patterns)] match pat.kind {
PatKind::Or(..) => true,
_ => false,
}matches!(pat.kind, PatKind::Or(..));
1903 if needs_paren {
1904 self.popen();
1905 }
1906 self.print_pat(pat);
1907 if needs_paren {
1908 self.pclose();
1909 }
1910 }
1911
1912 fn print_pat(&mut self, pat: &ast::Pat) {
1913 self.maybe_print_comment(pat.span.lo());
1914 self.ann.pre(self, AnnNode::Pat(pat));
1915 match &pat.kind {
1917 PatKind::Missing => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1918 PatKind::Wild => self.word("_"),
1919 PatKind::Never => self.word("!"),
1920 PatKind::Ident(BindingMode(by_ref, mutbl), ident, sub) => {
1921 if mutbl.is_mut() {
1922 self.word_nbsp("mut");
1923 }
1924 if let ByRef::Yes(pinnedness, rmutbl) = by_ref {
1925 self.word_nbsp("ref");
1926 if pinnedness.is_pinned() {
1927 self.word_nbsp("pin");
1928 }
1929 if rmutbl.is_mut() {
1930 self.word_nbsp("mut");
1931 } else if pinnedness.is_pinned() {
1932 self.word_nbsp("const");
1933 }
1934 }
1935 self.print_ident(*ident);
1936 if let Some(p) = sub {
1937 self.space();
1938 self.word_space("@");
1939 self.print_pat_paren_if_or(p);
1940 }
1941 }
1942 PatKind::TupleStruct(qself, path, elts) => {
1943 if let Some(qself) = qself {
1944 self.print_qpath(path, qself, true);
1945 } else {
1946 self.print_path(path, true, 0);
1947 }
1948 self.popen();
1949 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
1950 self.pclose();
1951 }
1952 PatKind::Or(pats) => {
1953 self.strsep("|", true, Inconsistent, pats, |s, p| s.print_pat(p));
1954 }
1955 PatKind::Path(None, path) => {
1956 self.print_path(path, true, 0);
1957 }
1958 PatKind::Path(Some(qself), path) => {
1959 self.print_qpath(path, qself, false);
1960 }
1961 PatKind::Struct(qself, path, fields, etc) => {
1962 if let Some(qself) = qself {
1963 self.print_qpath(path, qself, true);
1964 } else {
1965 self.print_path(path, true, 0);
1966 }
1967 self.nbsp();
1968 self.word("{");
1969 let empty = fields.is_empty() && *etc == ast::PatFieldsRest::None;
1970 if !empty {
1971 self.space();
1972 }
1973 self.commasep_cmnt(
1974 Consistent,
1975 fields,
1976 |s, f| {
1977 let cb = s.cbox(INDENT_UNIT);
1978 if !f.is_shorthand {
1979 s.print_ident(f.ident);
1980 s.word_nbsp(":");
1981 }
1982 s.print_pat(&f.pat);
1983 s.end(cb);
1984 },
1985 |f| f.pat.span,
1986 );
1987 if let ast::PatFieldsRest::Rest(_) | ast::PatFieldsRest::Recovered(_) = etc {
1988 if !fields.is_empty() {
1989 self.word_space(",");
1990 }
1991 self.word("..");
1992 if let ast::PatFieldsRest::Recovered(_) = etc {
1993 self.word("/* recovered parse error */");
1994 }
1995 }
1996 if !empty {
1997 self.space();
1998 }
1999 self.word("}");
2000 }
2001 PatKind::Tuple(elts) => {
2002 self.popen();
2003 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2004 if elts.len() == 1 {
2005 self.word(",");
2006 }
2007 self.pclose();
2008 }
2009 PatKind::Box(inner) => {
2010 self.word("box ");
2011 self.print_pat_paren_if_or(inner);
2012 }
2013 PatKind::Deref(inner) => {
2014 self.word("deref!");
2015 self.popen();
2016 self.print_pat(inner);
2017 self.pclose();
2018 }
2019 PatKind::Ref(inner, pinned, mutbl) => {
2020 self.word("&");
2021 if pinned.is_pinned() {
2022 self.word("pin ");
2023 if mutbl.is_not() {
2024 self.word("const ");
2025 }
2026 }
2027 if mutbl.is_mut() {
2028 self.word("mut ");
2029 }
2030 if let PatKind::Ident(ast::BindingMode::MUT, ..) = inner.kind {
2031 self.popen();
2032 self.print_pat(inner);
2033 self.pclose();
2034 } else {
2035 self.print_pat_paren_if_or(inner);
2036 }
2037 }
2038 PatKind::Expr(e) => self.print_expr(e, FixupContext::default()),
2039 PatKind::Range(begin, end, Spanned { node: end_kind, .. }) => {
2040 if let Some(e) = begin {
2041 self.print_expr(e, FixupContext::default());
2042 }
2043 match end_kind {
2044 RangeEnd::Included(RangeSyntax::DotDotDot) => self.word("..."),
2045 RangeEnd::Included(RangeSyntax::DotDotEq) => self.word("..="),
2046 RangeEnd::Excluded => self.word(".."),
2047 }
2048 if let Some(e) = end {
2049 self.print_expr(e, FixupContext::default());
2050 }
2051 }
2052 PatKind::Guard(subpat, guard) => {
2053 self.popen();
2054 self.print_pat(subpat);
2055 self.space();
2056 self.word_space("if");
2057 self.print_expr(&guard.cond, FixupContext::default());
2058 self.pclose();
2059 }
2060 PatKind::Slice(elts) => {
2061 self.word("[");
2062 self.commasep(Inconsistent, elts, |s, p| s.print_pat(p));
2063 self.word("]");
2064 }
2065 PatKind::Rest => self.word(".."),
2066 PatKind::Paren(inner) => {
2067 self.popen();
2068 self.print_pat(inner);
2069 self.pclose();
2070 }
2071 PatKind::MacCall(m) => self.print_mac(m),
2072 PatKind::Err(_) => {
2073 self.popen();
2074 self.word("/*ERROR*/");
2075 self.pclose();
2076 }
2077 }
2078 self.ann.post(self, AnnNode::Pat(pat))
2079 }
2080
2081 fn print_explicit_self(&mut self, explicit_self: &ast::ExplicitSelf) {
2082 match &explicit_self.node {
2083 SelfKind::Value(m) => {
2084 self.print_mutability(*m, false);
2085 self.word("self")
2086 }
2087 SelfKind::Region(lt, m) => {
2088 self.word("&");
2089 self.print_opt_lifetime(lt);
2090 self.print_mutability(*m, false);
2091 self.word("self")
2092 }
2093 SelfKind::Pinned(lt, m) => {
2094 self.word("&");
2095 self.print_opt_lifetime(lt);
2096 self.word("pin ");
2097 self.print_mutability(*m, true);
2098 self.word("self")
2099 }
2100 SelfKind::Explicit(typ, m) => {
2101 self.print_mutability(*m, false);
2102 self.word("self");
2103 self.word_space(":");
2104 self.print_type(typ)
2105 }
2106 }
2107 }
2108
2109 fn print_coroutine_kind(&mut self, coroutine_kind: ast::CoroutineKind) {
2110 match coroutine_kind {
2111 ast::CoroutineKind::Gen { .. } => {
2112 self.word_nbsp("gen");
2113 }
2114 ast::CoroutineKind::Async { .. } => {
2115 self.word_nbsp("async");
2116 }
2117 ast::CoroutineKind::AsyncGen { .. } => {
2118 self.word_nbsp("async");
2119 self.word_nbsp("gen");
2120 }
2121 }
2122 }
2123
2124 pub fn print_type_bounds(&mut self, bounds: &[ast::GenericBound]) {
2125 let mut first = true;
2126 for bound in bounds {
2127 if first {
2128 first = false;
2129 } else {
2130 self.nbsp();
2131 self.word_space("+");
2132 }
2133
2134 match bound {
2135 GenericBound::Trait(tref) => {
2136 self.print_poly_trait_ref(tref);
2137 }
2138 GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2139 GenericBound::Use(args, _) => {
2140 self.word("use");
2141 self.word("<");
2142 self.commasep(Inconsistent, args, |s, arg| match arg {
2143 ast::PreciseCapturingArg::Arg(p, _) => s.print_path(p, false, 0),
2144 ast::PreciseCapturingArg::Lifetime(lt) => s.print_lifetime(*lt),
2145 });
2146 self.word(">")
2147 }
2148 }
2149 }
2150 }
2151
2152 fn print_lifetime(&mut self, lifetime: ast::Lifetime) {
2153 self.word(lifetime.ident.name.to_string());
2154 self.ann_post(lifetime.ident)
2155 }
2156
2157 fn print_lifetime_bounds(&mut self, bounds: &ast::GenericBounds) {
2158 for (i, bound) in bounds.iter().enumerate() {
2159 if i != 0 {
2160 self.word(" + ");
2161 }
2162 match bound {
2163 ast::GenericBound::Outlives(lt) => self.print_lifetime(*lt),
2164 _ => {
2165 {
::core::panicking::panic_fmt(format_args!("expected a lifetime bound, found a trait bound"));
}panic!("expected a lifetime bound, found a trait bound")
2166 }
2167 }
2168 }
2169 }
2170
2171 fn print_generic_params(&mut self, generic_params: &[ast::GenericParam]) {
2172 if generic_params.is_empty() {
2173 return;
2174 }
2175
2176 self.word("<");
2177
2178 self.commasep(Inconsistent, generic_params, |s, param| {
2179 s.print_outer_attributes_inline(¶m.attrs);
2180
2181 match ¶m.kind {
2182 ast::GenericParamKind::Lifetime => {
2183 let lt = ast::Lifetime { id: param.id, ident: param.ident };
2184 s.print_lifetime(lt);
2185 if !param.bounds.is_empty() {
2186 s.word_nbsp(":");
2187 s.print_lifetime_bounds(¶m.bounds)
2188 }
2189 }
2190 ast::GenericParamKind::Type { default } => {
2191 s.print_ident(param.ident);
2192 if !param.bounds.is_empty() {
2193 s.word_nbsp(":");
2194 s.print_type_bounds(¶m.bounds);
2195 }
2196 if let Some(default) = default {
2197 s.space();
2198 s.word_space("=");
2199 s.print_type(default)
2200 }
2201 }
2202 ast::GenericParamKind::Const { ty, default, .. } => {
2203 s.word_space("const");
2204 s.print_ident(param.ident);
2205 s.space();
2206 s.word_space(":");
2207 s.print_type(ty);
2208 if !param.bounds.is_empty() {
2209 s.word_nbsp(":");
2210 s.print_type_bounds(¶m.bounds);
2211 }
2212 if let Some(default) = default {
2213 s.space();
2214 s.word_space("=");
2215 s.print_expr(&default.value, FixupContext::default());
2216 }
2217 }
2218 }
2219 });
2220
2221 self.word(">");
2222 }
2223
2224 pub fn print_mutability(&mut self, mutbl: ast::Mutability, print_const: bool) {
2225 match mutbl {
2226 ast::Mutability::Mut => self.word_nbsp("mut"),
2227 ast::Mutability::Not => {
2228 if print_const {
2229 self.word_nbsp("const");
2230 }
2231 }
2232 }
2233 }
2234
2235 fn print_mt(&mut self, mt: &ast::MutTy, print_const: bool) {
2236 self.print_mutability(mt.mutbl, print_const);
2237 self.print_type(&mt.ty)
2238 }
2239
2240 fn print_param(&mut self, input: &ast::Param, is_closure: bool) {
2241 let ib = self.ibox(INDENT_UNIT);
2242
2243 self.print_outer_attributes_inline(&input.attrs);
2244
2245 match input.ty.kind {
2246 ast::TyKind::Infer if is_closure => self.print_pat(&input.pat),
2247 _ => {
2248 if let Some(eself) = input.to_self() {
2249 self.print_explicit_self(&eself);
2250 } else {
2251 if !#[allow(non_exhaustive_omitted_patterns)] match input.pat.kind {
PatKind::Missing => true,
_ => false,
}matches!(input.pat.kind, PatKind::Missing) {
2252 self.print_pat(&input.pat);
2253 self.word(":");
2254 self.space();
2255 }
2256 self.print_type(&input.ty);
2257 }
2258 }
2259 }
2260 self.end(ib);
2261 }
2262
2263 fn print_fn_ret_ty(&mut self, fn_ret_ty: &ast::FnRetTy) {
2264 if let ast::FnRetTy::Ty(ty) = fn_ret_ty {
2265 self.space_if_not_bol();
2266 let ib = self.ibox(INDENT_UNIT);
2267 self.word_space("->");
2268 self.print_type(ty);
2269 self.end(ib);
2270 self.maybe_print_comment(ty.span.lo());
2271 }
2272 }
2273
2274 fn print_ty_fn(
2275 &mut self,
2276 ext: ast::Extern,
2277 safety: ast::Safety,
2278 decl: &ast::FnDecl,
2279 name: Option<Ident>,
2280 generic_params: &[ast::GenericParam],
2281 ) {
2282 let ib = self.ibox(INDENT_UNIT);
2283 self.print_formal_generic_params(generic_params);
2284 let generics = ast::Generics::default();
2285 let header = ast::FnHeader { safety, ext, ..ast::FnHeader::default() };
2286 self.print_fn(decl, header, name, &generics);
2287 self.end(ib);
2288 }
2289
2290 fn print_fn_header_info(&mut self, header: ast::FnHeader) {
2291 self.print_constness(header.constness);
2292 header.coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind));
2293 self.print_safety(header.safety);
2294
2295 match header.ext {
2296 ast::Extern::None => {}
2297 ast::Extern::Implicit(_) => {
2298 self.word_nbsp("extern");
2299 }
2300 ast::Extern::Explicit(abi, _) => {
2301 self.word_nbsp("extern");
2302 self.print_token_literal(abi.as_token_lit(), abi.span);
2303 self.nbsp();
2304 }
2305 }
2306
2307 self.word("fn")
2308 }
2309
2310 fn print_safety(&mut self, s: ast::Safety) {
2311 match s {
2312 ast::Safety::Default => {}
2313 ast::Safety::Safe(_) => self.word_nbsp("safe"),
2314 ast::Safety::Unsafe(_) => self.word_nbsp("unsafe"),
2315 }
2316 }
2317
2318 fn print_constness(&mut self, s: ast::Const) {
2319 match s {
2320 ast::Const::No => {}
2321 ast::Const::Yes(_) => self.word_nbsp("const"),
2322 }
2323 }
2324
2325 fn print_is_auto(&mut self, s: ast::IsAuto) {
2326 match s {
2327 ast::IsAuto::Yes => self.word_nbsp("auto"),
2328 ast::IsAuto::No => {}
2329 }
2330 }
2331
2332 fn print_meta_item_lit(&mut self, lit: &ast::MetaItemLit) {
2333 self.print_token_literal(lit.as_token_lit(), lit.span)
2334 }
2335
2336 fn print_token_literal(&mut self, token_lit: token::Lit, span: Span) {
2337 self.maybe_print_comment(span.lo());
2338 self.word(token_lit.to_string())
2339 }
2340
2341 fn print_symbol(&mut self, sym: Symbol, style: ast::StrStyle) {
2342 self.print_string(sym.as_str(), style);
2343 }
2344
2345 fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool {
2346 self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false)
2347 }
2348
2349 fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool {
2350 self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true)
2351 }
2352
2353 fn print_attribute(&mut self, attr: &ast::Attribute) {
2354 self.print_attribute_inline(attr, false);
2355 }
2356
2357 fn print_meta_list_item(&mut self, item: &ast::MetaItemInner) {
2358 match item {
2359 ast::MetaItemInner::MetaItem(mi) => self.print_meta_item(mi),
2360 ast::MetaItemInner::Lit(lit) => self.print_meta_item_lit(lit),
2361 }
2362 }
2363
2364 fn print_meta_item(&mut self, item: &ast::MetaItem) {
2365 let ib = self.ibox(INDENT_UNIT);
2366
2367 match item.unsafety {
2368 ast::Safety::Unsafe(_) => {
2369 self.word("unsafe");
2370 self.popen();
2371 }
2372 ast::Safety::Default | ast::Safety::Safe(_) => {}
2373 }
2374
2375 match &item.kind {
2376 ast::MetaItemKind::Word => self.print_path(&item.path, false, 0),
2377 ast::MetaItemKind::NameValue(value) => {
2378 self.print_path(&item.path, false, 0);
2379 self.space();
2380 self.word_space("=");
2381 self.print_meta_item_lit(value);
2382 }
2383 ast::MetaItemKind::List(items) => {
2384 self.print_path(&item.path, false, 0);
2385 self.popen();
2386 self.commasep(Consistent, items, |s, i| s.print_meta_list_item(i));
2387 self.pclose();
2388 }
2389 }
2390
2391 match item.unsafety {
2392 ast::Safety::Unsafe(_) => self.pclose(),
2393 ast::Safety::Default | ast::Safety::Safe(_) => {}
2394 }
2395
2396 self.end(ib);
2397 }
2398
2399 pub(crate) fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String {
2400 Self::to_string(|s| s.print_type_bounds(bounds))
2401 }
2402
2403 pub(crate) fn where_bound_predicate_to_string(
2404 &self,
2405 where_bound_predicate: &ast::WhereBoundPredicate,
2406 ) -> String {
2407 Self::to_string(|s| s.print_where_bound_predicate(where_bound_predicate))
2408 }
2409
2410 pub(crate) fn tt_to_string(&self, tt: &TokenTree) -> String {
2411 Self::to_string(|s| {
2412 s.print_tt(tt, false);
2413 })
2414 }
2415
2416 pub(crate) fn path_segment_to_string(&self, p: &ast::PathSegment) -> String {
2417 Self::to_string(|s| s.print_path_segment(p, false))
2418 }
2419
2420 pub(crate) fn meta_list_item_to_string(&self, li: &ast::MetaItemInner) -> String {
2421 Self::to_string(|s| s.print_meta_list_item(li))
2422 }
2423
2424 pub(crate) fn attribute_to_string(&self, attr: &ast::Attribute) -> String {
2425 Self::to_string(|s| s.print_attribute(attr))
2426 }
2427}