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