1use super::{CommentConfig, Separator, State};
2use crate::pp::{BreakToken, Printer, SIZE_INFINITY};
3use foundry_common::iter::IterDelimited;
4use foundry_config::fmt as config;
5use itertools::{Either, Itertools};
6use solar::parse::{
7 Cursor,
8 ast::{self, Span},
9 interface::BytePos,
10};
11use std::{borrow::Cow, fmt::Debug};
12
13pub(crate) trait LitExt<'ast> {
14 fn is_str_concatenation(&self) -> bool;
15}
16
17impl<'ast> LitExt<'ast> for ast::Lit<'ast> {
18 fn is_str_concatenation(&self) -> bool {
20 if let ast::LitKind::Str(_, _, parts) = &self.kind { !parts.is_empty() } else { false }
21 }
22}
23
24impl<'ast> State<'_, 'ast> {
26 pub(super) fn print_lit_inner(&mut self, lit: &'ast ast::Lit<'ast>, is_yul: bool) {
27 let ast::Lit { span, symbol, ref kind } = *lit;
28 if self.handle_span(span, false) {
29 return;
30 }
31
32 match *kind {
33 ast::LitKind::Str(kind, ..) => {
34 self.s.ibox(0);
35 let mut literals = lit.literals().peekable();
36 while let Some((span, symbol)) = literals.next() {
37 if !self.handle_span(span, false) {
38 let quote_pos = span.lo() + kind.prefix().len() as u32;
39 self.print_str_lit(kind, quote_pos, symbol.as_str());
40 }
41 if let Some((next_span, _)) = literals.peek() {
42 if !self.print_trailing_comment(span.hi(), Some(next_span.lo())) {
43 self.space_if_not_bol();
44 }
45 } else {
46 self.neverbreak();
47 }
48 }
49 self.end();
50 }
51 ast::LitKind::Number(_) | ast::LitKind::BigNumber(_) | ast::LitKind::Rational(..) => {
52 self.print_num_literal(symbol.as_str(), is_yul);
53 }
54 ast::LitKind::Address(value) => self.word(value.to_string()),
55 ast::LitKind::Bool(value) => self.word(if value { "true" } else { "false" }),
56 ast::LitKind::Err(_) => self.word(symbol.to_string()),
57 }
58 }
59
60 fn print_num_literal(&mut self, source: &str, is_yul: bool) {
61 fn strip_underscores_if(b: bool, s: &str) -> Cow<'_, str> {
62 if b && s.contains('_') { Cow::Owned(s.replace('_', "")) } else { Cow::Borrowed(s) }
63 }
64
65 fn add_underscores(
66 out: &mut String,
67 config: config::NumberUnderscore,
68 string: &str,
69 is_dec: bool,
70 is_yul: bool,
71 reversed: bool,
72 ) {
73 if !config.is_thousands() || !is_dec || is_yul || string.len() < 5 {
77 out.push_str(string);
78 return;
79 }
80
81 let chunks = if reversed {
82 Either::Left(string.as_bytes().chunks(3))
83 } else {
84 Either::Right(string.as_bytes().rchunks(3).rev())
85 }
86 .map(|chunk| std::str::from_utf8(chunk).unwrap());
87 for chunk in Itertools::intersperse(chunks, "_") {
88 out.push_str(chunk);
89 }
90 }
91
92 debug_assert!(source.is_ascii(), "{source:?}");
93
94 let config = self.config.number_underscore;
95 let is_dec = !["0x", "0b", "0o"].iter().any(|prefix| source.starts_with(prefix));
96
97 let (val, exp) = if is_dec {
98 source.split_once(['e', 'E']).unwrap_or((source, ""))
99 } else {
100 (source, "")
101 };
102 let (val, fract) = val.split_once('.').unwrap_or((val, ""));
103
104 let strip_underscores = !config.is_preserve() || is_yul;
105 let mut val = &strip_underscores_if(strip_underscores, val)[..];
106 let mut exp = &strip_underscores_if(strip_underscores, exp)[..];
107 let mut fract = &strip_underscores_if(strip_underscores, fract)[..];
108
109 let mut exp_sign = "";
112 if is_dec {
113 val = val.trim_start_matches(['0', '_']);
114 fract = fract.trim_end_matches(['0', '_']);
115 (exp_sign, exp) =
116 if let Some(exp) = exp.strip_prefix('-') { ("-", exp) } else { ("", exp) };
117 if exp.bytes().all(|b| b == b'0' || b == b'_') {
119 exp = "";
120 }
121 }
122
123 let mut out = String::with_capacity(source.len() * 2);
124 if val.is_empty() {
125 out.push('0');
126 } else {
127 add_underscores(&mut out, config, val, is_dec, is_yul, false);
128 }
129 if source.contains('.') {
130 out.push('.');
131 match (fract.is_empty(), exp.is_empty()) {
132 (false, false) => out.push_str(fract),
134 (false, true) => add_underscores(&mut out, config, fract, is_dec, is_yul, true),
136 (true, _) => out.push('0'),
138 };
139 }
140 if !exp.is_empty() {
141 out.push('e');
142 out.push_str(exp_sign);
143 add_underscores(&mut out, config, exp, is_dec, is_yul, false);
144 }
145
146 self.word(out);
147 }
148
149 pub(super) fn print_str_lit(&mut self, kind: ast::StrKind, quote_pos: BytePos, s: &str) {
151 self.print_comments(quote_pos, CommentConfig::default());
152 let s = self.str_lit_to_string(kind, quote_pos, s);
153 self.word(s);
154 }
155
156 fn str_lit_to_string(&self, kind: ast::StrKind, quote_pos: BytePos, s: &str) -> String {
158 let prefix = kind.prefix();
159 let quote = match self.config.quote_style {
160 config::QuoteStyle::Double => '\"',
161 config::QuoteStyle::Single => '\'',
162 config::QuoteStyle::Preserve => self.char_at(quote_pos).unwrap_or_default(),
163 };
164 debug_assert!(matches!(quote, '\"' | '\''), "{quote:?}");
165 let s = solar::parse::interface::data_structures::fmt::from_fn(move |f| {
166 if matches!(kind, ast::StrKind::Hex) {
167 match self.config.hex_underscore {
168 config::HexUnderscore::Preserve => {}
169 config::HexUnderscore::Remove | config::HexUnderscore::Bytes => {
170 let mut clean = s.to_string().replace('_', "");
171 if matches!(self.config.hex_underscore, config::HexUnderscore::Bytes) {
172 clean =
173 clean.chars().chunks(2).into_iter().map(|c| c.format("")).join("_");
174 }
175 return f.write_str(&clean);
176 }
177 };
178 }
179 f.write_str(s)
180 });
181 let mut s = format!("{prefix}{quote}{s}{quote}");
182
183 #[allow(unstable_name_collisions)]
185 if Cursor::new(&s).exactly_one().is_err() {
186 let other_quote = if quote == '\"' { '\'' } else { '\"' };
187 {
188 let s = unsafe { s.as_bytes_mut() };
189 s[prefix.len()] = other_quote as u8;
190 s[s.len() - 1] = other_quote as u8;
191 }
192 debug_assert!(Cursor::new(&s).exactly_one().map(|_| true).unwrap());
193 }
194
195 s
196 }
197
198 pub(super) fn print_tuple_empty(&mut self, pos_lo: BytePos, pos_hi: BytePos) {
199 if self.handle_span(Span::new(pos_lo, pos_hi), true) {
200 return;
201 }
202
203 self.print_inside_parens(|state| {
204 state.s.cbox(state.ind);
205 if let Some(cmnt) =
206 state.print_comments(pos_hi, CommentConfig::skip_ws().mixed_prev_space())
207 {
208 if cmnt.is_mixed() {
209 state.s.offset(-state.ind);
210 } else {
211 state.break_offset_if_not_bol(0, -state.ind, false);
212 }
213 }
214 state.end();
215 });
216 }
217
218 pub(super) fn print_tuple<'a, T, P, S>(
219 &mut self,
220 values: &'a [T],
221 pos_lo: BytePos,
222 pos_hi: BytePos,
223 mut print: P,
224 mut get_span: S,
225 format: ListFormat,
226 ) where
227 P: FnMut(&mut Self, &'a T),
228 S: FnMut(&T) -> Span,
229 {
230 if self.handle_span(Span::new(pos_lo, pos_hi), true) {
231 return;
232 }
233
234 if values.is_empty() {
235 self.print_tuple_empty(pos_lo, pos_hi);
236 return;
237 }
238
239 if !(values.len() == 1 && format.is_inline()) {
240 self.print_inside_parens(|state| {
242 state.commasep(values, pos_lo, pos_hi, print, get_span, format)
243 });
244 return;
245 }
246
247 self.print_inside_parens(|state| {
249 let span = get_span(&values[0]);
250 state.s.cbox(state.ind);
251 let skip_break = if state.peek_comment_before(span.hi()).is_some() {
252 state.hardbreak();
253 false
254 } else {
255 true
256 };
257
258 state.print_comments(span.lo(), CommentConfig::skip_ws().mixed_prev_space());
259 print(state, &values[0]);
260
261 if !state.print_trailing_comment(span.hi(), Some(pos_hi)) && skip_break {
264 state.neverbreak();
265 } else {
266 state.break_offset_if_not_bol(0, -state.ind, false);
267 }
268 state.end();
269 });
270 }
271
272 pub(super) fn print_array<'a, T, P, S>(
273 &mut self,
274 values: &'a [T],
275 span: Span,
276 print: P,
277 get_span: S,
278 ) where
279 P: FnMut(&mut Self, &'a T),
280 S: FnMut(&T) -> Span,
281 {
282 if self.handle_span(span, false) {
283 return;
284 }
285
286 self.print_word("[");
287 self.commasep(values, span.lo(), span.hi(), print, get_span, ListFormat::compact());
288 self.print_word("]");
289 }
290
291 pub(super) fn commasep_opening_logic<T, S>(
292 &mut self,
293 values: &[T],
294 mut get_span: S,
295 format: ListFormat,
296 manual_opening: bool,
297 ) -> bool
298 where
299 S: FnMut(&T) -> Span,
300 {
301 let Some(span) = values.first().map(&mut get_span) else {
302 return false;
303 };
304
305 if span.is_dummy()
308 && let Some(next_pos) = values.get(1).map(|v| get_span(v).lo())
309 && self.peek_comment_before(next_pos).is_some()
310 {
311 return true;
312 }
313
314 if let Some((cmnt_span, cmnt_style)) =
316 self.peek_comment_before(span.lo()).map(|c| (c.span, c.style))
317 {
318 let cmnt_disabled = self.inline_config.is_disabled(cmnt_span);
319 if self.cursor.enabled && cmnt_disabled && cmnt_style.is_isolated() {
321 self.print_sep(Separator::Hardbreak);
322 if !format.with_delimiters {
323 self.s.offset(self.ind);
324 }
325 };
326
327 if manual_opening {
330 self.hardbreak();
331 self.s.offset(self.ind);
332 return true;
333 }
334
335 let cmnt_config = if format.with_delimiters {
336 CommentConfig::skip_ws().mixed_no_break().mixed_prev_space()
337 } else {
338 CommentConfig::skip_ws().no_breaks().mixed_prev_space().offset(self.ind)
339 };
340 if let Some(last_style) = self.print_comments(span.lo(), cmnt_config) {
342 match (cmnt_style.is_mixed(), last_style.is_mixed()) {
343 (true, true) => {
344 if format.breaks_with_comments() {
345 self.hardbreak();
346 } else {
347 self.space();
348 }
349 if !format.with_delimiters && !cmnt_disabled {
350 self.s.offset(self.ind);
351 }
352 }
353 (false, true) => {
354 self.nbsp();
355 }
356 (false, false) if !format.with_delimiters && !cmnt_disabled => {
357 self.hardbreak();
358 self.s.offset(self.ind);
359 }
360 _ => {}
361 }
362 }
363 if self.cursor.enabled {
364 self.cursor.advance_to(span.lo(), true);
365 }
366 return true;
367 }
368
369 if self.cursor.enabled {
370 self.cursor.advance_to(span.lo(), true);
371 }
372
373 if !values.is_empty() && !format.with_delimiters {
374 format.print_break(true, values.len(), &mut self.s);
375 self.s.offset(self.ind);
376 return true;
377 }
378
379 false
380 }
381
382 pub(super) fn commasep<'a, T, P, S>(
383 &mut self,
384 values: &'a [T],
385 _pos_lo: BytePos,
386 pos_hi: BytePos,
387 mut print: P,
388 mut get_span: S,
389 format: ListFormat,
390 ) where
391 P: FnMut(&mut Self, &'a T),
392 S: FnMut(&T) -> Span,
393 {
394 if values.is_empty() {
395 return;
396 }
397
398 let has_comments =
401 self.peek_comment_before(get_span(&values[0]).lo()).is_some() ||
403 values.windows(2).any(|w| self.peek_comment_between(get_span(&w[0]).hi(), get_span(&w[1]).lo()).is_some()) ||
405 self.peek_comment_between(get_span(values.last().unwrap()).hi(), pos_hi).is_some();
407
408 let manual_opening =
412 format.is_consistent() && !format.with_delimiters && self.call_with_opts_and_args;
413 let manual_offset = !has_comments && manual_opening;
415
416 let is_single_without_cmnts = values.len() == 1 && !format.break_single && !has_comments;
417 let skip_first_break = if format.with_delimiters || format.is_inline() {
418 self.s.cbox(if format.no_ind { 0 } else { self.ind });
419 if is_single_without_cmnts {
420 true
421 } else {
422 self.commasep_opening_logic(values, &mut get_span, format, manual_opening)
423 }
424 } else {
425 let res = self.commasep_opening_logic(values, &mut get_span, format, manual_opening);
426 if !manual_offset {
427 self.s.cbox(if format.no_ind { 0 } else { self.ind });
428 }
429 res
430 };
431
432 if let Some(sym) = format.prev_symbol() {
433 self.word_space(sym);
434 } else if is_single_without_cmnts && format.with_space {
435 self.nbsp();
436 } else if !skip_first_break && !format.is_inline() {
437 format.print_break(true, values.len(), &mut self.s);
438 if manual_offset {
439 self.s.offset(self.ind);
440 }
441 }
442
443 if format.is_compact() && !(format.breaks_with_comments() && has_comments) {
444 self.s.cbox(0);
445 }
446
447 let mut last_delimiter_break = !format.with_delimiters;
448 let mut skip_last_break =
449 is_single_without_cmnts || !format.with_delimiters || format.is_inline();
450 for (i, value) in values.iter().enumerate() {
451 let is_last = i == values.len() - 1;
452 if self
453 .print_comments(get_span(value).lo(), CommentConfig::skip_ws().mixed_prev_space())
454 .is_some_and(|cmnt| cmnt.is_mixed())
455 && format.breaks_with_comments()
456 {
457 self.hardbreak(); }
459
460 if !(is_last && get_span(value).is_dummy()) {
462 print(self, value);
463 }
464
465 let next_span = if is_last { None } else { Some(get_span(&values[i + 1])) };
466 let next_pos = next_span.map(Span::lo).unwrap_or(pos_hi);
467 let cmnt_before_next =
468 self.peek_comment_before(next_pos).map(|cmnt| (cmnt.span, cmnt.style));
469
470 if !is_last {
471 if cmnt_before_next.is_some_and(|(cmnt_span, _)| {
473 let span = self.cursor.span(cmnt_span.lo());
474 self.inline_config.is_disabled(span)
475 && self.snippet(span).is_some_and(|snip| !snip.contains(','))
477 }) {
478 self.print_comments(
479 next_pos,
480 CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
481 );
482 }
483 self.print_word(",");
484 }
485
486 if !is_last
487 && format.breaks_with_comments()
488 && cmnt_before_next.is_some_and(|(cmnt_span, cmnt_style)| {
489 let disabled = self.inline_config.is_disabled(cmnt_span);
490 (cmnt_style.is_mixed() && !disabled) || (cmnt_style.is_isolated() && disabled)
491 })
492 {
493 self.hardbreak(); }
495
496 let comment_config = if !is_last || format.with_delimiters {
498 CommentConfig::skip_ws().mixed_no_break().mixed_prev_space()
499 } else {
500 CommentConfig::skip_ws().no_breaks().mixed_prev_space()
501 };
502 let with_trailing = self.print_comments(next_pos, comment_config).is_some();
503
504 if is_last && with_trailing {
505 if self.is_bol_or_only_ind() {
506 self.break_offset_if_not_bol(0, -self.ind, false);
509 } else {
510 self.s.break_offset(SIZE_INFINITY as usize, -self.ind);
511 }
512 skip_last_break = true;
513 last_delimiter_break = false;
514 }
515
516 if let Some(next_span) = next_span
518 && !self.is_bol_or_only_ind()
519 && !self.inline_config.is_disabled(next_span)
520 && !next_span.is_dummy()
521 {
522 format.print_break(false, values.len(), &mut self.s);
523 if manual_offset {
524 self.s.offset(self.ind);
525 }
526 }
527 }
528
529 if format.is_compact() && !(format.breaks_with_comments() && has_comments) {
530 self.end();
531 }
532 if !skip_last_break {
533 if let Some(sym) = format.post_symbol() {
534 format.print_break(false, values.len(), &mut self.s);
535 self.s.offset(-self.ind);
536 self.word(sym);
537 } else {
538 format.print_break(true, values.len(), &mut self.s);
539 self.s.offset(-self.ind);
540 }
541 } else if is_single_without_cmnts && format.with_space {
542 self.nbsp();
543 } else if let Some(sym) = format.post_symbol() {
544 self.nbsp();
545 self.word(sym);
546 }
547
548 if !manual_offset {
549 self.end();
550 }
551 self.cursor.advance_to(pos_hi, true);
552
553 if last_delimiter_break {
554 format.print_break(true, values.len(), &mut self.s);
555 }
556 }
557
558 pub(super) fn print_path(&mut self, path: &'ast ast::PathSlice, consistent_break: bool) {
559 if consistent_break {
560 self.s.cbox(self.ind);
561 } else {
562 self.s.ibox(self.ind);
563 }
564 for (pos, ident) in path.segments().iter().delimited() {
565 self.print_ident(ident);
566 if !pos.is_last {
567 if !self.emit_or_revert {
568 self.zerobreak();
569 }
570 self.word(".");
571 }
572 }
573 self.end();
574 }
575
576 pub(super) fn print_block_inner<T: Debug>(
577 &mut self,
578 block: &'ast [T],
579 block_format: BlockFormat,
580 mut print: impl FnMut(&mut Self, &'ast T),
581 mut get_block_span: impl FnMut(&'ast T) -> Span,
582 pos_hi: BytePos,
583 ) {
584 if block_format.attempt_single_line() && block.len() == 1 {
586 self.print_single_line_block(block, block_format, print, get_block_span);
587 return;
588 }
589
590 if block.is_empty() {
592 self.print_empty_block(block_format, pos_hi);
593 return;
594 }
595
596 self.block_depth += 1;
598
599 let block_lo = get_block_span(&block[0]).lo();
601 match block_format {
602 BlockFormat::NoBraces(None) => {
603 if !self.handle_span(self.cursor.span(block_lo), false) {
604 self.print_comments(block_lo, CommentConfig::skip_ws());
605 }
606 self.s.cbox(0);
607 }
608 BlockFormat::NoBraces(Some(offset)) => {
609 let enabled =
610 !self.inline_config.is_disabled(Span::new(block_lo, block_lo + BytePos(1)))
611 && !self.handle_span(self.cursor.span(block_lo), true);
612 match self
613 .peek_comment()
614 .and_then(|cmnt| (cmnt.span.hi() < block_lo).then_some((cmnt.span, cmnt.style)))
615 {
616 Some((span, style)) => {
617 if enabled {
618 if !self.inline_config.is_disabled(span) || style.is_isolated() {
620 self.cursor.advance_to(span.lo(), true);
621 self.break_offset(SIZE_INFINITY as usize, offset);
622 }
623 if let Some(cmnt) = self.print_comments(
624 block_lo,
625 CommentConfig::skip_leading_ws(false).offset(offset),
626 ) && !cmnt.is_mixed()
627 && !cmnt.is_blank()
628 {
629 self.s.offset(offset);
630 }
631 } else if style.is_isolated() {
632 self.print_sep_unhandled(Separator::Hardbreak);
633 self.s.offset(offset);
634 }
635 }
636 None => {
637 if enabled {
638 self.zerobreak();
639 self.s.offset(offset);
640 } else if self.cursor.enabled {
641 self.print_sep_unhandled(Separator::Space);
642 self.s.offset(offset);
643 self.cursor.advance_to(block_lo, true);
644 }
645 }
646 }
647 self.s.cbox(self.ind);
648 }
649 _ => {
650 self.print_word("{");
651 self.s.cbox(self.ind);
652 if !self.handle_span(self.cursor.span(block_lo), false)
653 && self
654 .print_comments(block_lo, CommentConfig::default())
655 .is_none_or(|cmnt| cmnt.is_mixed())
656 {
657 self.hardbreak_if_nonempty();
658 }
659 }
660 }
661
662 for (i, stmt) in block.iter().enumerate() {
664 let is_last = i == block.len() - 1;
665 print(self, stmt);
666
667 let is_disabled = self.inline_config.is_disabled(get_block_span(stmt));
668 let (next_enabled, next_lo) = if is_last {
669 (false, None)
670 } else {
671 let next_span = get_block_span(&block[i + 1]);
672 (
673 !self.inline_config.is_disabled(next_span),
674 self.peek_comment_before(next_span.lo()).is_none().then_some(next_span.lo()),
675 )
676 };
677
678 if !is_disabled
680 && next_enabled
681 && (!is_last
682 || self.peek_comment_before(pos_hi).is_some_and(|cmnt| cmnt.style.is_mixed()))
683 {
684 self.hardbreak_if_not_bol();
685 continue;
686 }
687 if is_disabled
690 && next_enabled
691 && let Some(next_lo) = next_lo
692 && self
693 .peek_comment_before(next_lo)
694 .is_none_or(|cmnt| self.inline_config.is_disabled(cmnt.span))
695 {
696 self.hardbreak_if_not_bol()
697 }
698 }
699
700 self.print_comments(
701 pos_hi,
702 CommentConfig::skip_trailing_ws().mixed_no_break().mixed_prev_space(),
703 );
704 if !block_format.breaks() {
705 if !self.last_token_is_break() && !self.is_beginning_of_line() {
706 self.hardbreak();
707 }
708 self.s.offset(-self.ind);
709 }
710 self.end();
711 if block_format.with_braces() {
712 self.print_word("}");
713 }
714
715 self.block_depth -= 1;
717 }
718
719 fn print_single_line_block<T: Debug>(
720 &mut self,
721 block: &'ast [T],
722 block_format: BlockFormat,
723 mut print: impl FnMut(&mut Self, &'ast T),
724 mut get_block_span: impl FnMut(&'ast T) -> Span,
725 ) {
726 self.s.cbox(self.ind);
727
728 match block_format {
729 BlockFormat::Compact(true) => {
730 self.scan_break(BreakToken { pre_break: Some("{"), ..Default::default() });
731 print(self, &block[0]);
732 self.print_comments(get_block_span(&block[0]).hi(), CommentConfig::default());
733 self.s.scan_break(BreakToken { post_break: Some("}"), ..Default::default() });
734 self.s.offset(-self.ind);
735 }
736 _ => {
737 self.word("{");
738 self.space();
739 print(self, &block[0]);
740 self.print_comments(get_block_span(&block[0]).hi(), CommentConfig::default());
741 self.space_if_not_bol();
742 self.s.offset(-self.ind);
743 self.word("}");
744 }
745 }
746
747 self.end();
748 }
749
750 fn print_empty_block(&mut self, block_format: BlockFormat, pos_hi: BytePos) {
751 let has_braces = block_format.with_braces();
752
753 if self.peek_comment_before(pos_hi).is_none_or(|c| c.style.is_trailing()) {
755 if self.config.bracket_spacing {
756 if has_braces {
757 self.word("{ }");
758 } else {
759 self.nbsp();
760 }
761 } else if has_braces {
762 self.word("{}");
763 }
764 self.print_comments(pos_hi, CommentConfig::skip_ws());
765 return;
766 }
767
768 if has_braces {
770 self.word("{");
771 }
772 let offset = if let BlockFormat::NoBraces(Some(off)) = block_format { off } else { 0 };
773 self.print_comments(
774 pos_hi,
775 self.cmnt_config()
776 .offset(offset)
777 .mixed_no_break()
778 .mixed_prev_space()
779 .mixed_post_glued(),
780 );
781 self.print_comments(
782 pos_hi,
783 CommentConfig::default().mixed_no_break().mixed_prev_space().mixed_post_glued(),
784 );
785 if has_braces {
786 self.word("}");
787 }
788 }
789}
790
791#[derive(Debug, Clone, Copy, PartialEq, Eq)]
793pub(crate) struct ListFormat {
794 kind: ListFormatKind,
796 no_ind: bool,
798 break_single: bool,
800 breaks_cmnts: bool,
802 with_space: bool,
804 with_delimiters: bool,
806}
807
808#[derive(Debug, Clone, Copy, PartialEq, Eq)]
810pub(crate) enum ListFormatKind {
811 AlwaysBreak,
813 Consistent,
815 Compact,
817 Inline,
819 Yul { sym_prev: Option<&'static str>, sym_post: Option<&'static str> },
821}
822
823impl Default for ListFormat {
824 fn default() -> Self {
825 Self {
826 kind: ListFormatKind::Consistent,
827 no_ind: false,
828 break_single: false,
829 breaks_cmnts: false,
830 with_space: false,
831 with_delimiters: true,
832 }
833 }
834}
835
836impl ListFormat {
837 pub(crate) const fn prev_symbol(&self) -> Option<&'static str> {
839 if let ListFormatKind::Yul { sym_prev, .. } = self.kind { sym_prev } else { None }
840 }
841
842 pub(crate) const fn post_symbol(&self) -> Option<&'static str> {
843 if let ListFormatKind::Yul { sym_post, .. } = self.kind { sym_post } else { None }
844 }
845
846 pub(crate) const fn is_consistent(&self) -> bool {
847 matches!(self.kind, ListFormatKind::Consistent)
848 }
849
850 pub(crate) const fn is_compact(&self) -> bool {
851 matches!(self.kind, ListFormatKind::Compact)
852 }
853
854 pub(crate) const fn is_inline(&self) -> bool {
855 matches!(self.kind, ListFormatKind::Inline)
856 }
857
858 pub(crate) const fn breaks_with_comments(&self) -> bool {
859 self.breaks_cmnts
860 }
861
862 pub(crate) fn inline() -> Self {
864 Self { kind: ListFormatKind::Inline, ..Default::default() }
865 }
866
867 pub(crate) fn consistent() -> Self {
868 Self { kind: ListFormatKind::Consistent, ..Default::default() }
869 }
870
871 pub(crate) fn compact() -> Self {
872 Self { kind: ListFormatKind::Compact, ..Default::default() }
873 }
874
875 pub(crate) fn always_break() -> Self {
876 Self {
877 kind: ListFormatKind::AlwaysBreak,
878 breaks_cmnts: true,
879 break_single: true,
880 with_delimiters: true,
881 ..Default::default()
882 }
883 }
884
885 pub(crate) fn yul(sym_prev: Option<&'static str>, sym_post: Option<&'static str>) -> Self {
886 Self {
887 kind: ListFormatKind::Yul { sym_prev, sym_post },
888 breaks_cmnts: true,
889 with_delimiters: true,
890 ..Default::default()
891 }
892 }
893
894 pub(crate) const fn without_ind(mut self, without: bool) -> Self {
895 if !self.is_inline() {
896 self.no_ind = without;
897 }
898 self
899 }
900
901 pub(crate) const fn break_single(mut self, value: bool) -> Self {
902 if !self.is_inline() {
903 self.break_single = value;
904 }
905 self
906 }
907
908 pub(crate) const fn break_cmnts(mut self) -> Self {
909 if !self.is_inline() {
910 self.breaks_cmnts = true;
911 }
912 self
913 }
914
915 pub(crate) const fn with_space(mut self) -> Self {
916 if !self.is_inline() {
917 self.with_space = true;
918 }
919 self
920 }
921
922 pub(crate) const fn with_delimiters(mut self, with: bool) -> Self {
923 if matches!(self.kind, ListFormatKind::Compact | ListFormatKind::Consistent) {
924 self.with_delimiters = with;
925 }
926 self
927 }
928
929 pub(crate) fn print_break(&self, soft: bool, elems: usize, p: &mut Printer) {
931 match self.kind {
932 ListFormatKind::Inline => p.nbsp(), ListFormatKind::AlwaysBreak if elems > 1 || (self.break_single && elems == 1) => {
934 p.hardbreak()
935 }
936 _ => {
937 if soft && !self.with_space {
938 p.zerobreak();
939 } else {
940 p.space();
941 }
942 }
943 }
944 }
945}
946
947#[derive(Debug, Clone, Copy, PartialEq, Eq)]
949#[expect(dead_code)]
950pub(crate) enum BlockFormat {
951 Regular,
952 Compact(bool),
955 NoBraces(Option<isize>),
958}
959
960impl BlockFormat {
961 pub(crate) const fn with_braces(&self) -> bool {
962 !matches!(self, Self::NoBraces(_))
963 }
964 pub(crate) const fn breaks(&self) -> bool {
965 matches!(self, Self::NoBraces(None))
966 }
967
968 pub(crate) const fn attempt_single_line(&self) -> bool {
969 matches!(self, Self::Compact(_))
970 }
971}