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