1#![allow(clippy::too_many_arguments)]
2use crate::{
3 FormatterConfig, InlineConfig,
4 pp::{self, BreakToken, SIZE_INFINITY, Token},
5 state::sol::BinOpGroup,
6};
7use foundry_common::{
8 comments::{Comment, CommentStyle, Comments, estimate_line_width, line_with_tabs},
9 iter::IterDelimited,
10};
11use foundry_config::fmt::{DocCommentStyle, IndentStyle, IntTypes};
12use solar::parse::{
13 ast::{self, Span},
14 interface::{BytePos, source_map::SourceFile},
15 token,
16};
17use std::{borrow::Cow, ops::Deref, sync::Arc};
18
19mod common;
20mod sol;
21mod yul;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub(super) enum CallContextKind {
26 Chained,
28
29 Nested,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub(super) struct CallContext {
36 pub(super) kind: CallContextKind,
38
39 pub(super) size: usize,
41
42 pub(super) has_indent: bool,
44}
45
46impl CallContext {
47 pub(super) const fn nested(size: usize) -> Self {
48 Self { kind: CallContextKind::Nested, size, has_indent: false }
49 }
50
51 pub(super) const fn chained(size: usize, has_indent: bool) -> Self {
52 Self { kind: CallContextKind::Chained, size, has_indent }
53 }
54
55 pub(super) const fn is_nested(&self) -> bool {
56 matches!(self.kind, CallContextKind::Nested)
57 }
58
59 pub(super) const fn is_chained(&self) -> bool {
60 matches!(self.kind, CallContextKind::Chained)
61 }
62}
63
64#[derive(Debug, Default)]
65pub(super) struct CallStack {
66 stack: Vec<CallContext>,
67}
68
69impl Deref for CallStack {
70 type Target = [CallContext];
71 fn deref(&self) -> &Self::Target {
72 &self.stack
73 }
74}
75
76impl CallStack {
77 pub(crate) fn push(&mut self, call: CallContext) {
78 self.stack.push(call);
79 }
80
81 pub(crate) fn pop(&mut self) -> Option<CallContext> {
82 self.stack.pop()
83 }
84
85 pub(crate) fn is_nested(&self) -> bool {
86 self.last().is_some_and(|call| call.is_nested())
87 }
88
89 pub(crate) const fn has_indented_parent_chain(&self) -> bool {
92 matches!(
93 self.stack.as_slice(),
94 [.., parent, last] if last.is_nested() && parent.is_chained() && parent.has_indent
95 )
96 }
97}
98
99#[derive(Clone, Copy)]
100struct ChainedNamedCall {
101 callee: Span,
102 keep_inline: bool,
103}
104
105pub(super) struct State<'sess, 'ast> {
106 pub(super) s: pp::Printer,
108 ind: isize,
109
110 file: &'sess SourceFile,
111 pub(super) comments: Comments,
112 config: Arc<FormatterConfig>,
113 inline_config: InlineConfig<()>,
114 cursor: SourcePos,
115 directive_doc_groups: Vec<Span>,
117
118 has_crlf: bool,
121 contract: Option<&'ast ast::ItemContract<'ast>>,
123 block_depth: usize,
125 call_stack: CallStack,
127
128 single_line_stmt: Option<bool>,
130 binary_expr: Option<BinOpGroup>,
132 return_bin_expr: bool,
134 call_with_opts_and_args: bool,
136 chained_named_call: Option<ChainedNamedCall>,
138 skip_index_break: bool,
140 emit_or_revert: bool,
142 var_init: bool,
144 inline_assignments: bool,
146}
147
148impl std::ops::Deref for State<'_, '_> {
149 type Target = pp::Printer;
150
151 #[inline(always)]
152 fn deref(&self) -> &Self::Target {
153 &self.s
154 }
155}
156
157impl std::ops::DerefMut for State<'_, '_> {
158 #[inline(always)]
159 fn deref_mut(&mut self) -> &mut Self::Target {
160 &mut self.s
161 }
162}
163
164struct SourcePos {
165 pos: BytePos,
166 enabled: bool,
167}
168
169impl SourcePos {
170 pub(super) fn advance(&mut self, bytes: u32) {
173 self.pos += BytePos(bytes);
174 }
175
176 pub(super) fn advance_to(&mut self, pos: BytePos, enabled: bool) {
177 if self.enabled || pos >= self.pos {
180 self.pos = std::cmp::max(pos, self.pos);
181 self.enabled = enabled;
182 }
183 }
184
185 pub(super) fn next_line(&mut self, is_at_crlf: bool) {
186 self.pos += if is_at_crlf { 2 } else { 1 };
187 }
188
189 pub(super) fn span(&self, to: BytePos) -> Span {
190 Span::new(self.pos, to)
191 }
192}
193
194pub(super) enum Separator {
195 Nbsp,
196 Space,
197 Hardbreak,
198 SpaceOrNbsp(bool),
199}
200
201impl Separator {
202 fn print(&self, p: &mut pp::Printer) {
203 match self {
204 Self::Nbsp => p.nbsp(),
205 Self::Space => p.space(),
206 Self::Hardbreak => p.hardbreak(),
207 Self::SpaceOrNbsp(breaks) => p.space_or_nbsp(*breaks),
208 }
209 }
210}
211
212impl<'sess> State<'sess, '_> {
214 pub(super) fn new(
215 file: &'sess SourceFile,
216 config: Arc<FormatterConfig>,
217 inline_config: InlineConfig<()>,
218 comments: Comments,
219 ) -> Self {
220 let directive_doc_groups = Self::directive_doc_groups(file, &comments);
221 Self {
222 s: pp::Printer::new(
223 config.line_length,
224 matches!(config.style, IndentStyle::Tab).then(|| config.tab_width),
225 ),
226 ind: config.tab_width as isize,
227 file,
228 comments,
229 config,
230 inline_config,
231 cursor: SourcePos { pos: file.start_pos, enabled: true },
232 directive_doc_groups,
233 has_crlf: false,
234 contract: None,
235 single_line_stmt: None,
236 call_with_opts_and_args: false,
237 chained_named_call: None,
238 skip_index_break: false,
239 binary_expr: None,
240 return_bin_expr: false,
241 emit_or_revert: false,
242 var_init: false,
243 inline_assignments: false,
244 block_depth: 0,
245 call_stack: CallStack::default(),
246 }
247 }
248
249 fn check_crlf(&mut self, span: Span) {
255 if let Some(snip) = self.snippet(span)
256 && snip.contains('\r')
257 {
258 self.has_crlf = true;
259 }
260 }
261
262 fn is_at_crlf(&self) -> bool {
265 self.has_crlf && self.char_at(self.cursor.pos) == Some('\r')
266 }
267
268 fn cursor_next_line(&mut self) {
274 if self.cursor.enabled || matches!(self.char_at(self.cursor.pos), Some('\n' | '\r')) {
275 self.cursor.next_line(self.is_at_crlf());
276 }
277 }
278
279 fn space_left(&self) -> usize {
281 std::cmp::min(self.s.space_left(), self.max_space_left(0))
282 }
283
284 fn max_space_left(&self, prefix_len: usize) -> usize {
287 self.config
288 .line_length
289 .saturating_sub(self.block_depth * self.config.tab_width + prefix_len)
290 }
291
292 fn break_offset_if_not_bol(&mut self, n: usize, off: isize, search: bool) {
293 if search {
296 self.find_and_replace_last_token_still_buffered(
299 pp::Printer::hardbreak_tok_offset(off),
300 |token| token.is_hardbreak(),
301 );
302 return;
303 }
304
305 if !self.is_beginning_of_line() {
307 self.break_offset(n, off)
308 } else if off != 0
309 && let Some(last_token) = self.last_token_still_buffered()
310 && last_token.is_hardbreak()
311 {
312 self.replace_last_token_still_buffered(pp::Printer::hardbreak_tok_offset(off));
315 }
316 }
317
318 fn braces_break(&mut self) {
319 if self.config.bracket_spacing {
320 self.space();
321 } else {
322 self.zerobreak();
323 }
324 }
325}
326
327impl<'sess> State<'sess, '_> {
329 fn snippet(&self, span: Span) -> Option<&'sess str> {
330 let start = span.lo().0.checked_sub(self.file.start_pos.0)? as usize;
331 let end = span.hi().0.checked_sub(self.file.start_pos.0)? as usize;
332 self.file.src.get(start..end)
333 }
334
335 fn source_line(&self, pos: BytePos) -> usize {
336 self.file.lookup_line(self.file.relative_position(pos)).map_or(0, |line| line + 1)
337 }
338
339 fn char_at(&self, pos: BytePos) -> Option<char> {
340 let offset = pos.0.checked_sub(self.file.start_pos.0)? as usize;
341 self.file.src.get(offset..)?.chars().next()
342 }
343
344 fn find_opening_brace(&self, span: Span) -> Option<BytePos> {
346 self.find_uncommented_char(span, '{')
347 }
348
349 fn find_uncommented_char(&self, span: Span, needle: char) -> Option<BytePos> {
351 let snip = self.snippet(span)?;
352 let mut idx = 0;
353 while idx < snip.len() {
354 let rest = &snip[idx..];
355 if rest.starts_with(needle) {
356 return Some(span.lo() + idx as u32);
357 }
358 idx += if let Some(line) = rest.strip_prefix("//") {
359 2 + line.find('\n').unwrap_or(line.len())
360 } else if let Some(block) = rest.strip_prefix("/*") {
361 2 + block.find("*/").map_or(block.len(), |end| end + 2)
362 } else {
363 rest.chars().next().map_or(1, char::len_utf8)
364 };
365 }
366 None
367 }
368
369 fn print_span(&mut self, span: Span) {
370 match self.snippet(span) {
371 Some(s) => self.s.word(if matches!(self.config.style, IndentStyle::Tab) {
372 snippet_with_tabs(s.to_owned(), self.config.tab_width)
373 } else {
374 s.to_owned()
375 }),
376 None => panic!("failed to print {span:?}: invalid source span"),
377 }
378 while let Some(cmnt) = self.peek_comment() {
380 if cmnt.pos() >= span.hi() {
381 break;
382 }
383 let _ = self.next_comment().unwrap();
384 }
385 self.cursor.advance_to(span.hi(), false);
387 }
388
389 #[must_use]
391 fn handle_span(&mut self, span: Span, skip_prev_cmnts: bool) -> bool {
392 if !skip_prev_cmnts {
393 self.print_comments(span.lo(), CommentConfig::default());
394 }
395 self.print_span_if_disabled(span)
396 }
397
398 #[inline]
400 #[must_use]
401 fn print_span_if_disabled(&mut self, span: Span) -> bool {
402 let cursor_span = self.cursor.span(span.hi());
403 if self.inline_config.is_disabled(cursor_span) {
404 self.print_span_cold(cursor_span);
405 return true;
406 }
407 if self.inline_config.is_disabled(span) {
408 self.print_span_cold(span);
409 return true;
410 }
411 false
412 }
413
414 #[cold]
415 fn print_span_cold(&mut self, span: Span) {
416 self.print_span(span);
417 }
418
419 fn print_tokens(&mut self, tokens: &[token::Token]) {
420 let span = Span::join_first_last(tokens.iter().map(|t| t.span));
422 self.print_span(span);
423 }
424
425 fn print_word(&mut self, w: impl Into<Cow<'static, str>>) {
426 let cow = w.into();
427 self.cursor.advance(cow.len() as u32);
428 self.word(cow);
429 }
430
431 fn print_sep(&mut self, sep: Separator) {
432 if self.handle_span(
433 self.cursor.span(self.cursor.pos + if self.is_at_crlf() { 2 } else { 1 }),
434 true,
435 ) {
436 return;
437 }
438
439 self.print_sep_unhandled(sep);
440 }
441
442 fn print_sep_unhandled(&mut self, sep: Separator) {
443 sep.print(&mut self.s);
444 self.cursor_next_line();
445 }
446
447 fn print_ident(&mut self, ident: &ast::Ident) {
448 if self.handle_span(ident.span, true) {
449 return;
450 }
451
452 self.print_comments(ident.span.lo(), CommentConfig::skip_ws());
453 self.word(ident.to_string());
454 }
455
456 fn print_inside_parens<F>(&mut self, f: F)
457 where
458 F: FnOnce(&mut Self),
459 {
460 self.print_word("(");
461 f(self);
462 self.print_word(")");
463 }
464
465 fn brace_spacing_delta(
467 &self,
468 line: &str,
469 in_block_comment: &mut bool,
470 quote: &mut Option<u8>,
471 ) -> isize {
472 let bytes = line.as_bytes();
473 let mut delta = 0;
474 let mut i = 0;
475 while i < bytes.len() {
476 if let Some(delimiter) = *quote {
477 match bytes[i] {
478 b'\\' => i = (i + 2).min(bytes.len()),
479 c if c == delimiter => {
480 *quote = None;
481 i += 1;
482 }
483 _ => i += 1,
484 }
485 continue;
486 }
487 if *in_block_comment {
488 if bytes.get(i..i + 2) == Some(b"*/") {
489 *in_block_comment = false;
490 i += 2;
491 } else {
492 i += 1;
493 }
494 continue;
495 }
496 match bytes[i] {
497 b'/' if bytes.get(i + 1) == Some(&b'/') => break,
498 b'/' if bytes.get(i + 1) == Some(&b'*') => {
499 *in_block_comment = true;
500 i += 2;
501 }
502 delimiter @ (b'\'' | b'"') => {
503 *quote = Some(delimiter);
504 i += 1;
505 }
506 b'{' | b'}' => {
507 let inner = if bytes[i] == b'{' {
508 bytes.get(i + 1)
509 } else {
510 i.checked_sub(1).and_then(|j| bytes.get(j))
511 };
512 if let Some(&inner) = inner
513 && !matches!(inner, b'{' | b'}')
514 {
515 delta += match (matches!(inner, b' ' | b'\t'), self.config.bracket_spacing)
516 {
517 (true, false) => -1,
518 (false, true) => 1,
519 _ => 0,
520 };
521 }
522 i += 1;
523 }
524 _ => i += 1,
525 }
526 }
527 delta
528 }
529
530 fn int_type_delta(&self, ty: &ast::Type<'_>) -> isize {
533 match &ty.kind {
534 ast::TypeKind::Elementary(
535 ast::ElementaryType::Int(size) | ast::ElementaryType::UInt(size),
536 ) => match (self.config.int_types, size.bits_raw()) {
537 (IntTypes::Long, 0) => 3,
538 (IntTypes::Short, 256) => -3,
539 _ => 0,
540 },
541 ast::TypeKind::Array(array) => self.int_type_delta(&array.element),
542 ast::TypeKind::Mapping(mapping) => {
543 self.int_type_delta(&mapping.key) + self.int_type_delta(&mapping.value)
544 }
545 ast::TypeKind::Function(function) => {
546 let params: isize = function
547 .parameters
548 .vars
549 .iter()
550 .map(|param| self.int_type_delta(¶m.ty))
551 .sum();
552 let returns: isize = function.returns.as_ref().map_or(0, |returns| {
553 returns.vars.iter().map(|ret| self.int_type_delta(&ret.ty)).sum()
554 });
555 params + returns
556 }
557 _ => 0,
558 }
559 }
560
561 fn estimate_type_size(&self, ty: &ast::Type<'_>) -> usize {
562 self.estimate_size(ty.span).saturating_add_signed(self.int_type_delta(ty))
563 }
564
565 fn estimate_size(&self, span: Span) -> usize {
566 self.estimate_size_inner(span, false)
567 }
568
569 fn estimate_call_args_size(&self, span: Span) -> usize {
572 self.estimate_size_inner(span, true)
573 }
574
575 fn estimate_assignment_size(&self, span: Span) -> usize {
578 self.estimate_size_inner(span, !self.has_comment_between(span.lo(), span.hi()))
579 }
580
581 fn estimate_size_inner(&self, span: Span, normalize_delimiters: bool) -> usize {
582 if let Some(snip) = self.snippet(span) {
583 let (mut size, mut first, mut prev_needs_space) = (0, true, false);
584 let (mut in_block_comment, mut quote) = (false, None);
585
586 for line in snip.lines() {
587 let line = line.trim();
588 if line.is_empty() {
590 continue;
591 }
592
593 if prev_needs_space {
594 size += 1;
595 } else if !first && let Some(char) = line.chars().next() {
596 match char {
601 '&' | '|' | '=' | '>' | '<' | '+' | '-' | '*' | '/' | '%' | '^' | '?'
602 | ':' => size += 1,
603 ')' | ']'
604 if self.config.bracket_spacing
605 && (!normalize_delimiters || quote.is_some()) =>
606 {
607 size += 1
608 }
609 '}' if self.config.bracket_spacing => size += 1,
610 _ => (),
611 }
612 }
613 first = false;
614
615 let mut search = line;
617 loop {
618 if let Some((lhs, comment)) = search.split_once(r#"/*"#) {
619 size += lhs.trim_end().len() + 2;
620 search = comment;
621 } else if let Some((comment, rhs)) = search.split_once(r#"*/"#) {
622 size += comment.len() + 2;
623 search = rhs;
624 } else {
625 size += search.trim().len();
626 break;
627 }
628 }
629 let brace_delta = self.brace_spacing_delta(line, &mut in_block_comment, &mut quote);
630 size = size.saturating_add_signed(brace_delta);
631
632 prev_needs_space = match line.chars().next_back() {
638 Some('{') => self.config.bracket_spacing,
639 Some('[' | '(') => {
640 self.config.bracket_spacing && (!normalize_delimiters || quote.is_some())
641 }
642 Some(',' | ';') => true,
643 Some(
644 '&' | '|' | '=' | '>' | '<' | '+' | '-' | '*' | '/' | '%' | '^' | '?' | ':',
645 ) => !line.ends_with("*/"),
646 _ => false,
647 };
648 }
649 return size;
650 }
651
652 span.to_range().len()
653 }
654
655 fn same_source_line(&self, a: BytePos, b: BytePos) -> bool {
656 self.source_line(a) == self.source_line(b)
657 }
658}
659
660impl<'sess> State<'sess, '_> {
662 #[must_use]
664 fn handle_comment(&mut self, cmnt: Comment, skip_break: bool) -> Option<Comment> {
665 if self.cursor.enabled {
666 if self.inline_config.is_disabled(cmnt.span) {
667 if cmnt.style.is_isolated() {
671 self.hardbreak_if_not_bol();
672 } else if cmnt.style.is_trailing() && !self.last_token_is_space() {
673 self.nbsp();
674 }
675 self.print_span_cold(cmnt.span);
676 if !skip_break && (cmnt.style.is_isolated() || cmnt.style.is_trailing()) {
677 self.print_sep(Separator::Hardbreak);
678 }
679 return None;
680 }
681 } else if self.print_span_if_disabled(cmnt.span) {
682 if !skip_break && (cmnt.style.is_isolated() || cmnt.style.is_trailing()) {
683 self.print_sep(Separator::Hardbreak);
684 }
685 return None;
686 }
687 Some(cmnt)
688 }
689
690 fn cmnt_config(&self) -> CommentConfig {
691 Default::default()
692 }
693
694 const fn print_docs(&mut self, docs: &'_ ast::DocComments<'_>) {
695 let _ = docs;
697 }
698
699 fn print_comments(&mut self, pos: BytePos, mut config: CommentConfig) -> Option<CommentStyle> {
704 let mut last_style: Option<CommentStyle> = None;
705 let mut is_leading = true;
706 let config_cache = config;
707 let mut buffered_blank = None;
708 let mut previous_mixed_at_bol = false;
709 while self.peek_comment().is_some_and(|c| c.pos() < pos) {
710 let mut cmnt = self.next_comment().unwrap();
711 let style_cache = cmnt.style;
712
713 if self.config.docs_style == foundry_config::fmt::DocCommentStyle::Block
715 && cmnt.is_doc
716 && cmnt.kind == ast::CommentKind::Line
717 && !self.preserve_doc_comment(&cmnt)
718 {
719 let mut ref_line = self.source_line(cmnt.span.hi());
720 while let Some(next_cmnt) = self.peek_comment() {
721 if !next_cmnt.is_doc
722 || next_cmnt.kind != ast::CommentKind::Line
723 || self.preserve_doc_comment(next_cmnt)
724 || ref_line + 1 != self.source_line(next_cmnt.span.lo())
725 {
726 break;
727 }
728
729 let next_to_merge = self.next_comment().unwrap();
730 cmnt.lines.extend(next_to_merge.lines);
731 cmnt.span = cmnt.span.to(next_to_merge.span);
732 ref_line += 1;
733 }
734 }
735
736 if self.peek_comment_before(pos).is_some() {
738 config.iso_no_break = false;
739 config.trailing_no_break = false;
740 }
741
742 let Some(mut cmnt) = self.handle_comment(
744 cmnt,
745 if style_cache.is_isolated() {
746 config.iso_no_break
747 } else {
748 config.trailing_no_break
749 },
750 ) else {
751 last_style = Some(style_cache);
752 continue;
753 };
754
755 if cmnt.style.is_blank() {
756 match config.skip_blanks {
757 Some(Skip::All) => continue,
758 Some(Skip::Leading { resettable: true }) if is_leading => continue,
759 Some(Skip::Leading { resettable: false }) if last_style.is_none() => continue,
760 Some(Skip::Trailing) => {
761 buffered_blank = Some(cmnt);
762 continue;
763 }
764 _ => (),
765 }
766 } else if !cmnt.is_doc {
768 is_leading = false;
769 }
770
771 if let Some(blank) = buffered_blank.take() {
772 self.print_comment(blank, config);
773 }
774
775 if previous_mixed_at_bol
776 && cmnt.style.is_trailing()
777 && matches!(cmnt.kind, ast::CommentKind::Line)
778 {
779 self.hardbreak_if_not_bol();
780 }
781
782 if cmnt.style.is_trailing() && self.is_bol_or_only_ind() {
785 cmnt.style = CommentStyle::Isolated;
786 }
787
788 if cmnt.style.is_mixed() {
790 if let Some(cmnt) = self.peek_comment_before(pos) {
791 config.mixed_no_break_prev = true;
792 config.mixed_no_break_post = true;
793 config.mixed_post_nbsp = false;
794 if cmnt.style.is_mixed() {
798 config = config.mixed_post_glued();
799 }
800 }
801
802 if last_style.is_some_and(|s| s.is_mixed()) {
804 config.mixed_no_break_prev = true;
805 config.mixed_no_break_post = true;
806 config.mixed_prev_space = false;
807 }
808 } else if config.offset != 0
809 && cmnt.style.is_isolated()
810 && last_style.is_some_and(|s| s.is_isolated())
811 {
812 self.offset(config.offset);
813 }
814
815 last_style = Some(cmnt.style);
816 previous_mixed_at_bol = cmnt.style.is_mixed() && self.is_bol_or_only_ind();
817 self.print_comment(cmnt, config);
818 config = config_cache;
819 }
820 last_style
821 }
822
823 fn print_wrapped_line(
825 &mut self,
826 line: &str,
827 prefix: &'static str,
828 break_offset: isize,
829 is_doc: bool,
830 ) {
831 if !line.starts_with(prefix) {
832 self.word(line.to_owned());
833 return;
834 }
835
836 fn post_break_prefix(prefix: &'static str, has_content: bool) -> &'static str {
837 if !has_content {
838 return prefix;
839 }
840 match prefix {
841 "///" => "/// ",
842 "//" => "// ",
843 "/*" => "/* ",
844 " *" => " * ",
845 _ => prefix,
846 }
847 }
848
849 self.ibox(0);
850 self.word(prefix);
851
852 let content = &line[prefix.len()..];
853 let content = if is_doc {
854 let ws_len = content
856 .char_indices()
857 .take_while(|(_, c)| c.is_whitespace())
858 .last()
859 .map_or(0, |(idx, c)| idx + c.len_utf8());
860 let (leading_ws, rest) = content.split_at(ws_len);
861 if !leading_ws.is_empty() {
862 self.word(leading_ws.to_owned());
863 }
864 rest
865 } else {
866 if let Some(first_char) = content.chars().next() {
868 if first_char.is_whitespace() {
869 self.nbsp();
870 &content[first_char.len_utf8()..]
871 } else {
872 content
873 }
874 } else {
875 ""
876 }
877 };
878
879 let post_break = post_break_prefix(prefix, !content.is_empty());
880
881 let (mut chars, mut current_word) = (content.chars().peekable(), String::new());
883 while let Some(ch) = chars.next() {
884 if ch.is_whitespace() {
885 if !current_word.is_empty() {
887 self.word(std::mem::take(&mut current_word));
888 }
889
890 let mut ws_count = 1;
892 while chars.peek().is_some_and(|c| c.is_whitespace()) {
893 ws_count += 1;
894 chars.next();
895 }
896 self.s.scan_break(BreakToken {
897 offset: break_offset,
898 blank_space: ws_count,
899 post_break: if post_break.starts_with("/*") { None } else { Some(post_break) },
900 ..Default::default()
901 });
902 continue;
903 }
904
905 current_word.push(ch);
906 }
907
908 if !current_word.is_empty() {
910 self.word(current_word);
911 }
912
913 self.end();
914 }
915
916 fn merge_comment_lines(&self, lines: &[String], prefix: &str) -> Vec<String> {
918 if lines.is_empty() || lines.len() < 2 || !prefix.starts_with("//") {
920 return lines.to_vec();
921 }
922
923 let mut result = Vec::new();
924 let mut i = 0;
925
926 while i < lines.len() {
927 let current_line = &lines[i];
928
929 if current_line.trim().is_empty() || !current_line.starts_with(prefix) {
931 result.push(current_line.clone());
932 i += 1;
933 continue;
934 }
935
936 if i + 1 < lines.len() {
937 let next_line = &lines[i + 1];
938
939 if next_line.starts_with(prefix) && !next_line.trim().is_empty() {
941 let next_content = next_line[prefix.len()..].trim_start();
942
943 if next_content.starts_with('@') {
946 result.push(current_line.clone());
947 i += 1;
948 continue;
949 }
950
951 if estimate_line_width(current_line, self.config.tab_width) > self.space_left()
953 {
954 let merged_line = format!("{current_line} {next_content}");
956 result.push(merged_line);
957
958 i += 2;
960 continue;
961 }
962 }
963 }
964
965 result.push(current_line.clone());
967 i += 1;
968 }
969
970 result
971 }
972
973 fn print_comment(&mut self, mut cmnt: Comment, mut config: CommentConfig) {
974 self.cursor.advance_to(cmnt.span.hi(), true);
975
976 let preserve = self.preserve_doc_comment(&cmnt);
977 let wrap_comments = self.config.wrap_comments && !preserve;
978 if cmnt.is_doc && !preserve {
979 cmnt = style_doc_comment(self.config.docs_style, cmnt);
980 }
981
982 match cmnt.style {
983 CommentStyle::Mixed => {
984 let Some(prefix) = cmnt.prefix() else { return };
985 let never_break = self.last_token_is_neverbreak();
986 let starts_line = self.is_bol_or_only_ind() || self.last_token_is_break();
987 if !self.is_bol_or_only_ind() {
988 match (never_break || config.mixed_no_break_prev, config.mixed_prev_space) {
989 (false, true) => config.space(&mut self.s),
990 (false, false) => config.zerobreak(&mut self.s),
991 (true, true) => self.nbsp(),
992 (true, false) => (),
993 };
994 }
995 if wrap_comments {
996 if starts_line {
998 self.ibox(config.offset);
999 }
1000 let merged_lines = self.merge_comment_lines(&cmnt.lines, prefix);
1001 for (pos, line) in merged_lines.into_iter().delimited() {
1002 self.print_wrapped_line(&line, prefix, 0, cmnt.is_doc);
1003 if !pos.is_last {
1004 self.hardbreak();
1005 }
1006 }
1007 if starts_line {
1008 self.end();
1009 }
1010 } else {
1011 self.visual_align();
1013 for (pos, line) in cmnt.lines.into_iter().delimited() {
1014 if !line.is_empty() {
1015 self.word(line);
1016 }
1017 if !pos.is_last {
1018 self.hardbreak();
1019 }
1020 }
1021 self.end();
1022 }
1023 if config.mixed_post_nbsp {
1024 if config.mixed_post_glued {
1025 self.nbsp();
1026 } else {
1027 config.nbsp_or_space(wrap_comments, &mut self.s);
1028 }
1029 self.cursor.advance(1);
1030 } else if !config.mixed_no_break_post {
1031 config.space(&mut self.s);
1032 self.cursor.advance(1);
1033 }
1034 }
1035 CommentStyle::Isolated => {
1036 let Some(mut prefix) = cmnt.prefix() else { return };
1037 if !config.iso_no_break {
1038 config.hardbreak_if_not_bol(self.is_bol_or_only_ind(), &mut self.s);
1039 }
1040
1041 if wrap_comments {
1042 let merged_lines = self.merge_comment_lines(&cmnt.lines, prefix);
1044 for (pos, line) in merged_lines.into_iter().delimited() {
1045 let hb = |this: &mut Self| {
1046 this.hardbreak();
1047 if pos.is_last {
1048 this.cursor.next_line(this.is_at_crlf());
1049 }
1050 };
1051 if line.is_empty() {
1052 hb(self);
1053 continue;
1054 }
1055 if pos.is_first {
1056 self.ibox(config.offset);
1057 if cmnt.is_doc && matches!(prefix, "/**") {
1058 self.word(prefix);
1059 hb(self);
1060 prefix = " * ";
1061 continue;
1062 }
1063 }
1064
1065 self.print_wrapped_line(&line, prefix, 0, cmnt.is_doc);
1066
1067 if pos.is_last {
1068 self.end();
1069 if !config.iso_no_break {
1070 hb(self);
1071 }
1072 } else {
1073 hb(self);
1074 }
1075 }
1076 } else {
1077 for (pos, line) in cmnt.lines.into_iter().delimited() {
1079 let hb = |this: &mut Self| {
1080 this.hardbreak();
1081 if pos.is_last {
1082 this.cursor.next_line(this.is_at_crlf());
1083 }
1084 };
1085 if line.is_empty() {
1086 hb(self);
1087 continue;
1088 }
1089 if pos.is_first {
1090 self.ibox(config.offset);
1091 if cmnt.is_doc && matches!(prefix, "/**") {
1092 self.word(prefix);
1093 hb(self);
1094 prefix = " * ";
1095 continue;
1096 }
1097 }
1098
1099 self.word(line);
1100
1101 if pos.is_last {
1102 self.end();
1103 if !config.iso_no_break {
1104 hb(self);
1105 }
1106 } else {
1107 hb(self);
1108 }
1109 }
1110 }
1111 }
1112 CommentStyle::Trailing => {
1113 let Some(prefix) = cmnt.prefix() else { return };
1114 self.neverbreak();
1115 if !self.is_bol_or_only_ind() {
1116 self.nbsp();
1117 }
1118
1119 if !wrap_comments && cmnt.lines.len() == 1 {
1120 self.word(cmnt.lines.pop().unwrap());
1121 } else if wrap_comments {
1122 if cmnt.is_doc || matches!(cmnt.kind, ast::CommentKind::Line) {
1123 config.offset = 0;
1124 } else {
1125 config.offset = self.ind;
1126 }
1127 for (lpos, line) in cmnt.lines.into_iter().delimited() {
1128 if !line.is_empty() {
1129 self.print_wrapped_line(&line, prefix, config.offset, cmnt.is_doc);
1130 }
1131 if !lpos.is_last {
1132 config.hardbreak(&mut self.s);
1133 }
1134 }
1135 } else {
1136 self.visual_align();
1137 for (pos, line) in cmnt.lines.into_iter().delimited() {
1138 if !line.is_empty() {
1139 self.word(line);
1140 if !pos.is_last {
1141 self.hardbreak();
1142 }
1143 }
1144 }
1145 self.end();
1146 }
1147
1148 if !config.trailing_no_break {
1149 self.print_sep(Separator::Hardbreak);
1150 }
1151 }
1152
1153 CommentStyle::BlankLine => {
1154 if !self.last_token_is_break() && !self.is_bol_or_only_ind() {
1156 config.hardbreak(&mut self.s);
1157 self.cursor.next_line(self.is_at_crlf());
1158 }
1159
1160 let twice = match self.last_token() {
1162 Some(Token::String(s)) => ";" == s,
1163 Some(Token::Begin(_)) => true,
1164 Some(Token::End) => true,
1165 _ => false,
1166 };
1167 if twice {
1168 config.hardbreak(&mut self.s);
1169 self.cursor.next_line(self.is_at_crlf());
1170 }
1171 config.hardbreak(&mut self.s);
1172 self.cursor.next_line(self.is_at_crlf());
1173 }
1174 }
1175 }
1176
1177 fn peek_comment<'b>(&'b self) -> Option<&'b Comment>
1178 where
1179 'sess: 'b,
1180 {
1181 self.comments.peek()
1182 }
1183
1184 fn peek_comment_before<'b>(&'b self, pos: BytePos) -> Option<&'b Comment>
1185 where
1186 'sess: 'b,
1187 {
1188 self.comments.iter().take_while(|c| c.pos() < pos).find(|c| !c.style.is_blank())
1189 }
1190
1191 fn peek_mixed_comment_before(&self, pos: Option<BytePos>) -> bool {
1194 pos.is_some_and(|pos| {
1195 self.peek_comment().is_some_and(|cmnt| cmnt.pos() < pos && cmnt.style.is_mixed())
1196 })
1197 }
1198
1199 fn has_comment_before_with<F>(&self, pos: BytePos, f: F) -> bool
1200 where
1201 F: FnMut(&Comment) -> bool,
1202 {
1203 self.comments.iter().take_while(|c| c.pos() < pos).any(f)
1204 }
1205
1206 fn peek_comment_between<'b>(&'b self, pos_lo: BytePos, pos_hi: BytePos) -> Option<&'b Comment>
1207 where
1208 'sess: 'b,
1209 {
1210 self.comments
1211 .iter()
1212 .skip_while(|c| c.pos() < pos_lo)
1213 .take_while(|c| c.pos() < pos_hi)
1214 .find(|c| !c.style.is_blank())
1215 }
1216
1217 fn has_comment_between(&self, start_pos: BytePos, end_pos: BytePos) -> bool {
1218 self.has_comment_before_with(end_pos, |c| c.pos() > start_pos)
1219 }
1220
1221 fn has_breakable_comment_between(&self, start_pos: BytePos, end_pos: BytePos) -> bool {
1222 self.comments
1223 .iter()
1224 .filter(|comment| comment.pos() >= start_pos && comment.pos() < end_pos)
1225 .any(|comment| !comment.style.is_blank())
1226 }
1227
1228 pub(crate) fn next_comment(&mut self) -> Option<Comment> {
1229 self.comments.next()
1230 }
1231
1232 fn peek_trailing_comment<'b>(
1233 &'b self,
1234 span_pos: BytePos,
1235 next_pos: Option<BytePos>,
1236 ) -> Option<&'b Comment>
1237 where
1238 'sess: 'b,
1239 {
1240 self.comments.peek_trailing_in_file(self.file, span_pos, next_pos).map(|(cmnt, _)| cmnt)
1241 }
1242
1243 fn print_trailing_comment_inner(
1244 &mut self,
1245 span_pos: BytePos,
1246 next_pos: Option<BytePos>,
1247 config: Option<CommentConfig>,
1248 ) -> bool {
1249 let mut printed = 0;
1250 if let Some((_, n)) = self.comments.peek_trailing_in_file(self.file, span_pos, next_pos) {
1251 let config =
1252 config.unwrap_or(CommentConfig::skip_ws().mixed_no_break().mixed_prev_space());
1253 while printed <= n {
1254 let cmnt = self.comments.next().unwrap();
1255 if let Some(cmnt) = self.handle_comment(cmnt, config.trailing_no_break) {
1256 self.print_comment(cmnt, config);
1257 };
1258 printed += 1;
1259 }
1260 }
1261 printed != 0
1262 }
1263
1264 fn print_trailing_comment(&mut self, span_pos: BytePos, next_pos: Option<BytePos>) -> bool {
1265 self.print_trailing_comment_inner(span_pos, next_pos, None)
1266 }
1267
1268 fn print_trailing_comment_no_break(&mut self, span_pos: BytePos, next_pos: Option<BytePos>) {
1269 self.print_trailing_comment_inner(
1270 span_pos,
1271 next_pos,
1272 Some(CommentConfig::skip_ws().trailing_no_break().mixed_no_break().mixed_prev_space()),
1273 );
1274 }
1275
1276 fn print_remaining_comments(&mut self, skip_leading_ws: bool) {
1277 if self.peek_comment().is_none() && !self.is_bol_or_only_ind() {
1280 self.hardbreak();
1281 return;
1282 }
1283
1284 let mut is_leading = true;
1285 while let Some(cmnt) = self.next_comment() {
1286 if cmnt.style.is_blank() && skip_leading_ws && is_leading {
1287 continue;
1288 }
1289
1290 is_leading = false;
1291 if let Some(cmnt) = self.handle_comment(cmnt, false) {
1292 self.print_comment(cmnt, CommentConfig::default());
1293 } else if self.peek_comment().is_none() && !self.is_bol_or_only_ind() {
1294 self.hardbreak();
1295 }
1296 }
1297 }
1298
1299 fn preserve_doc_comment(&self, cmnt: &Comment) -> bool {
1301 self.directive_doc_groups.iter().any(|span| span.contains(cmnt.span))
1302 }
1303
1304 fn directive_doc_groups(file: &SourceFile, comments: &Comments) -> Vec<Span> {
1305 let line = |pos| file.lookup_line(file.relative_position(pos)).unwrap();
1306 let mut groups = Vec::new();
1307 let mut comments = comments.iter().peekable();
1308 while let Some(cmnt) = comments.next() {
1309 if !cmnt.is_doc || cmnt.kind != ast::CommentKind::Line {
1310 continue;
1311 }
1312
1313 let mut span = cmnt.span;
1314 let mut has_directive = cmnt.format_directives().next().is_some();
1315 while let Some(next) = comments.peek()
1316 && next.is_doc
1317 && next.kind == ast::CommentKind::Line
1318 && next.style.is_isolated()
1319 && line(span.hi()) + 1 == line(next.span.lo())
1320 {
1321 has_directive |= next.format_directives().next().is_some();
1322 span = span.to(next.span);
1323 comments.next();
1324 }
1325 if has_directive {
1326 groups.push(span);
1327 }
1328 }
1329 groups
1330 }
1331}
1332
1333#[derive(Clone, Copy)]
1334enum Skip {
1335 All,
1336 Leading { resettable: bool },
1337 Trailing,
1338}
1339
1340#[derive(Default, Clone, Copy)]
1341pub(crate) struct CommentConfig {
1342 skip_blanks: Option<Skip>,
1344 offset: isize,
1345
1346 iso_no_break: bool,
1348 trailing_no_break: bool,
1350 mixed_prev_space: bool,
1352 mixed_post_nbsp: bool,
1353 mixed_post_glued: bool,
1357 mixed_no_break_prev: bool,
1358 mixed_no_break_post: bool,
1359}
1360
1361impl CommentConfig {
1362 pub(crate) fn skip_ws() -> Self {
1363 Self { skip_blanks: Some(Skip::All), ..Default::default() }
1364 }
1365
1366 pub(crate) fn empty_block() -> Self {
1369 Self::skip_ws().mixed_no_break().mixed_prev_space().mixed_post_glued()
1370 }
1371
1372 pub(crate) fn skip_leading_ws(resettable: bool) -> Self {
1373 Self { skip_blanks: Some(Skip::Leading { resettable }), ..Default::default() }
1374 }
1375
1376 pub(crate) fn skip_trailing_ws() -> Self {
1377 Self { skip_blanks: Some(Skip::Trailing), ..Default::default() }
1378 }
1379
1380 pub(crate) const fn offset(mut self, off: isize) -> Self {
1381 self.offset = off;
1382 self
1383 }
1384
1385 pub(crate) const fn no_breaks(mut self) -> Self {
1386 self.iso_no_break = true;
1387 self.trailing_no_break = true;
1388 self.mixed_no_break_prev = true;
1389 self.mixed_no_break_post = true;
1390 self
1391 }
1392
1393 pub(crate) const fn trailing_no_break(mut self) -> Self {
1394 self.trailing_no_break = true;
1395 self
1396 }
1397
1398 pub(crate) const fn mixed_no_break(mut self) -> Self {
1399 self.mixed_no_break_prev = true;
1400 self.mixed_no_break_post = true;
1401 self
1402 }
1403
1404 pub(crate) const fn mixed_no_break_post(mut self) -> Self {
1405 self.mixed_no_break_post = true;
1406 self
1407 }
1408
1409 pub(crate) const fn mixed_prev_space(mut self) -> Self {
1410 self.mixed_prev_space = true;
1411 self
1412 }
1413
1414 pub(crate) const fn mixed_post_nbsp(mut self) -> Self {
1415 self.mixed_post_nbsp = true;
1416 self
1417 }
1418
1419 pub(crate) const fn mixed_post_glued(mut self) -> Self {
1420 self.mixed_post_nbsp = true;
1421 self.mixed_post_glued = true;
1422 self
1423 }
1424
1425 pub(crate) fn hardbreak_if_not_bol(&self, is_bol: bool, p: &mut pp::Printer) {
1426 if self.offset != 0 && !is_bol {
1427 self.hardbreak(p);
1428 } else {
1429 p.hardbreak_if_not_bol();
1430 }
1431 }
1432
1433 pub(crate) fn hardbreak(&self, p: &mut pp::Printer) {
1434 p.break_offset(SIZE_INFINITY as usize, self.offset);
1435 }
1436
1437 pub(crate) fn space(&self, p: &mut pp::Printer) {
1438 p.break_offset(1, self.offset);
1439 }
1440
1441 pub(crate) fn nbsp_or_space(&self, breaks: bool, p: &mut pp::Printer) {
1442 if breaks {
1443 self.space(p);
1444 } else {
1445 p.nbsp();
1446 }
1447 }
1448
1449 pub(crate) fn zerobreak(&self, p: &mut pp::Printer) {
1450 p.break_offset(0, self.offset);
1451 }
1452}
1453
1454fn snippet_with_tabs(s: String, tab_width: usize) -> String {
1455 let mut formatted = String::with_capacity(s.len());
1456 for line in s.split_inclusive('\n') {
1457 let (line, has_newline) =
1458 line.strip_suffix('\n').map_or((line, false), |line| (line, true));
1459 let line = line.strip_suffix('\r').unwrap_or(line);
1460 line_with_tabs(&mut formatted, line, tab_width, None);
1461 if has_newline {
1462 formatted.push('\n');
1463 }
1464 }
1465
1466 formatted
1467}
1468
1469fn style_doc_comment(style: DocCommentStyle, mut cmnt: Comment) -> Comment {
1473 match style {
1474 DocCommentStyle::Line if cmnt.kind == ast::CommentKind::Block => {
1475 let mut new_lines = Vec::new();
1476 for (pos, line) in cmnt.lines.iter().delimited() {
1477 if pos.is_first || pos.is_last {
1478 continue;
1480 }
1481
1482 let trimmed = line.trim_start();
1484 if let Some(content) = trimmed.strip_prefix('*') {
1485 new_lines.push(format!("///{content}"));
1486 } else if !trimmed.is_empty() {
1487 new_lines.push(format!("/// {trimmed}"));
1488 }
1489 }
1490
1491 cmnt.lines = new_lines;
1492 cmnt.kind = ast::CommentKind::Line;
1493 cmnt
1494 }
1495 DocCommentStyle::Block if cmnt.kind == ast::CommentKind::Line => {
1496 let mut new_lines = vec!["/**".to_string()];
1497
1498 for line in &cmnt.lines {
1499 new_lines.push(format!(" *{content}", content = &line[3..]))
1501 }
1502
1503 new_lines.push(" */".to_string());
1504 cmnt.lines = new_lines;
1505 cmnt.kind = ast::CommentKind::Block;
1506 cmnt
1507 }
1508 _ => cmnt,
1510 }
1511}