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