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