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