Skip to main content

forge_fmt/state/
sol.rs

1#![allow(clippy::too_many_arguments)]
2
3use super::{
4    ChainedNamedCall, CommentConfig, Separator, State,
5    common::{BlockFormat, ListFormat},
6};
7use crate::{
8    pp::SIZE_INFINITY,
9    state::{CallContext, common::LitExt},
10};
11use foundry_common::{comments::Comment, iter::IterDelimited};
12use foundry_config::fmt::{self as config, MultilineFuncHeaderStyle};
13use solar::{
14    ast::BoxSlice,
15    interface::SpannedOption,
16    parse::{
17        ast::{self, ImportItems, Span},
18        interface::BytePos,
19    },
20};
21use std::{collections::HashMap, fmt::Debug};
22
23#[rustfmt::skip]
24macro_rules! get_span {
25    () => { |value| value.span };
26    (()) => { |value| value.span() };
27}
28
29/// Language-specific pretty printing: Solidity.
30impl<'ast> State<'_, 'ast> {
31    pub(crate) fn print_source_unit(&mut self, source_unit: &'ast ast::SourceUnit<'ast>) {
32        // Figure out if the cursor needs to check for CR (`\r`).
33        if let Some(item) = source_unit.items.first() {
34            self.check_crlf(item.span.to(source_unit.items.last().unwrap().span));
35        }
36
37        let mut items = source_unit.items.iter().peekable();
38        let mut is_first = true;
39        while let Some(item) = items.next() {
40            // If imports shouldn't be sorted, or if the item is not an import, print it directly.
41            if !self.config.sort_imports || !matches!(item.kind, ast::ItemKind::Import(_)) {
42                self.print_item(item, is_first);
43                is_first = false;
44                if let Some(next_item) = items.peek() {
45                    self.separate_items(next_item, false);
46                }
47                continue;
48            }
49
50            // Otherwise, collect a group of consecutive imports and sort them before printing.
51            let mut import_group = vec![item];
52            while let Some(next_item) = items.peek() {
53                // Groups end when the next item is not an import or when there is a blank line.
54                if !matches!(next_item.kind, ast::ItemKind::Import(_))
55                    || self.has_comment_between(item.span.hi(), next_item.span.lo())
56                {
57                    break;
58                }
59                import_group.push(items.next().unwrap());
60            }
61
62            import_group.sort_by_key(|item| {
63                if let ast::ItemKind::Import(import) = &item.kind {
64                    import.path.value.as_str()
65                } else {
66                    unreachable!("Expected an import item")
67                }
68            });
69
70            for (pos, group_item) in import_group.iter().delimited() {
71                self.print_item(group_item, is_first);
72                is_first = false;
73
74                if !pos.is_last {
75                    self.hardbreak_if_not_bol();
76                }
77            }
78            if let Some(next_item) = items.peek() {
79                self.separate_items(next_item, false);
80            }
81        }
82
83        self.print_remaining_comments(is_first);
84    }
85
86    /// Prints a hardbreak if the item needs an isolated line break.
87    fn separate_items(&mut self, next_item: &'ast ast::Item<'ast>, advance: bool) {
88        if !item_needs_iso(&next_item.kind) {
89            return;
90        }
91        // A trailing directive can begin a doc group that continues before the next item.
92        if self
93            .directive_doc_groups
94            .iter()
95            .any(|group| group.lo() < self.cursor.pos && self.cursor.pos < group.hi())
96        {
97            return;
98        }
99        // Never isolate items within a `disable-start`/`disable-end` region, where the source
100        // layout is preserved verbatim. The cursor sits right past the line break that follows the
101        // previous item, so check the byte that was last copied from the source. Line-based
102        // directives such as `disable-line` only opt out of formatting that line's contents, so
103        // they keep the isolation break.
104        if self.cursor.pos > BytePos(0)
105            && self
106                .inline_config
107                .is_disabled_block(Span::new(self.cursor.pos - BytePos(1), self.cursor.pos))
108        {
109            return;
110        }
111        let span = next_item.span;
112
113        let cmnts = self
114            .comments
115            .iter()
116            .filter_map(|c| (c.pos() < span.lo()).then_some(c.style))
117            .collect::<Vec<_>>();
118
119        if let Some(first) = cmnts.first()
120            && let Some(last) = cmnts.last()
121        {
122            if !(first.is_blank() || last.is_blank()) {
123                self.hardbreak();
124                return;
125            }
126            if advance {
127                if self.peek_comment_before(span.lo()).is_some() {
128                    self.print_comments(span.lo(), CommentConfig::default());
129                } else if self.inline_config.is_disabled(span.shrink_to_lo()) {
130                    self.hardbreak();
131                    self.cursor.advance_to(span.lo(), true);
132                }
133            }
134        } else {
135            self.hardbreak();
136        }
137    }
138
139    fn print_item(&mut self, item: &'ast ast::Item<'ast>, skip_ws: bool) {
140        let ast::Item { ref docs, span, ref kind } = *item;
141        self.print_docs(docs);
142
143        // The comments preceding the item are printed before checking whether it is disabled,
144        // because printing a disabled item copies the source verbatim and drops every comment
145        // that ends before it.
146        let cmnt = self.print_comments(
147            span.lo(),
148            if skip_ws { CommentConfig::skip_leading_ws(false) } else { CommentConfig::default() },
149        );
150
151        if self.print_span_if_disabled(span) {
152            if !self.print_trailing_comment(span.hi(), None) {
153                self.print_sep(Separator::Hardbreak);
154            }
155            return;
156        }
157
158        if cmnt.is_some_and(|cmnt| cmnt.is_mixed()) {
159            self.zerobreak();
160        }
161
162        match kind {
163            ast::ItemKind::Pragma(pragma) => self.print_pragma(pragma),
164            ast::ItemKind::Import(import) => self.print_import(import),
165            ast::ItemKind::Using(using) => self.print_using(using),
166            ast::ItemKind::Contract(contract) => self.print_contract(contract, span),
167            ast::ItemKind::Function(func) => self.print_function(func),
168            ast::ItemKind::Variable(var) => self.print_var_def(var),
169            ast::ItemKind::Struct(strukt) => self.print_struct(strukt, span),
170            ast::ItemKind::Enum(enm) => self.print_enum(enm, span),
171            ast::ItemKind::Udvt(udvt) => self.print_udvt(udvt),
172            ast::ItemKind::Error(err) => self.print_error(err),
173            ast::ItemKind::Event(event) => self.print_event(event),
174        }
175
176        self.cursor.advance_to(span.hi(), true);
177        self.print_comments(span.hi(), CommentConfig::default());
178        self.print_trailing_comment(span.hi(), None);
179        self.hardbreak_if_not_bol();
180        self.cursor_next_line();
181    }
182
183    fn print_pragma(&mut self, pragma: &'ast ast::PragmaDirective<'ast>) {
184        self.word("pragma ");
185        match &pragma.tokens {
186            ast::PragmaTokens::Version(ident, semver_req) => {
187                self.print_ident(ident);
188                self.nbsp();
189                self.word(semver_req.to_string());
190            }
191            ast::PragmaTokens::Custom(a, b) => {
192                self.print_ident_or_strlit(a);
193                if let Some(b) = b {
194                    self.nbsp();
195                    self.print_ident_or_strlit(b);
196                }
197            }
198            ast::PragmaTokens::Verbatim(tokens) => {
199                self.print_tokens(tokens);
200            }
201        }
202        self.word(";");
203    }
204
205    fn print_commasep_aliases<'a, I>(&mut self, aliases: I)
206    where
207        I: Iterator<Item = &'a (ast::Ident, Option<ast::Ident>)>,
208        'ast: 'a,
209    {
210        for (pos, (ident, alias)) in aliases.delimited() {
211            self.print_ident(ident);
212            if let Some(alias) = alias {
213                self.word(" as ");
214                self.print_ident(alias);
215            }
216            if !pos.is_last {
217                self.word(",");
218                self.space();
219            }
220        }
221    }
222
223    fn print_import(&mut self, import: &'ast ast::ImportDirective<'ast>) {
224        let ast::ImportDirective { path, items } = import;
225        self.word("import ");
226
227        use config::NamespaceImportStyle as NIStyle;
228
229        match (items, self.config.namespace_import_style) {
230            (ImportItems::Plain(None), _) => {
231                self.print_ast_str_lit(path);
232            }
233
234            (ImportItems::Plain(Some(source_alias)), NIStyle::Preserve | NIStyle::PreferPlain)
235            | (ImportItems::Glob(source_alias), NIStyle::PreferPlain) => {
236                self.print_ast_str_lit(path);
237                self.word(" as ");
238                self.print_ident(source_alias);
239            }
240
241            (ImportItems::Glob(source_alias), NIStyle::Preserve | NIStyle::PreferGlob)
242            | (ImportItems::Plain(Some(source_alias)), NIStyle::PreferGlob) => {
243                self.word("*");
244                self.word(" as ");
245                self.print_ident(source_alias);
246                self.word(" from ");
247                self.print_ast_str_lit(path);
248            }
249
250            (ImportItems::Aliases(aliases), _) => {
251                // Check if we should keep single imports on one line
252                let use_single_line = self.config.single_line_imports && aliases.len() == 1;
253
254                if use_single_line {
255                    self.word("{");
256                    if self.config.bracket_spacing {
257                        self.nbsp();
258                    }
259                } else {
260                    self.s.cbox(self.ind);
261                    self.word("{");
262                    self.braces_break();
263                }
264
265                if self.config.sort_imports {
266                    let mut sorted: Vec<_> = aliases.iter().collect();
267                    sorted.sort_by_key(|(ident, _alias)| ident.name.as_str());
268                    self.print_commasep_aliases(sorted.into_iter());
269                } else {
270                    self.print_commasep_aliases(aliases.iter());
271                };
272
273                if use_single_line {
274                    if self.config.bracket_spacing {
275                        self.nbsp();
276                    }
277                    self.word("}");
278                } else {
279                    self.braces_break();
280                    self.s.offset(-self.ind);
281                    self.word("}");
282                    self.end();
283                }
284                self.word(" from ");
285                self.print_ast_str_lit(path);
286            }
287        }
288        self.word(";");
289    }
290
291    fn print_using(&mut self, using: &'ast ast::UsingDirective<'ast>) {
292        let ast::UsingDirective { list, ty, global } = using;
293        self.word("using ");
294        match list {
295            ast::UsingList::Single(path) => self.print_path(path, true),
296            ast::UsingList::Multiple(items) => {
297                self.s.cbox(self.ind);
298                self.word("{");
299                self.braces_break();
300                for (pos, (path, op)) in items.iter().delimited() {
301                    self.print_path(path, true);
302                    if let Some(op) = op {
303                        self.word(" as ");
304                        self.word(op.to_str());
305                    }
306                    if !pos.is_last {
307                        self.word(",");
308                        self.space();
309                    }
310                }
311                self.braces_break();
312                self.s.offset(-self.ind);
313                self.word("}");
314                self.end();
315            }
316        }
317        self.word(" for ");
318        if let Some(ty) = ty {
319            self.print_ty(ty);
320        } else {
321            self.word("*");
322        }
323        if *global {
324            self.word(" global");
325        }
326        self.word(";");
327    }
328
329    fn print_contract(&mut self, c: &'ast ast::ItemContract<'ast>, span: Span) {
330        let ast::ItemContract { kind, name, layout, bases, body } = c;
331        self.contract = Some(c);
332        self.cursor.advance_to(span.lo(), true);
333
334        // Position of the body's opening brace, needed to identify the comments that belong to
335        // the contract header. The `is` and `layout` clauses can appear in either order, so the
336        // header ends at whichever clause ends last.
337        let header_hi = bases
338            .last()
339            .map(|base| base.span().hi())
340            .max(layout.as_ref().map(|layout| layout.span.hi()))
341            .unwrap_or(name.span.hi());
342        let body_lo = body.first().map_or(span.hi(), |item| item.span.lo());
343        let brace = self.find_opening_brace(Span::new(header_hi, body_lo));
344
345        self.s.cbox(self.ind);
346        self.ibox(0);
347        self.cbox(0);
348        self.word_nbsp(kind.to_str());
349        self.print_ident(name);
350        self.nbsp();
351
352        if let Some(layout) = layout
353            && !self.handle_span(layout.span, false)
354        {
355            self.word("layout at ");
356            self.print_expr(layout.slot);
357            let breaks = !bases.is_empty() || !self.peek_mixed_comment_before(brace);
358            self.print_sep(Separator::SpaceOrNbsp(breaks));
359        }
360
361        if let Some(first) = bases.first().map(|base| base.span())
362            && let Some(last) = bases.last().map(|base| base.span())
363            && self.inline_config.is_disabled(first.to(last))
364        {
365            _ = self.handle_span(first.until(last), false);
366        } else if !bases.is_empty() {
367            self.word("is");
368            self.space();
369            let last = bases.len() - 1;
370            for (i, base) in bases.iter().enumerate() {
371                if !self.handle_span(base.span(), false) {
372                    self.print_modifier_call(base, false);
373                    if i != last {
374                        self.word(",");
375                        if self
376                            .print_comments(
377                                bases[i + 1].span().lo(),
378                                CommentConfig::skip_ws().mixed_prev_space().mixed_post_nbsp(),
379                            )
380                            .is_none()
381                        {
382                            self.space();
383                        }
384                    }
385                }
386            }
387            if self.print_trailing_comment(bases.last().unwrap().span().hi(), None) {
388                self.s.offset(-self.ind);
389            } else if self.peek_mixed_comment_before(brace) {
390                self.nbsp();
391            } else {
392                self.space();
393                self.s.offset(-self.ind);
394            }
395        }
396
397        // Print the comments preceding the opening brace, otherwise they get relocated into the
398        // contract body. They are glued to both the header and the brace, as breaking them apart
399        // turns them into trailing comments, which are relocated again on the next run.
400        while self.peek_mixed_comment_before(brace) {
401            let cmnt = self.next_comment().unwrap();
402            if let Some(cmnt) = self.handle_comment(cmnt, true) {
403                self.print_comment(cmnt, CommentConfig::skip_ws().mixed_no_break());
404            }
405            self.nbsp();
406        }
407        self.end();
408
409        self.print_word("{");
410        self.end();
411        if body.is_empty() {
412            match self.print_comments(span.hi(), CommentConfig::empty_block()) {
413                // Adjust the offset of the trailing break from comment printing
414                // so the closing brace is not indented
415                Some(_) if self.last_token_is_break() => self.s.offset(-self.ind),
416                Some(_) => {}
417                None if self.config.bracket_spacing => self.nbsp(),
418                None => {}
419            }
420            self.end();
421        } else {
422            // update block depth
423            self.block_depth += 1;
424
425            self.print_sep(Separator::Hardbreak);
426            if self.config.contract_new_lines {
427                self.hardbreak();
428            }
429            let body_lo = body[0].span.lo();
430            if self.peek_comment_before(body_lo).is_some() {
431                self.print_comments(body_lo, CommentConfig::skip_leading_ws(true));
432            }
433
434            let mut is_first = true;
435            let mut items = body.iter().peekable();
436            while let Some(item) = items.next() {
437                self.print_item(item, is_first);
438                is_first = false;
439                if let Some(next_item) = items.peek() {
440                    if self.inline_config.is_disabled(next_item.span) {
441                        _ = self.handle_span(next_item.span, false);
442                    } else {
443                        self.separate_items(next_item, true);
444                    }
445                }
446            }
447
448            let cmnt = self.print_comments(span.hi(), CommentConfig::skip_trailing_ws());
449            let mut glued = false;
450            if self.last_token_is_break() {
451                if self.config.contract_new_lines && cmnt.is_some_and(|cmnt| !cmnt.is_blank()) {
452                    self.print_sep(Separator::Hardbreak);
453                }
454                self.s.offset(-self.ind);
455            } else {
456                glued = self.glue_brace_to_trailing_comments(cmnt.is_some());
457            }
458            self.end();
459            if self.config.contract_new_lines && !glued {
460                self.hardbreak_if_nonempty();
461            }
462
463            // restore block depth
464            self.block_depth -= 1;
465        }
466        // The cursor is updated with the actual span; a disabled trailing comment of the last item
467        // may have already consumed source beyond the closing brace.
468        self.word("}");
469
470        self.cursor.advance_to(span.hi(), true);
471        self.contract = None;
472    }
473
474    /// Glues the closing brace of an item body to a trailing run of mixed comments.
475    ///
476    /// A trailing run of mixed comments ends in a string token; a break in between would
477    /// reclassify the last comment on the next run, so the brace is glued with a hard space.
478    /// Bodies that end with a pending break (the caller adjusts its offset instead), an existing
479    /// space, or verbatim source that already broke the line are left unchanged.
480    ///
481    /// Returns `true` if the brace was glued.
482    fn glue_brace_to_trailing_comments(&mut self, printed: bool) -> bool {
483        if printed
484            && !self.last_token_is_break()
485            && !self.last_token_is_space()
486            && !self.is_beginning_of_line()
487        {
488            self.nbsp();
489            return true;
490        }
491        false
492    }
493
494    fn print_struct(&mut self, strukt: &'ast ast::ItemStruct<'ast>, span: Span) {
495        let ast::ItemStruct { name, fields } = strukt;
496        let ind = if self.estimate_size(name.span) + 8 >= self.space_left() { self.ind } else { 0 };
497        self.s.ibox(self.ind);
498        self.word("struct");
499        self.space();
500        self.print_ident(name);
501        self.word(" {");
502        if !fields.is_empty() {
503            self.break_offset(SIZE_INFINITY as usize, ind);
504        }
505        self.s.ibox(0);
506        for var in fields.iter() {
507            self.print_var_def(var);
508            if !self.print_trailing_comment(var.span.hi(), None) {
509                self.hardbreak();
510            }
511        }
512        let cmnt_config =
513            if fields.is_empty() { CommentConfig::empty_block() } else { CommentConfig::skip_ws() };
514        let printed = self.print_comments(span.hi(), cmnt_config).is_some();
515        if self.last_token_is_break() {
516            if ind == 0 {
517                self.s.offset(-self.ind);
518            }
519        } else {
520            self.glue_brace_to_trailing_comments(printed);
521        }
522        self.end();
523        self.end();
524        self.word("}");
525    }
526
527    fn print_enum(&mut self, enm: &'ast ast::ItemEnum<'ast>, span: Span) {
528        let ast::ItemEnum { name, variants } = enm;
529        self.s.cbox(self.ind);
530        self.word("enum ");
531        self.print_ident(name);
532        self.word(" {");
533        self.hardbreak_if_nonempty();
534        let mut printed = false;
535        for (pos, ident) in variants.iter().delimited() {
536            self.print_comments(ident.span.lo(), CommentConfig::default());
537            self.print_ident(ident);
538            if !pos.is_last {
539                self.word(",");
540            }
541            printed = self.print_trailing_comment(ident.span.hi(), None);
542            if !printed {
543                self.hardbreak();
544            }
545        }
546        if self.print_comments(span.hi(), CommentConfig::skip_ws()).is_some() {
547            printed = true;
548        }
549        if self.last_token_is_break() {
550            self.s.offset(-self.ind);
551        } else {
552            self.glue_brace_to_trailing_comments(printed);
553        }
554        self.end();
555        self.word("}");
556    }
557
558    fn print_udvt(&mut self, udvt: &'ast ast::ItemUdvt<'ast>) {
559        let ast::ItemUdvt { name, ty } = udvt;
560        self.word("type ");
561        self.print_ident(name);
562        self.word(" is ");
563        self.print_ty(ty);
564        self.word(";");
565    }
566
567    // NOTE(rusowsky): Functions are the only source unit item that handle inline (disabled) format
568    fn print_function(&mut self, func: &'ast ast::ItemFunction<'ast>) {
569        let ast::ItemFunction { kind, ref header, ref body, body_span } = *func;
570        let ast::FunctionHeader {
571            name,
572            ref parameters,
573            visibility,
574            state_mutability: sm,
575            virtual_,
576            ref override_,
577            ref returns,
578            ..
579        } = *header;
580
581        self.s.cbox(self.ind);
582
583        // Print fn name and params
584        _ = self.handle_span(self.cursor.span(header.span.lo()), false);
585        self.print_word(kind.to_str());
586        if let Some(name) = name {
587            self.print_sep(Separator::Nbsp);
588            self.print_ident(&name);
589            self.cursor.advance_to(name.span.hi(), true);
590        }
591        self.s.cbox(-self.ind);
592        let header_style = self.config.multiline_func_header;
593        let params_format = match header_style {
594            MultilineFuncHeaderStyle::ParamsAlways => ListFormat::always_break(),
595            MultilineFuncHeaderStyle::All
596                if header.parameters.len() > 1 && !self.can_header_be_inlined(func) =>
597            {
598                ListFormat::always_break()
599            }
600            MultilineFuncHeaderStyle::AllParams
601                if !header.parameters.is_empty() && !self.can_header_be_inlined(func) =>
602            {
603                ListFormat::always_break()
604            }
605            _ => ListFormat::consistent().break_cmnts().break_single(
606                // ensure fn params are always breakable when there is a single `Contract.Struct`
607                parameters.len() == 1
608                    && matches!(
609                        &parameters[0].ty,
610                        ast::Type { kind: ast::TypeKind::Custom(ty), .. } if ty.segments().len() > 1
611                    ),
612            ),
613        };
614        self.print_parameter_list(parameters, parameters.span, params_format);
615        self.end();
616
617        // Map attributes to their corresponding comments
618        let (mut map, attributes, first_attrib_pos) =
619            AttributeCommentMapper::new(returns.as_ref(), body_span.lo()).build(self, header);
620
621        let mut handle_pre_cmnts = |this: &mut Self, span: Span| -> bool {
622            if this.inline_config.is_disabled(span)
623                // Note: `map` is still captured from the outer scope, which is fine.
624                && let Some((pre_cmnts, ..)) = map.remove(&span.lo())
625            {
626                for (pos, cmnt) in pre_cmnts.into_iter().delimited() {
627                    if pos.is_first && cmnt.style.is_isolated() && !this.is_bol_or_only_ind() {
628                        this.print_sep(Separator::Hardbreak);
629                    }
630                    if let Some(cmnt) = this.handle_comment(cmnt, false) {
631                        this.print_comment(cmnt, CommentConfig::skip_ws().mixed_post_nbsp());
632                    }
633                    if pos.is_last {
634                        return true;
635                    }
636                }
637            }
638            false
639        };
640
641        let skip_attribs = returns.as_ref().is_some_and(|ret| {
642            let attrib_span = Span::new(first_attrib_pos, ret.span.lo());
643            handle_pre_cmnts(self, attrib_span);
644            self.handle_span(attrib_span, false)
645        });
646        let skip_returns = {
647            let pos = if skip_attribs { self.cursor.pos } else { first_attrib_pos };
648            let ret_span = Span::new(pos, body_span.lo());
649            handle_pre_cmnts(self, ret_span);
650            self.handle_span(ret_span, false)
651        };
652
653        let attrib_box = self.config.multiline_func_header.params_first()
654            || (self.config.multiline_func_header.attrib_first()
655                && !self.can_header_params_be_inlined(func));
656        if attrib_box {
657            self.s.cbox(0);
658        }
659        if !(skip_attribs || skip_returns) {
660            // Print fn attributes in correct order
661            if let Some(v) = visibility {
662                self.print_fn_attribute(v.span, &mut map, &mut |s| s.word(v.to_str()));
663            }
664            if let Some(sm) = sm
665                && !matches!(*sm, ast::StateMutability::NonPayable)
666            {
667                self.print_fn_attribute(sm.span, &mut map, &mut |s| s.word(sm.to_str()));
668            }
669            if let Some(v) = virtual_ {
670                self.print_fn_attribute(v, &mut map, &mut |s| s.word("virtual"));
671            }
672            if let Some(o) = override_ {
673                self.print_fn_attribute(o.span, &mut map, &mut |s| s.print_override(o));
674            }
675            for m in attributes.iter().filter(|a| matches!(a.kind, AttributeKind::Modifier(_))) {
676                if let AttributeKind::Modifier(modifier) = m.kind {
677                    let is_base = self.is_modifier_a_base_contract(kind, modifier);
678                    self.print_fn_attribute(m.span, &mut map, &mut |s| {
679                        s.print_modifier_call(modifier, is_base)
680                    });
681                }
682            }
683        }
684        if !skip_returns
685            && let Some(ret) = returns
686            && !ret.is_empty()
687        {
688            if !self.handle_span(self.cursor.span(ret.span.lo()), false) {
689                if !self.is_bol_or_only_ind() && !self.last_token_is_space() {
690                    self.print_sep(Separator::Space);
691                }
692                self.cursor.advance_to(ret.span.lo(), true);
693                self.print_word("returns ");
694            }
695            self.print_parameter_list(
696                ret,
697                ret.span,
698                ListFormat::consistent(), // .with_cmnts_break(false),
699            );
700        }
701
702        // Print fn body
703        if let Some(body) = body {
704            if self.handle_span(self.cursor.span(body_span.lo()), false) {
705                // Print spacing if necessary. Updates cursor.
706            } else {
707                if let Some(cmnt) = self.peek_comment_before(body_span.lo()) {
708                    if cmnt.style.is_mixed() {
709                        // These shouldn't update the cursor, as we've already dealt with it above
710                        self.space();
711                        self.s.offset(-self.ind);
712                        self.print_comments(body_span.lo(), CommentConfig::skip_ws());
713                    } else {
714                        self.zerobreak();
715                        self.s.offset(-self.ind);
716                        self.print_comments(body_span.lo(), CommentConfig::skip_ws());
717                        self.s.offset(-self.ind);
718                    }
719                } else {
720                    // If there are no modifiers, overrides, nor returns never break
721                    if header.modifiers.is_empty()
722                        && header.override_.is_none()
723                        && returns.as_ref().is_none_or(|r| r.is_empty())
724                        && (header.visibility().is_none() || body.is_empty())
725                    {
726                        self.nbsp();
727                    } else {
728                        self.space();
729                        self.s.offset(-self.ind);
730                    }
731                }
732                self.cursor.advance_to(body_span.lo(), true);
733            }
734            self.print_word("{");
735            self.end();
736            if attrib_box {
737                self.end();
738            }
739
740            self.print_block_without_braces(body, body_span.hi(), Some(self.ind));
741            if self.cursor.enabled || self.cursor.pos < body_span.hi() {
742                self.print_word("}");
743                self.cursor.advance_to(body_span.hi(), true);
744            }
745        } else {
746            self.print_comments(body_span.lo(), CommentConfig::skip_ws().mixed_prev_space());
747            self.end();
748            if attrib_box {
749                self.end();
750            }
751            self.neverbreak();
752            self.print_word(";");
753        }
754
755        if let Some(cmnt) = self.peek_trailing_comment(body_span.hi(), None) {
756            if cmnt.is_doc {
757                // trailing doc comments after the fn body are isolated
758                // these shouldn't update the cursor, as this is our own formatting
759                self.hardbreak();
760                self.hardbreak();
761            }
762            self.print_trailing_comment(body_span.hi(), None);
763        }
764    }
765
766    fn print_fn_attribute(
767        &mut self,
768        span: Span,
769        map: &mut AttributeCommentMap,
770        print_fn: &mut dyn FnMut(&mut Self),
771    ) {
772        match map.remove(&span.lo()) {
773            Some((pre_cmnts, inner_cmnts, post_cmnts)) => {
774                // Print preceding comments. The separator before the attribute is printed below,
775                // so a mixed comment must not add one of its own or the two become a blank line.
776                let mut previous_mixed = false;
777                for cmnt in pre_cmnts {
778                    // A line comment after a mixed comment becomes isolated once the header wraps.
779                    if previous_mixed
780                        && cmnt.style.is_trailing()
781                        && matches!(cmnt.kind, ast::CommentKind::Line)
782                    {
783                        self.hardbreak_if_not_bol();
784                    }
785                    previous_mixed = cmnt.style.is_mixed();
786                    let Some(cmnt) = self.handle_comment(cmnt, false) else {
787                        continue;
788                    };
789                    self.print_comment(
790                        cmnt,
791                        CommentConfig::default().mixed_no_break_post().mixed_prev_space(),
792                    );
793                }
794                // Push the inner comments back to the queue, so that they are printed in their
795                // intended place.
796                for cmnt in inner_cmnts.into_iter().rev() {
797                    self.comments.push_front(cmnt);
798                }
799                let enabled = if self.handle_span(span, false) {
800                    false
801                } else {
802                    if !self.is_bol_or_only_ind() {
803                        self.space();
804                    }
805                    self.ibox(0);
806                    print_fn(self);
807                    self.cursor.advance_to(span.hi(), true);
808                    true
809                };
810                // Print subsequent comments.
811                for cmnt in post_cmnts {
812                    let Some(cmnt) = self.handle_comment(cmnt, false) else {
813                        continue;
814                    };
815                    self.print_comment(cmnt, CommentConfig::default().mixed_prev_space());
816                }
817                if enabled {
818                    self.end();
819                }
820            }
821            // Fallback for attributes not in the map (should never happen)
822            None => {
823                if !self.is_bol_or_only_ind() {
824                    self.space();
825                }
826                print_fn(self);
827                self.cursor.advance_to(span.hi(), true);
828            }
829        }
830    }
831
832    fn is_modifier_a_base_contract(
833        &self,
834        kind: ast::FunctionKind,
835        modifier: &'ast ast::Modifier<'ast>,
836    ) -> bool {
837        // Add `()` in functions when the modifier is a base contract.
838        // HACK: heuristics:
839        // 1. exactly matches the name of a base contract as declared in the `contract is`;
840        // this does not account for inheritance;
841        let is_contract_base = self.contract.is_some_and(|contract| {
842            contract
843                .bases
844                .iter()
845                .any(|contract_base| contract_base.name.to_string() == modifier.name.to_string())
846        });
847        // 2. assume that title case names in constructors are bases.
848        // LEGACY: constructors used to also be `function NameOfContract...`; not checked.
849        let is_constructor = matches!(kind, ast::FunctionKind::Constructor);
850        // LEGACY: we are checking the beginning of the path, not the last segment.
851        is_contract_base
852            || (is_constructor
853                && modifier.name.first().name.as_str().starts_with(char::is_uppercase))
854    }
855
856    fn print_error(&mut self, err: &'ast ast::ItemError<'ast>) {
857        let ast::ItemError { name, parameters } = err;
858        self.word("error ");
859        self.print_ident(name);
860        self.print_parameter_list(
861            parameters,
862            parameters.span,
863            if self.config.prefer_compact.errors() {
864                ListFormat::compact()
865            } else {
866                ListFormat::consistent()
867            },
868        );
869        self.word(";");
870    }
871
872    fn print_event(&mut self, event: &'ast ast::ItemEvent<'ast>) {
873        let ast::ItemEvent { name, parameters, anonymous } = event;
874        self.word("event ");
875        self.print_ident(name);
876        self.print_parameter_list(
877            parameters,
878            parameters.span,
879            if self.config.prefer_compact.events() {
880                ListFormat::compact().break_cmnts()
881            } else {
882                ListFormat::consistent().break_cmnts()
883            },
884        );
885        if *anonymous {
886            self.word(" anonymous");
887        }
888        self.word(";");
889    }
890
891    fn print_var_def(&mut self, var: &'ast ast::VariableDefinition<'ast>) {
892        self.print_var(var, true);
893        self.word(";");
894    }
895
896    /// Prints the RHS of an assignment or variable initializer.
897    fn print_assign_rhs(
898        &mut self,
899        rhs: &'ast ast::Expr<'ast>,
900        lhs_size: usize,
901        space_left: usize,
902        ty: Option<&ast::TypeKind<'ast>>,
903        cache: bool,
904    ) {
905        // Only measure assignments that can break, before printing consumes leading comments.
906        let rhs_layout = (!self.inline_assignments).then(|| {
907            // Check if the total expression overflows but the RHS would fit alone on a new line.
908            // This helps keep the RHS together on a single line when possible.
909            let rhs_size = if is_binary_expr(&rhs.kind)
910                && !self.has_comment_between(rhs.span.lo(), rhs.span.hi())
911            {
912                self.estimate_binary_size(rhs)
913            } else if assignment_member_depth(rhs) >= 2
914                && self.peek_comment_before(rhs.span.lo()).is_none()
915            {
916                // These chains can break before a member after collapsing their terminal
917                // delimiters. Size that collapsed form before choosing the
918                // assignment break instead.
919                self.estimate_assignment_size(rhs.span)
920            } else {
921                self.estimate_size(rhs.span)
922            };
923            let overflows = lhs_size + rhs_size >= space_left;
924            let fits_alone = rhs_size + self.config.tab_width < space_left;
925            let fits_alone_no_cmnts =
926                fits_alone && !self.has_comment_between(rhs.span.lo(), rhs.span.hi());
927            let force_break = overflows && fits_alone_no_cmnts;
928            (rhs_size, fits_alone, fits_alone_no_cmnts, force_break)
929        });
930
931        if lhs_size <= space_left {
932            self.neverbreak();
933        }
934
935        // Handle comments before the RHS expression
936        if let Some(cmnt) = self.peek_comment_before(rhs.span.lo())
937            && self.inline_config.is_disabled(cmnt.span)
938        {
939            self.print_sep(Separator::Nbsp);
940        }
941        if self
942            .print_comments(
943                rhs.span.lo(),
944                CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
945            )
946            .is_some_and(|cmnt| cmnt.is_trailing())
947        {
948            self.break_offset_if_not_bol(SIZE_INFINITY as usize, self.ind, false);
949        }
950
951        // A certified inline body must not acquire source-dependent assignment hard breaks.
952        let Some((rhs_size, fits_alone, fits_alone_no_cmnts, force_break)) = rhs_layout else {
953            self.nbsp();
954            self.neverbreak();
955            self.print_expr(rhs);
956            self.var_init = cache;
957            return;
958        };
959
960        // Match on expression kind to determine formatting strategy
961        match &rhs.kind {
962            ast::ExprKind::Lit(lit, ..) if lit.is_str_concatenation() => {
963                // String concatenations stay on the same line with nbsp
964                self.print_sep(Separator::Nbsp);
965                self.neverbreak();
966                self.s.ibox(self.ind);
967                self.print_expr(rhs);
968                self.end();
969            }
970            ast::ExprKind::Lit(..) if ty.is_none() && !fits_alone => {
971                // Long string in assign expr goes on its own line
972                self.print_sep(Separator::Space);
973                self.s.offset(self.ind);
974                self.print_expr(rhs);
975            }
976            ast::ExprKind::Binary(lhs, op, _) => {
977                let print_inline = |this: &mut Self| {
978                    this.print_sep(Separator::Nbsp);
979                    this.neverbreak();
980                    this.print_expr(rhs);
981                };
982                let print_with_break = |this: &mut Self, force_break: bool| {
983                    if !this.is_bol_or_only_ind() {
984                        if force_break {
985                            this.print_sep(Separator::Hardbreak);
986                        } else {
987                            this.print_sep(Separator::Space);
988                        }
989                    }
990                    this.s.offset(this.ind);
991                    this.s.ibox(this.ind);
992                    this.print_expr(rhs);
993                    this.end();
994                };
995
996                // Binary expressions: check if we need to break and indent
997                if force_break {
998                    print_with_break(self, true);
999                } else if self.estimate_lhs_size(rhs, op) + lhs_size > space_left {
1000                    if has_complex_successor(&rhs.kind, true)
1001                        && get_callee_head_size(lhs) + lhs_size <= space_left
1002                    {
1003                        // Keep complex exprs (where callee fits) inline, as they will have breaks
1004                        if is_call(&lhs.kind) {
1005                            self.s.ibox(-self.ind);
1006                            print_inline(self);
1007                            self.end();
1008                        } else {
1009                            print_inline(self);
1010                        }
1011                    } else {
1012                        print_with_break(self, false);
1013                    }
1014                }
1015                // Otherwise, if expr fits, ensure no breaks
1016                else {
1017                    print_inline(self);
1018                }
1019            }
1020            _ => {
1021                // General case: handle calls, complex successors, and other expressions
1022                let callee_doesnt_fit = if let ast::ExprKind::Call(call_expr, ..) = &rhs.kind {
1023                    let callee_size = get_callee_head_size(call_expr);
1024                    callee_size + lhs_size > space_left
1025                        && callee_size + self.config.tab_width < space_left
1026                } else {
1027                    false
1028                };
1029
1030                if (lhs_size + 1 >= space_left && !is_call_chain(&rhs.kind, false))
1031                    || callee_doesnt_fit
1032                {
1033                    self.s.ibox(self.ind);
1034                } else {
1035                    self.s.ibox(0);
1036                };
1037
1038                if has_complex_successor(&rhs.kind, true)
1039                    && !matches!(&rhs.kind, ast::ExprKind::Member(..))
1040                {
1041                    // delegate breakpoints to `self.commasep(..)` for complex successors
1042                    if !self.is_bol_or_only_ind() {
1043                        let needs_offset = !callee_doesnt_fit
1044                            && rhs_size + lhs_size + 1 >= space_left
1045                            && fits_alone_no_cmnts;
1046                        let separator = if callee_doesnt_fit || needs_offset {
1047                            Separator::Space
1048                        } else {
1049                            Separator::Nbsp
1050                        };
1051                        self.print_sep(separator);
1052                        if needs_offset {
1053                            self.s.offset(self.ind);
1054                        }
1055                    }
1056                } else {
1057                    if !self.is_bol_or_only_ind() {
1058                        self.print_sep_unhandled(Separator::Space);
1059                    }
1060                    // apply type-dependent indentation if type info is available
1061                    if let Some(ty) = ty
1062                        && matches!(ty, ast::TypeKind::Elementary(..) | ast::TypeKind::Mapping(..))
1063                    {
1064                        self.s.offset(self.ind);
1065                    }
1066                }
1067                self.print_expr(rhs);
1068                self.end();
1069            }
1070        }
1071
1072        self.var_init = cache;
1073    }
1074
1075    fn print_var(&mut self, var: &'ast ast::VariableDefinition<'ast>, is_var_def: bool) {
1076        let ast::VariableDefinition {
1077            span,
1078            ty,
1079            visibility,
1080            mutability,
1081            data_location,
1082            override_,
1083            indexed,
1084            name,
1085            initializer,
1086        } = var;
1087
1088        if self.handle_span(*span, false) {
1089            return;
1090        }
1091
1092        // NOTE(rusowsky): this is hacky but necessary to properly estimate if we figure out if we
1093        // have double breaks (which should have double indentation) or not.
1094        // Alternatively, we could achieve the same behavior with a new box group that supports
1095        // "continuation" which would only increase indentation if its parent box broke.
1096        let init_space_left = self.space_left();
1097        let mut pre_init_size = self.estimate_size(ty.span);
1098
1099        // Non-elementary types use commasep which has its own padding.
1100        self.s.ibox(0);
1101        if override_.is_some() {
1102            self.s.cbox(self.ind);
1103        } else {
1104            self.s.ibox(self.ind);
1105        }
1106        self.print_ty(ty);
1107
1108        self.print_attribute(visibility.map(|v| v.to_str()), is_var_def, &mut pre_init_size);
1109        self.print_attribute(mutability.map(|m| m.to_str()), is_var_def, &mut pre_init_size);
1110        self.print_attribute(data_location.map(|d| d.to_str()), is_var_def, &mut pre_init_size);
1111
1112        if let Some(override_) = override_ {
1113            if self
1114                .print_comments(override_.span.lo(), CommentConfig::skip_ws().mixed_prev_space())
1115                .is_none()
1116            {
1117                self.print_sep(Separator::SpaceOrNbsp(is_var_def));
1118            }
1119            self.ibox(0);
1120            self.print_override(override_);
1121            pre_init_size += self.estimate_size(override_.span) + 1;
1122        }
1123
1124        if *indexed {
1125            self.print_attribute(indexed.then_some("indexed"), is_var_def, &mut pre_init_size);
1126        }
1127
1128        if let Some(ident) = name {
1129            self.print_sep(Separator::SpaceOrNbsp(is_var_def && override_.is_none()));
1130            self.print_comments(
1131                ident.span.lo(),
1132                CommentConfig::skip_ws().mixed_no_break().mixed_post_nbsp(),
1133            );
1134            self.print_ident(ident);
1135            pre_init_size += self.estimate_size(ident.span) + 1;
1136        }
1137        if let Some(init) = initializer {
1138            let cache = self.var_init;
1139            self.var_init = true;
1140
1141            pre_init_size += 2;
1142            self.print_word(" =");
1143            if override_.is_some() {
1144                self.end();
1145            }
1146            self.end();
1147
1148            self.print_assign_rhs(init, pre_init_size, init_space_left, Some(&ty.kind), cache);
1149        } else {
1150            if override_.is_some() {
1151                self.end();
1152            }
1153            self.end();
1154        }
1155        self.end();
1156    }
1157
1158    fn print_attribute(
1159        &mut self,
1160        attribute: Option<&'static str>,
1161        is_var_def: bool,
1162        size: &mut usize,
1163    ) {
1164        if let Some(s) = attribute {
1165            self.print_sep(Separator::SpaceOrNbsp(is_var_def));
1166            self.print_word(s);
1167            *size += s.len() + 1;
1168        }
1169    }
1170
1171    fn print_parameter_list(
1172        &mut self,
1173        parameters: &'ast [ast::VariableDefinition<'ast>],
1174        span: Span,
1175        format: ListFormat,
1176    ) {
1177        if self.handle_span(span, false) {
1178            return;
1179        }
1180
1181        self.print_tuple(
1182            parameters,
1183            span.lo(),
1184            span.hi(),
1185            |fmt, var| fmt.print_var(var, false),
1186            get_span!(),
1187            format,
1188        );
1189    }
1190
1191    fn print_ident_or_strlit(&mut self, value: &'ast ast::IdentOrStrLit) {
1192        match value {
1193            ast::IdentOrStrLit::Ident(ident) => self.print_ident(ident),
1194            ast::IdentOrStrLit::StrLit(strlit) => self.print_ast_str_lit(strlit),
1195        }
1196    }
1197
1198    /// Prints a raw AST string literal, which is unescaped.
1199    fn print_ast_str_lit(&mut self, strlit: &'ast ast::StrLit) {
1200        self.print_str_lit(ast::StrKind::Str, strlit.span.lo(), strlit.value.as_str());
1201    }
1202
1203    fn print_ty(&mut self, ty: &'ast ast::Type<'ast>) {
1204        if self.handle_span(ty.span, false) {
1205            return;
1206        }
1207
1208        match &ty.kind {
1209            &ast::TypeKind::Elementary(ty) => 'b: {
1210                match ty {
1211                    // `address payable` is normalized to `address`.
1212                    ast::ElementaryType::Address(true) => {
1213                        self.word("address payable");
1214                        break 'b;
1215                    }
1216                    // Integers are normalized to long form.
1217                    ast::ElementaryType::Int(size) | ast::ElementaryType::UInt(size) => {
1218                        match (self.config.int_types, size.bits_raw()) {
1219                            (config::IntTypes::Short, 0 | 256)
1220                            | (config::IntTypes::Preserve, 0) => {
1221                                let short = match ty {
1222                                    ast::ElementaryType::Int(_) => "int",
1223                                    ast::ElementaryType::UInt(_) => "uint",
1224                                    _ => unreachable!(),
1225                                };
1226                                self.word(short);
1227                                break 'b;
1228                            }
1229                            _ => {}
1230                        }
1231                    }
1232                    _ => {}
1233                }
1234                self.word(ty.to_abi_str());
1235            }
1236            ast::TypeKind::Array(ast::TypeArray { element, size }) => {
1237                self.print_ty(element);
1238                let open_bracket = self
1239                    .find_uncommented_char(Span::new(element.span.hi(), ty.span.hi()), '[')
1240                    .unwrap();
1241                self.print_comments(
1242                    open_bracket,
1243                    CommentConfig::skip_ws().mixed_prev_space().mixed_post_nbsp(),
1244                );
1245                if let Some(size) = size {
1246                    self.word("[");
1247                    self.print_expr(size);
1248                    self.word("]");
1249                } else {
1250                    self.word("[]");
1251                }
1252            }
1253            ast::TypeKind::Function(ast::TypeFunction {
1254                parameters,
1255                visibility,
1256                state_mutability,
1257                returns,
1258            }) => {
1259                self.cbox(0);
1260                self.word("function");
1261                self.print_parameter_list(parameters, parameters.span, ListFormat::inline());
1262
1263                if let Some(v) = visibility {
1264                    self.space();
1265                    self.word(v.to_str());
1266                }
1267                if let Some(sm) = state_mutability
1268                    && !matches!(**sm, ast::StateMutability::NonPayable)
1269                {
1270                    self.space();
1271                    self.word(sm.to_str());
1272                }
1273                if let Some(ret) = returns
1274                    && !ret.is_empty()
1275                {
1276                    self.nbsp();
1277                    self.word("returns");
1278                    self.nbsp();
1279                    self.print_parameter_list(
1280                        ret,
1281                        ret.span,
1282                        ListFormat::consistent(), // .with_cmnts_break(false),
1283                    );
1284                }
1285                self.end();
1286            }
1287            ast::TypeKind::Mapping(ast::TypeMapping { key, key_name, value, value_name }) => {
1288                self.word("mapping(");
1289                self.s.cbox(0);
1290                if let Some(cmnt) = self.peek_comment_before(key.span.lo()) {
1291                    if cmnt.style.is_mixed() {
1292                        self.print_comments(
1293                            key.span.lo(),
1294                            CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1295                        );
1296                        self.break_offset_if_not_bol(SIZE_INFINITY as usize, 0, false);
1297                    } else {
1298                        self.print_comments(key.span.lo(), CommentConfig::skip_ws());
1299                    }
1300                }
1301                // Fitting a mapping in one line takes, at least, 16 chars (one-char var name):
1302                // 'mapping(' + {key} + ' => ' {value} ') ' + {name} + ';'
1303                // To be more conservative, we use 18 to decide whether to force a break or not.
1304                else if 18
1305                    + self.estimate_type_size(key)
1306                    + key_name.map(|k| self.estimate_size(k.span)).unwrap_or(0)
1307                    + self.estimate_type_size(value)
1308                    + value_name.map(|v| self.estimate_size(v.span)).unwrap_or(0)
1309                    >= self.space_left()
1310                {
1311                    self.hardbreak();
1312                } else {
1313                    self.zerobreak();
1314                }
1315                self.s.cbox(0);
1316                self.print_ty(key);
1317                if let Some(ident) = key_name {
1318                    if self
1319                        .print_comments(
1320                            ident.span.lo(),
1321                            CommentConfig::skip_ws()
1322                                .mixed_no_break()
1323                                .mixed_prev_space()
1324                                .mixed_post_nbsp(),
1325                        )
1326                        .is_none()
1327                    {
1328                        self.nbsp();
1329                    }
1330                    self.print_ident(ident);
1331                }
1332                // NOTE(rusowsky): unless we add more spans to solar, using `value.span.lo()`
1333                // consumes "comment6" of which should be printed after the `=>`
1334                self.print_comments(
1335                    value.span.lo(),
1336                    CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1337                );
1338                if !self.is_bol_or_only_ind() {
1339                    self.space();
1340                }
1341                self.s.offset(self.ind);
1342                self.word("=> ");
1343                self.s.ibox(self.ind);
1344                self.print_ty(value);
1345                if let Some(ident) = value_name {
1346                    self.neverbreak();
1347                    if self
1348                        .print_comments(
1349                            ident.span.lo(),
1350                            CommentConfig::skip_ws()
1351                                .mixed_no_break()
1352                                .mixed_prev_space()
1353                                .mixed_post_nbsp(),
1354                        )
1355                        .is_none()
1356                    {
1357                        self.nbsp();
1358                    }
1359                    self.print_ident(ident);
1360                    if self
1361                        .peek_comment_before(ty.span.hi())
1362                        .is_some_and(|cmnt| cmnt.style.is_mixed())
1363                    {
1364                        self.neverbreak();
1365                        self.print_comments(
1366                            value.span.lo(),
1367                            CommentConfig::skip_ws().mixed_no_break(),
1368                        );
1369                    }
1370                }
1371                self.end();
1372                self.end();
1373                if self
1374                    .print_comments(
1375                        ty.span.hi(),
1376                        CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1377                    )
1378                    .is_some_and(|cmnt| !cmnt.is_mixed())
1379                {
1380                    self.break_offset_if_not_bol(0, -self.ind, false);
1381                } else {
1382                    self.zerobreak();
1383                    self.s.offset(-self.ind);
1384                }
1385                self.end();
1386                self.word(")");
1387            }
1388            ast::TypeKind::Custom(path) => self.print_path(path, false),
1389        }
1390    }
1391
1392    fn print_override(&mut self, override_: &'ast ast::Override<'ast>) {
1393        let ast::Override { span, paths } = override_;
1394        if self.handle_span(*span, false) {
1395            return;
1396        }
1397        self.word("override");
1398        if !paths.is_empty() {
1399            if self.config.override_spacing {
1400                self.nbsp();
1401            }
1402            self.print_tuple(
1403                paths,
1404                span.lo(),
1405                span.hi(),
1406                |this, path| this.print_path(path, false),
1407                get_span!(()),
1408                ListFormat::consistent(), // .with_cmnts_break(false),
1409            );
1410        }
1411    }
1412
1413    /* --- Expressions --- */
1414    /// Prints an expression by matching on its variant and delegating to the appropriate
1415    /// printer method, handling all Solidity expression kinds.
1416    fn print_expr(&mut self, expr: &'ast ast::Expr<'ast>) {
1417        let ast::Expr { span, ref kind } = *expr;
1418        // Drop blank lines before an expression (not after a comment): they cannot be kept when the
1419        // enclosing statement is inlined, which is decided ignoring them.
1420        self.print_comments(span.lo(), CommentConfig::skip_leading_ws(false));
1421        if self.handle_span(span, true) {
1422            return;
1423        }
1424
1425        match kind {
1426            ast::ExprKind::Array(exprs) => {
1427                self.print_array(exprs, expr.span, |this, e| this.print_expr(e), get_span!())
1428            }
1429            ast::ExprKind::Assign(lhs, None, rhs) => self.print_assign_expr(lhs, rhs),
1430            ast::ExprKind::Assign(lhs, Some(op), rhs) => self.print_bin_expr(lhs, op, rhs, true),
1431            ast::ExprKind::Binary(lhs, op, rhs) => self.print_bin_expr(lhs, op, rhs, false),
1432            ast::ExprKind::Call(call_expr, call_args) => {
1433                let cache = self.call_with_opts_and_args;
1434                let chained_named_call_cache = self.chained_named_call;
1435                // Keep calls within a chained callee inline when they fit, so a multiline named
1436                // argument list does not force an earlier break inside the callee.
1437                let keep_inline = chained_named_call_cache
1438                    .is_some_and(|call| call.keep_inline && call.callee.contains(expr.span))
1439                    && !self.has_comments_between_elements(call_args.span, call_args.exprs());
1440                self.call_with_opts_and_args = is_call_with_opts_and_args(&expr.kind);
1441                let named_args_size = if call_args.is_empty() {
1442                    4 + usize::from(self.config.bracket_spacing)
1443                } else {
1444                    2
1445                };
1446                self.chained_named_call = (matches!(call_args.kind, ast::CallArgsKind::Named(_))
1447                    && is_call_chain(&call_expr.kind, true))
1448                .then(|| ChainedNamedCall {
1449                    callee: call_expr.span,
1450                    keep_inline: !call_chain_contains_options(call_expr)
1451                        && !self.has_comment_between(call_expr.span.lo(), call_expr.span.hi())
1452                        && self
1453                            .estimate_call_chain_size(call_expr)
1454                            .is_some_and(|size| size + named_args_size <= self.space_left()),
1455                })
1456                .or_else(|| {
1457                    chained_named_call_cache.filter(|call| call.callee.contains(expr.span))
1458                });
1459                let list_format = if keep_inline {
1460                    ListFormat::inline()
1461                } else {
1462                    ListFormat::compact().break_cmnts().break_single(true)
1463                };
1464                let terminal_callee = call_expr.peel_parens();
1465                let callee_has_breakable_comment = self
1466                    .has_breakable_comment_between(call_expr.span.lo(), terminal_callee.span.lo())
1467                    || self.has_breakable_comment_between(
1468                        terminal_callee.span.hi(),
1469                        call_expr.span.hi(),
1470                    )
1471                    || if let ast::ExprKind::Member(member_expr, ident) = &terminal_callee.kind {
1472                        self.has_breakable_comment_between(member_expr.span.hi(), ident.span.lo())
1473                    } else {
1474                        false
1475                    };
1476                self.print_member_or_call_chain(
1477                    call_expr,
1478                    MemberOrCallArgs::CallArgs(
1479                        self.estimate_call_args_size(call_args.span),
1480                        self.has_comments_between_elements(call_args.span, call_args.exprs()),
1481                    ),
1482                    |s| {
1483                        let callee_suffix_can_break = callee_has_breakable_comment
1484                            || match &terminal_callee.kind {
1485                                ast::ExprKind::Member(member_expr, _) => {
1486                                    s.member_suffix_emits_break(terminal_callee, member_expr)
1487                                }
1488                                ast::ExprKind::Index(..) => !s.skip_index_break,
1489                                _ => false,
1490                            };
1491                        s.print_call_args(
1492                            call_args,
1493                            list_format.without_ind(s.return_bin_expr).with_delimiters(
1494                                !s.call_with_opts_and_args
1495                                    || s.call_stack
1496                                        .last()
1497                                        .is_some_and(|call| call.is_chained() && call.has_indent),
1498                            ),
1499                            get_callee_head_size(call_expr),
1500                            callee_suffix_can_break,
1501                        );
1502                    },
1503                );
1504                self.call_with_opts_and_args = cache;
1505                self.chained_named_call = chained_named_call_cache;
1506            }
1507            ast::ExprKind::CallOptions(expr, named_args) => {
1508                // the flag is only meant to be used to format the call args
1509                let cache = self.call_with_opts_and_args;
1510                self.call_with_opts_and_args = false;
1511
1512                self.print_expr(expr);
1513                self.print_named_args(named_args, span.hi(), false);
1514
1515                // restore cached value
1516                self.call_with_opts_and_args = cache;
1517            }
1518            ast::ExprKind::Delete(expr) => {
1519                self.word("delete ");
1520                self.print_expr(expr);
1521            }
1522            ast::ExprKind::Ident(ident) => self.print_ident(ident),
1523            ast::ExprKind::Index(expr, kind) => self.print_index_expr(span, expr, kind),
1524            ast::ExprKind::Lit(lit, unit) => {
1525                self.print_lit_inner(lit, false);
1526                if let Some(unit) = unit {
1527                    self.nbsp();
1528                    self.word(unit.to_str());
1529                }
1530            }
1531            ast::ExprKind::Member(member_expr, ident) => {
1532                self.print_member_or_call_chain(
1533                    member_expr,
1534                    MemberOrCallArgs::Member(self.estimate_size(ident.span)),
1535                    |s| {
1536                        let has_mixed_comment = s
1537                            .peek_comment_between(member_expr.span.hi(), ident.span.lo())
1538                            .is_some_and(|comment| comment.style.is_mixed());
1539                        let break_before_suffix = if has_mixed_comment {
1540                            s.print_comments(
1541                                ident.span.lo(),
1542                                CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1543                            );
1544                            true
1545                        } else {
1546                            !s.print_trailing_comment(member_expr.span.hi(), Some(ident.span.lo()))
1547                                && s.peek_comment_between(member_expr.span.hi(), ident.span.lo())
1548                                    .is_none()
1549                                && s.member_suffix_emits_break(expr, member_expr)
1550                        };
1551                        if break_before_suffix {
1552                            s.zerobreak();
1553                        }
1554                        s.word(".");
1555                        s.print_ident(ident);
1556                    },
1557                );
1558            }
1559            ast::ExprKind::New(ty) => {
1560                self.word("new ");
1561                self.print_ty(ty);
1562            }
1563            ast::ExprKind::Payable(args) => {
1564                self.word("payable");
1565                self.print_call_args(args, ListFormat::compact().break_cmnts(), 7, false);
1566            }
1567            ast::ExprKind::Ternary(cond, then, els) => self.print_ternary_expr(cond, then, els),
1568            ast::ExprKind::Tuple(exprs) => self.print_tuple(
1569                exprs,
1570                span.lo(),
1571                span.hi(),
1572                |this, expr| match expr.as_ref() {
1573                    SpannedOption::Some(expr) => this.print_expr(expr),
1574                    SpannedOption::None(span) => {
1575                        this.print_comments(
1576                            span.hi(),
1577                            CommentConfig::skip_ws().mixed_no_break_post(),
1578                        );
1579                    }
1580                },
1581                |expr| match expr.as_ref() {
1582                    SpannedOption::Some(expr) => expr.span,
1583                    // Manually handled by printing the comment when `None`
1584                    SpannedOption::None(..) => Span::DUMMY,
1585                },
1586                ListFormat::compact().break_single(is_binary_expr(&expr.kind)),
1587            ),
1588            ast::ExprKind::TypeCall(ty) => {
1589                self.word("type");
1590                self.print_tuple(
1591                    std::slice::from_ref(ty),
1592                    span.lo(),
1593                    span.hi(),
1594                    Self::print_ty,
1595                    get_span!(),
1596                    ListFormat::consistent(),
1597                );
1598            }
1599            ast::ExprKind::Type(ty) => self.print_ty(ty),
1600            ast::ExprKind::Unary(un_op, expr) => {
1601                let prefix = un_op.kind.is_prefix();
1602                let op = un_op.kind.to_str();
1603                if prefix {
1604                    self.word(op);
1605                }
1606                self.print_expr(expr);
1607                if !prefix {
1608                    debug_assert!(un_op.kind.is_postfix());
1609                    self.word(op);
1610                }
1611            }
1612            ast::ExprKind::Err(_) => self.print_span(span),
1613        }
1614        self.cursor.advance_to(span.hi(), true);
1615    }
1616
1617    /// Prints a simple assignment expression of the form `lhs = rhs`.
1618    fn print_assign_expr(&mut self, lhs: &'ast ast::Expr<'ast>, rhs: &'ast ast::Expr<'ast>) {
1619        let cache = self.var_init;
1620        self.var_init = true;
1621
1622        let space_left = self.space_left();
1623        let lhs_size = self.estimate_size(lhs.span);
1624        // Normalize only indexes that the existing layout keeps together. Longer indexes keep
1625        // their own breaks, so their source delimiter padding remains relevant to that layout.
1626        let lhs_size = if matches!(lhs.kind, ast::ExprKind::Index(..))
1627            && lhs_size + 2 <= space_left
1628            && !self.has_comment_between(lhs.span.lo(), rhs.span.lo())
1629        {
1630            self.estimate_assignment_size(lhs.span)
1631        } else {
1632            lhs_size
1633        };
1634        self.print_expr(lhs);
1635        self.word(" =");
1636        self.print_assign_rhs(rhs, lhs_size + 2, space_left, None, cache);
1637    }
1638
1639    /// Prints a binary operator expression. Handles operator chains and formatting.
1640    fn print_bin_expr(
1641        &mut self,
1642        lhs: &'ast ast::Expr<'ast>,
1643        bin_op: &ast::BinOp,
1644        rhs: &'ast ast::Expr<'ast>,
1645        is_assign: bool,
1646    ) {
1647        let prev_chain = self.binary_expr;
1648        let is_chain = prev_chain.is_some_and(|prev| prev == bin_op.kind.group());
1649
1650        // Opening box if starting a new operator chain.
1651        if !is_chain {
1652            self.binary_expr = Some(bin_op.kind.group());
1653
1654            let indent = if (is_assign && has_complex_successor(&rhs.kind, true))
1655                || self.call_stack.is_nested()
1656                    && is_call_chain(&lhs.kind, false)
1657                    && self.estimate_size(lhs.span) >= self.space_left()
1658            {
1659                0
1660            } else {
1661                self.ind
1662            };
1663            self.s.ibox(indent);
1664        }
1665
1666        // Print LHS.
1667        self.print_expr(lhs);
1668
1669        // Handle assignment (`+=`, etc.) vs binary ops (`+`, `*`, etc.).
1670        let no_trailing_comment = !self.print_trailing_comment(lhs.span.hi(), Some(rhs.span.lo()));
1671        if is_assign {
1672            if no_trailing_comment {
1673                self.nbsp();
1674            }
1675            self.word(bin_op.kind.to_str());
1676            self.word("= ");
1677        } else {
1678            if no_trailing_comment
1679                && self
1680                    .print_comments(
1681                        bin_op.span.lo(),
1682                        CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1683                    )
1684                    .is_none_or(|cmnt| cmnt.is_mixed())
1685            {
1686                if !self.config.pow_no_space || !matches!(bin_op.kind, ast::BinOpKind::Pow) {
1687                    self.space_if_not_bol();
1688                } else if !self.is_bol_or_only_ind() && !self.last_token_is_break() {
1689                    self.zerobreak();
1690                }
1691            }
1692
1693            self.word(bin_op.kind.to_str());
1694
1695            if !self.config.pow_no_space || !matches!(bin_op.kind, ast::BinOpKind::Pow) {
1696                self.nbsp();
1697            }
1698        }
1699
1700        // Print RHS with optional ibox if mixed comment precedes.
1701        let rhs_has_mixed_comment =
1702            self.peek_comment_before(rhs.span.lo()).is_some_and(|cmnt| cmnt.style.is_mixed());
1703        if rhs_has_mixed_comment {
1704            self.ibox(0);
1705            self.print_expr(rhs);
1706            self.end();
1707        } else {
1708            self.print_expr(rhs);
1709        }
1710
1711        // End current box if this was top-level in the chain.
1712        if !is_chain {
1713            self.binary_expr = prev_chain;
1714            self.end();
1715        }
1716    }
1717
1718    /// Prints an indexing expression.
1719    fn print_index_expr(
1720        &mut self,
1721        span: Span,
1722        expr: &'ast ast::Expr<'ast>,
1723        kind: &'ast ast::IndexKind<'ast>,
1724    ) {
1725        self.print_expr(expr);
1726        self.word("[");
1727        self.s.cbox(self.ind);
1728
1729        let mut skip_break = false;
1730        let mut zerobreak = |this: &mut Self| {
1731            if this.skip_index_break {
1732                skip_break = true;
1733            } else {
1734                this.zerobreak();
1735            }
1736        };
1737        match kind {
1738            ast::IndexKind::Index(Some(inner_expr)) => {
1739                zerobreak(self);
1740                self.print_expr(inner_expr);
1741            }
1742            ast::IndexKind::Index(None) => {}
1743            ast::IndexKind::Range(start, end) => {
1744                if let Some(start_expr) = start {
1745                    if self
1746                        .print_comments(start_expr.span.lo(), CommentConfig::skip_ws())
1747                        .is_none_or(|s| s.is_mixed())
1748                    {
1749                        zerobreak(self);
1750                    }
1751                    self.print_expr(start_expr);
1752                } else {
1753                    zerobreak(self);
1754                }
1755
1756                self.word(":");
1757
1758                if let Some(end_expr) = end {
1759                    self.s.ibox(self.ind);
1760                    if start.is_some() {
1761                        zerobreak(self);
1762                    }
1763                    self.print_comments(
1764                        end_expr.span.lo(),
1765                        CommentConfig::skip_ws()
1766                            .mixed_prev_space()
1767                            .mixed_no_break()
1768                            .mixed_post_nbsp(),
1769                    );
1770                    self.print_expr(end_expr);
1771                }
1772
1773                // Trailing comment handling.
1774                let is_trailing = if let Some(style) = self.print_comments(
1775                    span.hi(),
1776                    CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
1777                ) {
1778                    skip_break = true;
1779                    style.is_trailing()
1780                } else {
1781                    false
1782                };
1783
1784                // Adjust indentation and line breaks.
1785                match (skip_break, end.is_some()) {
1786                    (true, true) => {
1787                        self.break_offset_if_not_bol(0, -2 * self.ind, false);
1788                        self.end();
1789                        if !is_trailing {
1790                            self.break_offset_if_not_bol(0, -self.ind, false);
1791                        }
1792                    }
1793                    (true, false) => {
1794                        self.break_offset_if_not_bol(0, -self.ind, false);
1795                    }
1796                    (false, true) => {
1797                        self.end();
1798                    }
1799                    _ => {}
1800                }
1801            }
1802        }
1803
1804        if !skip_break {
1805            self.zerobreak();
1806            self.s.offset(-self.ind);
1807        }
1808
1809        self.end();
1810        self.word("]");
1811    }
1812
1813    /// Prints a ternary expression of the form `cond ? then : else`.
1814    fn print_ternary_expr(
1815        &mut self,
1816        cond: &'ast ast::Expr<'ast>,
1817        then: &'ast ast::Expr<'ast>,
1818        els: &'ast ast::Expr<'ast>,
1819    ) {
1820        self.s.cbox(self.ind);
1821        self.s.ibox(0);
1822
1823        let print_sub_expr = |this: &mut Self, span_lo, prefix, expr: &'ast ast::Expr<'ast>| {
1824            match prefix {
1825                Some(prefix) => {
1826                    if this.peek_comment_before(span_lo).is_some() {
1827                        this.space();
1828                    }
1829                    this.print_comments(span_lo, CommentConfig::skip_ws());
1830                    this.end();
1831                    if !this.is_bol_or_only_ind() {
1832                        this.space();
1833                    }
1834                    this.s.ibox(0);
1835                    this.word(prefix);
1836                }
1837                None => {
1838                    this.print_comments(expr.span.lo(), CommentConfig::skip_ws());
1839                }
1840            };
1841            this.print_expr(expr);
1842        };
1843
1844        // conditional expression
1845        self.s.ibox(-self.ind);
1846        print_sub_expr(self, then.span.lo(), None, cond);
1847        self.end();
1848        // then expression
1849        print_sub_expr(self, then.span.lo(), Some("? "), then);
1850        // else expression
1851        print_sub_expr(self, els.span.lo(), Some(": "), els);
1852
1853        self.end();
1854        self.neverbreak();
1855        self.s.offset(-self.ind);
1856        self.end();
1857    }
1858
1859    // If `add_parens_if_empty` is true, then add parentheses `()` even if there are no arguments.
1860    fn print_modifier_call(
1861        &mut self,
1862        modifier: &'ast ast::Modifier<'ast>,
1863        add_parens_if_empty: bool,
1864    ) {
1865        let ast::Modifier { name, arguments } = modifier;
1866        self.print_path(name, false);
1867        if !arguments.is_empty() || add_parens_if_empty {
1868            self.print_call_args(
1869                arguments,
1870                ListFormat::compact().break_cmnts(),
1871                name.to_string().len(),
1872                false,
1873            );
1874        }
1875    }
1876
1877    fn member_suffix_emits_break(&self, expr: &ast::Expr<'_>, member_expr: &ast::Expr<'_>) -> bool {
1878        match member_expr.kind {
1879            ast::ExprKind::Ident(_) | ast::ExprKind::Type(_) => false,
1880            ast::ExprKind::Index(..) if self.skip_index_break => false,
1881            _ if self
1882                .chained_named_call
1883                .is_some_and(|call| call.keep_inline && call.callee.contains(expr.span)) =>
1884            {
1885                false
1886            }
1887            // Don't add a break when accessing a field after a call with named args.
1888            // e.g., `_lzSend({_dstEid: x, ...}).guid` should keep `.guid`
1889            // on the same line as the closing `})`.
1890            // See: https://github.com/foundry-rs/foundry/issues/12399
1891            _ if is_call_with_named_args(&member_expr.kind) => false,
1892            _ => true,
1893        }
1894    }
1895
1896    fn print_member_or_call_chain<F>(
1897        &mut self,
1898        child_expr: &'ast ast::Expr<'ast>,
1899        member_or_args: MemberOrCallArgs,
1900        print_suffix: F,
1901    ) where
1902        F: FnOnce(&mut Self),
1903    {
1904        fn member_depth(depth: usize, expr: &ast::Expr<'_>) -> usize {
1905            if let ast::ExprKind::Member(child, ..) = &expr.kind {
1906                member_depth(depth + 1, child)
1907            } else {
1908                depth
1909            }
1910        }
1911
1912        let (mut extra_box, skip_cache) = (false, self.skip_index_break);
1913        let parent_is_chain = self.call_stack.last().copied().is_some_and(|call| call.is_chained());
1914        if !parent_is_chain {
1915            // Estimate sizes of callee and optional member
1916            let callee_size = get_callee_head_size(child_expr) + member_or_args.member_size();
1917            let expr_size = self.estimate_size(child_expr.span);
1918
1919            let callee_fits_line = self.space_left() > callee_size + 1;
1920            let total_fits_line = self.space_left() > expr_size + member_or_args.size() + 2;
1921            let no_cmnt_or_mixed =
1922                self.peek_comment_before(child_expr.span.hi()).is_none_or(|c| c.style.is_mixed());
1923
1924            // If call with options, add an extra box to prioritize breaking the call args.
1925            if self.call_with_opts_and_args {
1926                self.cbox(0);
1927                extra_box = true;
1928            }
1929
1930            // Determine if this chain will add its own indentation
1931            let keep_chain_inline = self
1932                .chained_named_call
1933                .is_some_and(|call| call.keep_inline && call.callee.contains(child_expr.span));
1934            let chain_has_indent = !keep_chain_inline
1935                && (is_call_chain(&child_expr.kind, true)
1936                    || !(no_cmnt_or_mixed
1937                        || matches!(&child_expr.kind, ast::ExprKind::CallOptions(..)))
1938                    || !callee_fits_line
1939                    || (member_depth(0, child_expr) >= 2
1940                        && (!total_fits_line || member_or_args.has_comments())));
1941
1942            // Start a new chain if needed
1943            if is_call_chain(&child_expr.kind, false) {
1944                self.call_stack.push(CallContext::chained(callee_size, chain_has_indent));
1945            }
1946
1947            if chain_has_indent {
1948                self.s.cbox(self.ind);
1949            } else {
1950                self.skip_index_break = true;
1951                self.cbox(0);
1952            }
1953        }
1954
1955        // Recursively print the child/prefix expression.
1956        self.print_expr(child_expr);
1957
1958        // If an extra box was opened, close it
1959        if extra_box {
1960            self.end();
1961        }
1962
1963        // Call the closure to print the suffix for the current link, with the calculated position.
1964        print_suffix(self);
1965
1966        // If a chain was started, clean up the state and end the box.
1967        if !parent_is_chain {
1968            if is_call_chain(&child_expr.kind, false) {
1969                self.call_stack.pop();
1970            }
1971            self.end();
1972        }
1973
1974        // Restore cache
1975        if self.skip_index_break {
1976            self.skip_index_break = skip_cache;
1977        }
1978    }
1979
1980    fn print_call_args(
1981        &mut self,
1982        args: &'ast ast::CallArgs<'ast>,
1983        format: ListFormat,
1984        callee_size: usize,
1985        callee_suffix_can_break: bool,
1986    ) {
1987        let ast::CallArgs { span, ref kind } = *args;
1988        if self.handle_span(span, true) {
1989            return;
1990        }
1991
1992        self.call_stack.push(CallContext::nested(callee_size));
1993
1994        // Clear the binary expression cache before the call.
1995        let cache = self.binary_expr.take();
1996
1997        match kind {
1998            ast::CallArgsKind::Unnamed(exprs) => {
1999                self.print_tuple(
2000                    exprs,
2001                    span.lo(),
2002                    span.hi(),
2003                    |this, e| this.print_expr(e),
2004                    get_span!(),
2005                    format,
2006                );
2007            }
2008            ast::CallArgsKind::Named(named_args) => {
2009                let without_ind =
2010                    self.call_stack.has_indented_parent_chain() && !callee_suffix_can_break;
2011                self.print_inside_parens(|state| {
2012                    state.print_named_args(named_args, span.hi(), without_ind)
2013                });
2014            }
2015        }
2016
2017        // Restore the cache to continue with the current chain.
2018        self.binary_expr = cache;
2019        self.call_stack.pop();
2020    }
2021
2022    fn print_named_args(
2023        &mut self,
2024        args: &'ast [ast::NamedArg<'ast>],
2025        pos_hi: BytePos,
2026        without_ind: bool,
2027    ) {
2028        let list_format = match (self.config.bracket_spacing, self.config.prefer_compact.calls()) {
2029            (false, true) => ListFormat::compact(),
2030            (false, false) => ListFormat::consistent(),
2031            (true, true) => ListFormat::compact().with_space(),
2032            (true, false) => ListFormat::consistent().with_space(),
2033        };
2034
2035        self.word("{");
2036        // Use the start position of the first argument's name for comment processing.
2037        if let Some(first_arg) = args.first() {
2038            let list_lo = first_arg.name.span.lo();
2039            self.commasep(
2040                args,
2041                list_lo,
2042                pos_hi,
2043                // Closure to print a single named argument (`name: value`)
2044                |s, arg| {
2045                    s.cbox(0);
2046                    s.print_ident(&arg.name);
2047                    s.word(":");
2048                    if s.same_source_line(arg.name.span.hi(), arg.value.span.hi())
2049                        || !s.print_trailing_comment(arg.name.span.hi(), None)
2050                    {
2051                        s.nbsp();
2052                    }
2053                    s.print_comments(
2054                        arg.value.span.lo(),
2055                        CommentConfig::skip_ws().mixed_no_break().mixed_post_nbsp(),
2056                    );
2057                    s.print_expr(arg.value);
2058                    s.end();
2059                },
2060                |arg| arg.name.span.until(arg.value.span),
2061                list_format
2062                    .break_cmnts()
2063                    .break_single(true)
2064                    .without_ind(without_ind)
2065                    .with_delimiters(!self.call_with_opts_and_args),
2066            );
2067        } else if self.config.bracket_spacing {
2068            self.nbsp();
2069        }
2070        self.word("}");
2071    }
2072
2073    /* --- Statements --- */
2074    /// Prints the given statement in the source code, handling formatting, inline documentation,
2075    /// trailing comments and layout logic for various statement kinds.
2076    fn print_stmt(&mut self, stmt: &'ast ast::Stmt<'ast>) {
2077        self.print_stmt_bound(stmt, None);
2078    }
2079
2080    /// Prints a statement with a bounded trailing-comment scan.
2081    fn print_stmt_bound(&mut self, stmt: &'ast ast::Stmt<'ast>, next_pos: Option<BytePos>) {
2082        let ast::Stmt { ref docs, span, ref kind } = *stmt;
2083        self.print_docs(docs);
2084
2085        // Handle disabled statements.
2086        if self.handle_span(span, false) {
2087            self.print_trailing_comment_no_break(stmt.span.hi(), next_pos);
2088            return;
2089        }
2090
2091        // return statements can't have a preceding comment in the same line.
2092        let force_break = matches!(kind, ast::StmtKind::Return(..))
2093            && self.peek_comment_before(span.lo()).is_some_and(|cmnt| cmnt.style.is_mixed());
2094
2095        match kind {
2096            ast::StmtKind::Assembly(ast::StmtAssembly { dialect, flags, block }) => {
2097                self.print_assembly_stmt(span, dialect, flags, block)
2098            }
2099            ast::StmtKind::DeclSingle(var) => self.print_var(var, true),
2100            ast::StmtKind::DeclMulti(vars, init_expr) => {
2101                self.print_multi_decl_stmt(span, vars, init_expr)
2102            }
2103            ast::StmtKind::Block(stmts) => self.print_block(stmts, span),
2104            ast::StmtKind::Break => self.word("break"),
2105            ast::StmtKind::Continue => self.word("continue"),
2106            ast::StmtKind::DoWhile(stmt, cond) => {
2107                self.word("do ");
2108                self.print_stmt_as_block(stmt, cond.span.lo(), false);
2109                self.nbsp();
2110                self.print_if_cond("while", cond, cond.span.hi());
2111            }
2112            ast::StmtKind::Emit(path, args) => self.print_emit_or_revert("emit", path, args),
2113            ast::StmtKind::Expr(expr) => self.print_expr(expr),
2114            ast::StmtKind::For { .. } => self.print_for_stmt(stmt),
2115            ast::StmtKind::If(..) => self.print_if_stmt(stmt),
2116            ast::StmtKind::Return(expr) => self.print_return_stmt(force_break, expr),
2117            ast::StmtKind::Revert(path, args) => self.print_emit_or_revert("revert", path, args),
2118            ast::StmtKind::Try(ast::StmtTry { expr, clauses }) => {
2119                self.print_try_stmt(expr, clauses)
2120            }
2121            ast::StmtKind::UncheckedBlock(block) => {
2122                self.word("unchecked ");
2123                self.print_block(block, stmt.span);
2124            }
2125            ast::StmtKind::While(cond, body) => {
2126                // Check if blocks should be inlined and update cache if necessary
2127                let inline = self.is_single_line_block(stmt);
2128                if !inline.is_cached && self.single_line_stmt.is_none() {
2129                    self.single_line_stmt = Some(inline.outcome);
2130                }
2131
2132                // Print while cond and its statement
2133                self.print_if_cond("while", cond, body.span.lo());
2134                self.nbsp();
2135                self.print_stmt_as_block(body, body.span.hi(), inline.outcome);
2136
2137                // Clear cache if necessary
2138                if !inline.is_cached && self.single_line_stmt.is_some() {
2139                    self.single_line_stmt = None;
2140                }
2141            }
2142            ast::StmtKind::Placeholder => self.word("_"),
2143        }
2144        if stmt_needs_semi(kind) {
2145            self.neverbreak(); // semicolon shouldn't account for linebreaks
2146            self.word(";");
2147            self.cursor.advance_to(span.hi(), true);
2148        }
2149        // print comments without breaks, as those are handled by the caller.
2150        let ends_with_line_comment = self
2151            .comments
2152            .iter()
2153            .take_while(|cmnt| cmnt.pos() < stmt.span.hi())
2154            .filter(|cmnt| !cmnt.style.is_blank())
2155            .last()
2156            .is_some_and(|cmnt| {
2157                cmnt.style.is_trailing() && matches!(cmnt.kind, ast::CommentKind::Line)
2158            });
2159        self.print_comments(
2160            stmt.span.hi(),
2161            CommentConfig::skip_trailing_ws()
2162                .trailing_no_break()
2163                .mixed_no_break()
2164                .mixed_prev_space(),
2165        );
2166        if ends_with_line_comment && self.peek_comment().is_some() {
2167            self.hardbreak_if_not_bol();
2168        }
2169        self.print_trailing_comment_no_break(stmt.span.hi(), next_pos);
2170    }
2171
2172    /// Prints an `assembly` statement, including optional dialect and flags,
2173    /// followed by its Yul block.
2174    fn print_assembly_stmt(
2175        &mut self,
2176        span: Span,
2177        dialect: &'ast Option<ast::StrLit>,
2178        flags: &'ast [ast::StrLit],
2179        block: &'ast ast::yul::Block<'ast>,
2180    ) {
2181        _ = self.handle_span(self.cursor.span(span.lo()), false);
2182        if !self.handle_span(span.until(block.span), false) {
2183            self.cursor.advance_to(span.lo(), true);
2184            self.print_word("assembly "); // 9 chars
2185            if let Some(dialect) = dialect {
2186                self.print_ast_str_lit(dialect);
2187                self.print_sep(Separator::Nbsp);
2188            }
2189            if !flags.is_empty() {
2190                self.print_tuple(
2191                    flags,
2192                    span.lo(),
2193                    block.span.lo(),
2194                    Self::print_ast_str_lit,
2195                    get_span!(),
2196                    ListFormat::consistent(),
2197                );
2198                self.print_sep(Separator::Nbsp);
2199            }
2200        }
2201        self.print_yul_block(block, block.span, false, 9);
2202    }
2203
2204    /// Prints a multiple-variable declaration with a single initializer expression,
2205    /// formatted as a tuple-style assignment (e.g., `(a, b) = foo();`).
2206    fn print_multi_decl_stmt(
2207        &mut self,
2208        span: Span,
2209        vars: &'ast BoxSlice<'ast, SpannedOption<ast::VariableDefinition<'ast>>>,
2210        init_expr: &'ast ast::Expr<'ast>,
2211    ) {
2212        let space_left = self.space_left();
2213
2214        self.s.ibox(self.ind);
2215        self.s.ibox(-self.ind);
2216        self.print_tuple(
2217            vars,
2218            span.lo(),
2219            init_expr.span.lo(),
2220            |this, var| match var {
2221                SpannedOption::Some(var) => this.print_var(var, true),
2222                SpannedOption::None(span) => {
2223                    this.print_comments(span.hi(), CommentConfig::skip_ws().mixed_no_break_post());
2224                }
2225            },
2226            |var| match var {
2227                SpannedOption::Some(var) => var.span,
2228                // Manually handled by printing the comment when `None`
2229                SpannedOption::None(..) => Span::DUMMY,
2230            },
2231            ListFormat::consistent(),
2232        );
2233        self.end();
2234        self.word(" =");
2235
2236        if self.estimate_size(init_expr.span) + self.config.tab_width
2237            <= std::cmp::max(space_left, self.space_left())
2238        {
2239            self.print_sep(Separator::Space);
2240            self.ibox(0);
2241        } else {
2242            self.print_sep(Separator::Nbsp);
2243            self.neverbreak();
2244            self.s.ibox(-self.ind);
2245        }
2246        self.print_expr(init_expr);
2247        self.end();
2248        self.end();
2249    }
2250
2251    /// Prints a `for` loop statement, including its initializer, condition,
2252    /// increment expression, and loop body, with formatting and spacing.
2253    fn print_for_stmt(&mut self, stmt: &'ast ast::Stmt<'ast>) {
2254        let ast::StmtKind::For { init, cond, next, body } = &stmt.kind else { unreachable!() };
2255        let span = stmt.span;
2256        let inline = self.is_single_line_block(stmt);
2257        let set_inline_cache = self.single_line_stmt.is_none();
2258        if set_inline_cache {
2259            self.single_line_stmt = Some(inline.outcome);
2260        }
2261
2262        self.cbox(0);
2263        self.s.ibox(self.ind);
2264        let open_paren = self.find_uncommented_char(span, '(').unwrap();
2265        self.print_word("for");
2266        if self
2267            .print_comments(
2268                open_paren,
2269                CommentConfig::skip_ws().mixed_prev_space().mixed_post_nbsp(),
2270            )
2271            .is_none()
2272        {
2273            self.nbsp();
2274        }
2275        self.cursor.advance_to(open_paren, true);
2276        self.print_word("(");
2277        let init_has_leading_comment =
2278            init.as_ref().is_some_and(|stmt| self.peek_comment_before(stmt.span.lo()).is_some());
2279        if !init_has_leading_comment {
2280            self.zerobreak();
2281        }
2282
2283        // Print init.
2284        self.s.cbox(0);
2285        let init_trailing_comment = match init {
2286            Some(init_stmt) => {
2287                let has_trailing_comment = cond.as_ref().is_some_and(|cond| {
2288                    self.comments
2289                        .iter()
2290                        .skip_while(|cmnt| cmnt.pos() < init_stmt.span.hi())
2291                        .take_while(|cmnt| cmnt.pos() < cond.span.lo())
2292                        .any(|cmnt| cmnt.style.is_trailing())
2293                });
2294                self.print_stmt_bound(init_stmt, Some(init_stmt.span.hi()));
2295                has_trailing_comment
2296            }
2297            None => {
2298                self.print_word(";");
2299                false
2300            }
2301        };
2302
2303        // Print condition.
2304        match cond {
2305            Some(cond_expr) => {
2306                if init_trailing_comment {
2307                    self.hardbreak_if_not_bol();
2308                }
2309                self.print_sep(Separator::Space);
2310                self.print_expr(cond_expr);
2311            }
2312            None => self.zerobreak(),
2313        }
2314        self.print_word(";");
2315
2316        // Print next clause.
2317        match next {
2318            Some(next_expr) => {
2319                self.space();
2320                self.print_expr(next_expr);
2321            }
2322            None => self.zerobreak(),
2323        }
2324
2325        // Close head.
2326        self.break_offset_if_not_bol(0, -self.ind, false);
2327        self.end();
2328        self.print_word(") ");
2329        self.neverbreak();
2330        self.end();
2331
2332        // Print comments and body.
2333        self.print_comments(body.span.lo(), CommentConfig::skip_ws());
2334        let leaf = if let ast::StmtKind::Block(block) = &body.kind {
2335            block.stmts.first()
2336        } else {
2337            Some(&**body)
2338        };
2339        let inline_assignments = self.inline_assignments;
2340        // Only the measured leaf body is certified flat; nested headers may still wrap.
2341        if inline.outcome
2342            && leaf.is_some_and(|stmt| {
2343                matches!(
2344                    stmt.kind,
2345                    ast::StmtKind::Expr(_)
2346                        | ast::StmtKind::Return(_)
2347                        | ast::StmtKind::Emit(..)
2348                        | ast::StmtKind::Revert(..)
2349                )
2350            })
2351        {
2352            self.inline_assignments = true;
2353        }
2354        self.print_stmt_as_block(body, span.hi(), inline.outcome);
2355        self.inline_assignments = inline_assignments;
2356        self.end();
2357        if set_inline_cache {
2358            self.single_line_stmt = None;
2359        }
2360    }
2361
2362    /// Prints an `if` statement, including its condition, `then` block, and any chained
2363    /// `else` or `else if` branches, handling inline formatting decisions and comments.
2364    fn print_if_stmt(&mut self, stmt: &'ast ast::Stmt<'ast>) {
2365        let ast::StmtKind::If(cond, then, els_opt) = &stmt.kind else { unreachable!() };
2366        let span = stmt.span;
2367        // Check if blocks should be inlined and update cache if necessary
2368        let inline = self.is_single_line_block(stmt);
2369        let set_inline_cache = self.single_line_stmt.is_none();
2370        if set_inline_cache {
2371            self.single_line_stmt = Some(inline.outcome);
2372        }
2373
2374        self.cbox(0);
2375        self.ibox(0);
2376        // Print if stmt
2377        self.print_if_no_else(cond, then, inline.outcome);
2378
2379        // Print else (if) stmts, if any
2380        let mut current_else = els_opt.as_deref();
2381        while let Some(els) = current_else {
2382            if self.ends_with('}') {
2383                // If there are comments with line breaks, don't add spaces to mixed comments
2384                if self.has_comment_before_with(els.span.lo(), |cmnt| !cmnt.style.is_mixed()) {
2385                    // If last comment is miced, ensure line break
2386                    if self
2387                        .print_comments(els.span.lo(), CommentConfig::skip_ws().mixed_no_break())
2388                        .is_some_and(|cmnt| cmnt.is_mixed())
2389                    {
2390                        self.hardbreak();
2391                    }
2392                }
2393                // Otherwise, ensure a non-breaking space is added
2394                else if self
2395                    .print_comments(
2396                        els.span.lo(),
2397                        CommentConfig::skip_ws()
2398                            .mixed_no_break()
2399                            .mixed_prev_space()
2400                            .mixed_post_nbsp(),
2401                    )
2402                    .is_none()
2403                {
2404                    self.nbsp();
2405                }
2406            } else {
2407                self.hardbreak_if_not_bol();
2408                if self
2409                    .print_comments(els.span.lo(), CommentConfig::skip_ws())
2410                    .is_some_and(|cmnt| cmnt.is_mixed())
2411                {
2412                    self.hardbreak();
2413                };
2414            }
2415
2416            self.ibox(0);
2417            self.print_word("else ");
2418            match &els.kind {
2419                ast::StmtKind::If(cond, then, next_else) => {
2420                    self.print_if_no_else(cond, then, inline.outcome);
2421                    current_else = next_else.as_deref();
2422                }
2423                _ => {
2424                    self.print_stmt_as_block(els, span.hi(), inline.outcome);
2425                    self.end(); // end ibox for final else
2426                    break;
2427                }
2428            }
2429        }
2430        self.end();
2431
2432        // Clear inline cache if we set it earlier.
2433        if set_inline_cache {
2434            self.single_line_stmt = None;
2435        }
2436    }
2437
2438    /// Prints a `return` statement, optionally including a return expression.
2439    /// Handles spacing, line breaking, and formatting.
2440    fn print_return_stmt(&mut self, force_break: bool, expr: &'ast Option<&mut ast::Expr<'ast>>) {
2441        if force_break {
2442            self.hardbreak_if_not_bol();
2443        }
2444
2445        let space_left = self.space_left();
2446        let expr_size = expr.as_ref().map_or(0, |expr| self.estimate_size(expr.span));
2447
2448        // `return ' + expr + ';'
2449        let overflows = space_left < 8 + expr_size;
2450        let fits_alone = space_left > expr_size;
2451
2452        if let Some(expr) = expr {
2453            let is_simple = matches!(expr.kind, ast::ExprKind::Lit(..) | ast::ExprKind::Ident(..));
2454            let allow_break = overflows && fits_alone;
2455
2456            self.return_bin_expr = is_binary_expr(&expr.kind);
2457            self.s.ibox(if is_simple || allow_break { self.ind } else { 0 });
2458
2459            self.print_word("return");
2460
2461            match self.print_comments(
2462                expr.span.lo(),
2463                CommentConfig::skip_ws().mixed_no_break().mixed_prev_space().mixed_post_nbsp(),
2464            ) {
2465                Some(_) if !is_simple => self.s.offset(self.ind),
2466                None => self.print_sep(Separator::SpaceOrNbsp(allow_break)),
2467                _ => {}
2468            }
2469
2470            self.print_expr(expr);
2471            self.end();
2472            self.return_bin_expr = false;
2473        } else {
2474            self.print_word("return");
2475        }
2476    }
2477
2478    /// Prints a `try` statement along with its associated `catch` clauses,
2479    /// following Solidity's `try ... returns (...) { ... } catch (...) { ... }` syntax.
2480    fn print_try_stmt(
2481        &mut self,
2482        expr: &'ast ast::Expr<'ast>,
2483        clauses: &'ast [ast::TryCatchClause<'ast>],
2484    ) {
2485        self.cbox(0);
2486        if let Some((first, other)) = clauses.split_first() {
2487            // Print the 'try' clause
2488            let ast::TryCatchClause { args, block, span: try_span, .. } = first;
2489            self.cbox(0);
2490            self.ibox(0);
2491            self.print_word("try ");
2492            self.print_comments(expr.span.lo(), CommentConfig::skip_ws());
2493            self.print_expr(expr);
2494
2495            // Print comments.
2496            self.print_comments(
2497                args.first().map(|p| p.span.lo()).unwrap_or_else(|| expr.span.lo()),
2498                CommentConfig::skip_ws(),
2499            );
2500            if !self.is_beginning_of_line() {
2501                self.nbsp();
2502            }
2503
2504            if args.is_empty() {
2505                self.end();
2506            } else {
2507                self.print_word("returns ");
2508                self.print_word("(");
2509                self.zerobreak();
2510                self.end();
2511                let span = args.span.with_hi(block.span.lo());
2512                self.commasep(
2513                    args,
2514                    span.lo(),
2515                    span.hi(),
2516                    |fmt, var| fmt.print_var(var, false),
2517                    get_span!(),
2518                    ListFormat::compact().with_delimiters(false),
2519                );
2520                self.print_word(")");
2521                self.nbsp();
2522            }
2523            if block.is_empty() {
2524                self.print_block(block, *try_span);
2525                self.end();
2526            } else {
2527                self.print_word("{");
2528                self.end();
2529                self.neverbreak();
2530                self.print_trailing_comment_no_break(try_span.lo(), None);
2531                self.print_block_without_braces(block, try_span.hi(), Some(self.ind));
2532                if self.cursor.enabled || self.cursor.pos < try_span.hi() {
2533                    self.print_word("}");
2534                    self.cursor.advance_to(try_span.hi(), true);
2535                }
2536            }
2537
2538            let mut skip_ind = false;
2539            if self.print_trailing_comment(try_span.hi(), other.first().map(|c| c.span.lo())) {
2540                // if a trailing comment is printed at the very end, we have to manually
2541                // adjust the offset to avoid having a double break.
2542                self.break_offset_if_not_bol(0, self.ind, false);
2543                skip_ind = true;
2544            };
2545
2546            let mut prev_block_multiline = self.is_multiline_block(block, false, true);
2547
2548            // Handle 'catch' clauses
2549            for (pos, ast::TryCatchClause { name, args, block, span: catch_span }) in
2550                other.iter().delimited()
2551            {
2552                let current_block_multiline = self.is_multiline_block(block, false, true);
2553                if !pos.is_first || !skip_ind {
2554                    if (pos.is_first && block.is_empty() && is_call_with_named_args(&expr.kind))
2555                        || (prev_block_multiline && (current_block_multiline || pos.is_last))
2556                    {
2557                        self.nbsp();
2558                    } else {
2559                        self.space();
2560                        if !current_block_multiline {
2561                            self.s.offset(self.ind);
2562                        }
2563                    }
2564                }
2565                self.s.ibox(self.ind);
2566                self.print_comments(
2567                    catch_span.lo(),
2568                    CommentConfig::skip_ws().mixed_no_break().mixed_post_nbsp(),
2569                );
2570
2571                self.print_word("catch ");
2572                if !args.is_empty() {
2573                    self.print_comments(
2574                        args[0].span.lo(),
2575                        CommentConfig::skip_ws().mixed_no_break().mixed_post_nbsp(),
2576                    );
2577                    if let Some(name) = name {
2578                        self.print_ident(name);
2579                    }
2580                    self.print_parameter_list(
2581                        args,
2582                        args.span.with_hi(block.span.lo()),
2583                        ListFormat::inline(),
2584                    );
2585                    self.nbsp();
2586                }
2587                self.print_word("{");
2588                self.end();
2589                if !block.is_empty() {
2590                    self.print_trailing_comment_no_break(catch_span.lo(), None);
2591                }
2592                self.print_block_without_braces(block, catch_span.hi(), Some(self.ind));
2593                if self.cursor.enabled || self.cursor.pos < try_span.hi() {
2594                    self.print_word("}");
2595                    self.cursor.advance_to(catch_span.hi(), true);
2596                }
2597
2598                prev_block_multiline = current_block_multiline;
2599            }
2600        }
2601        self.end();
2602    }
2603
2604    fn print_if_no_else(
2605        &mut self,
2606        cond: &'ast ast::Expr<'ast>,
2607        then: &'ast ast::Stmt<'ast>,
2608        inline: bool,
2609    ) {
2610        if !self.handle_span(cond.span.until(then.span), true) {
2611            self.print_if_cond("if", cond, then.span.lo());
2612            // if empty block without comments, ensure braces are inlined
2613            if let ast::StmtKind::Block(block) = &then.kind
2614                && block.is_empty()
2615                && self.peek_comment_before(then.span.hi()).is_none()
2616            {
2617                self.neverbreak();
2618                self.print_sep(Separator::Nbsp);
2619            } else if inline
2620                && is_call(&cond.kind)
2621                && matches!(
2622                    self.config.single_line_statement_blocks,
2623                    config::SingleLineBlockStyle::Preserve
2624                )
2625            {
2626                // Keep the body beside a wrapped call condition so Preserve sees the same
2627                // layout on the next pass.
2628                self.print_sep(Separator::Nbsp);
2629            } else {
2630                self.print_sep(Separator::Space);
2631            }
2632        }
2633        self.end();
2634        self.print_stmt_as_block(then, then.span.hi(), inline);
2635        self.cursor.advance_to(then.span.hi(), true);
2636    }
2637
2638    fn print_if_cond(&mut self, kw: &'static str, cond: &'ast ast::Expr<'ast>, pos_hi: BytePos) {
2639        self.print_word(kw);
2640        self.print_sep_unhandled(Separator::Nbsp);
2641        self.print_tuple(
2642            std::slice::from_ref(cond),
2643            cond.span.lo(),
2644            pos_hi,
2645            Self::print_expr,
2646            get_span!(),
2647            ListFormat::compact().break_cmnts().break_single(is_binary_expr(&cond.kind)),
2648        );
2649    }
2650
2651    fn print_emit_or_revert(
2652        &mut self,
2653        kw: &'static str,
2654        path: &'ast ast::PathSlice,
2655        args: &'ast ast::CallArgs<'ast>,
2656    ) {
2657        self.word(kw);
2658        if self
2659            .print_comments(
2660                path.span().lo(),
2661                CommentConfig::skip_ws().mixed_no_break().mixed_prev_space().mixed_post_nbsp(),
2662            )
2663            .is_none()
2664        {
2665            self.nbsp();
2666        };
2667        self.s.cbox(0);
2668        self.emit_or_revert = path.segments().len() > 1;
2669        self.print_path(path, false);
2670        let format = if self.config.prefer_compact.calls() {
2671            ListFormat::compact()
2672        } else {
2673            ListFormat::consistent()
2674        };
2675        self.print_call_args(args, format.break_cmnts(), path.to_string().len(), false);
2676        self.emit_or_revert = false;
2677        self.end();
2678    }
2679
2680    fn print_block(&mut self, block: &'ast [ast::Stmt<'ast>], span: Span) {
2681        self.print_block_inner(
2682            block,
2683            BlockFormat::Regular,
2684            Self::print_stmt,
2685            |b| b.span,
2686            span.hi(),
2687        );
2688    }
2689
2690    fn print_block_without_braces(
2691        &mut self,
2692        block: &'ast [ast::Stmt<'ast>],
2693        pos_hi: BytePos,
2694        offset: Option<isize>,
2695    ) {
2696        self.print_block_inner(
2697            block,
2698            BlockFormat::NoBraces(offset),
2699            Self::print_stmt,
2700            |b| b.span,
2701            pos_hi,
2702        );
2703    }
2704
2705    // Body of a if/loop.
2706    fn print_stmt_as_block(&mut self, stmt: &'ast ast::Stmt<'ast>, pos_hi: BytePos, inline: bool) {
2707        if self.handle_span(stmt.span, false) {
2708            return;
2709        }
2710
2711        let stmts = if let ast::StmtKind::Block(stmts) = &stmt.kind {
2712            stmts
2713        } else {
2714            std::slice::from_ref(stmt)
2715        };
2716
2717        // Solidity only permits variable declarations inside braces, even when a parent's
2718        // cached inline decision would otherwise remove them.
2719        if inline
2720            && stmts.len() == 1
2721            && !matches!(stmts[0].kind, ast::StmtKind::DeclSingle(_) | ast::StmtKind::DeclMulti(..))
2722        {
2723            self.neverbreak();
2724            self.print_block_without_braces(stmts, pos_hi, None);
2725        } else {
2726            // Reset cache for nested (child) stmts within this (parent) block.
2727            let inline_parent = self.single_line_stmt.take();
2728
2729            self.print_word("{");
2730            self.print_block_without_braces(stmts, pos_hi, Some(self.ind));
2731            self.print_word("}");
2732
2733            // Restore cache for the rest of stmts within the same height.
2734            self.single_line_stmt = inline_parent;
2735        }
2736    }
2737
2738    /// Determines whether a statement body can be inlined and whether the decision came from
2739    /// the parent cache.
2740    fn is_single_line_block(&mut self, stmt: &'ast ast::Stmt<'ast>) -> Decision {
2741        let (cond, then, els_opt) = match &stmt.kind {
2742            ast::StmtKind::If(cond, then, els) => (cond.span, &**then, els.as_deref()),
2743            ast::StmtKind::While(cond, body) => (cond.span, &**body, None),
2744            ast::StmtKind::For { init, cond, next, body } => {
2745                (Self::for_header_span(stmt.span, init, cond, next), &**body, None)
2746            }
2747            _ => unreachable!(),
2748        };
2749        // Dangling-else guard runs before the cache check so an inlined parent can't
2750        // coerce this `if` into dropping braces and rebinding its `else`.
2751        if Self::then_block_can_capture_trailing_else(then, els_opt.is_some()) {
2752            return Decision { outcome: false, is_cached: false };
2753        }
2754
2755        // Block comments can move across statement terminators when printed. Inspect the
2756        // whole body before inheriting a parent's decision, so both passes retain its braces.
2757        if self.peek_comment_between(stmt.span.lo(), then.span.lo()).is_some()
2758            || self.has_comment_before_with(stmt.span.hi(), |comment| {
2759                comment.pos() >= stmt.span.lo() && matches!(comment.kind, ast::CommentKind::Block)
2760            })
2761        {
2762            return Decision { outcome: false, is_cached: false };
2763        }
2764
2765        // If a decision is already cached from a parent, use it directly.
2766        if let Some(cached_decision) = self.single_line_stmt {
2767            return Decision { outcome: cached_decision, is_cached: true };
2768        }
2769
2770        // Reject source layouts that Preserve must retain before measuring normalized output.
2771        let then_span = Self::inline_stmt_span(then);
2772        if matches!(self.config.single_line_statement_blocks, config::SingleLineBlockStyle::Multi)
2773            || (matches!(
2774                self.config.single_line_statement_blocks,
2775                config::SingleLineBlockStyle::Preserve
2776            ) && (self.is_stmt_in_new_line(cond, then)
2777                || !self.same_source_line(then_span.lo(), then_span.hi())))
2778            || self.is_multiline_block_stmt(then, true)
2779        {
2780            return Decision { outcome: false, is_cached: false };
2781        }
2782
2783        // If no decision was made, estimate the length to be formatted.
2784        // NOTE: conservative check -> worst-case scenario is formatting as multi-line block.
2785        let (then_margin, body_len) =
2786            if let ast::StmtKind::For { init, cond, next, .. } = &stmt.kind {
2787                let header_len = self.estimate_for_header_size(init, cond, next);
2788                // A wrapped header can leave clauses beside the closing parenthesis.
2789                if header_len >= self.space_left() {
2790                    return Decision { outcome: false, is_cached: false };
2791                }
2792                (header_len, Some(self.estimate_inline_stmt_size(then)))
2793            } else {
2794                // Keep existing condition layout estimates outside `for` loops.
2795                let header_len = 6 + self.estimate_size(cond);
2796                (if header_len < self.space_left() { header_len } else { 2 }, None)
2797            };
2798        if !self.is_inline_stmt(then, then_margin, body_len)
2799            || els_opt.is_some_and(|els| !self.is_inline_stmt(els, 6, None))
2800        {
2801            return Decision { outcome: false, is_cached: false };
2802        }
2803
2804        // If the parent would fit, check all of its children.
2805        if matches!(then.kind, ast::StmtKind::If(..)) {
2806            let child_decision = self.is_single_line_block(then);
2807            if !child_decision.outcome {
2808                return child_decision;
2809            }
2810        }
2811        if let Some(stmt) = els_opt {
2812            if matches!(stmt.kind, ast::StmtKind::If(..)) {
2813                return self.is_single_line_block(stmt);
2814            } else if self.is_multiline_block_stmt(stmt, true) {
2815                return Decision { outcome: false, is_cached: false };
2816            }
2817        }
2818
2819        // If all children can also fit, allow single-line block.
2820        Decision { outcome: true, is_cached: false }
2821    }
2822
2823    fn is_inline_stmt(
2824        &self,
2825        stmt: &'ast ast::Stmt<'ast>,
2826        header_len: usize,
2827        body_len: Option<usize>,
2828    ) -> bool {
2829        let span = Self::inline_stmt_span(stmt);
2830        if matches!(
2831            self.config.single_line_statement_blocks,
2832            config::SingleLineBlockStyle::Preserve
2833        ) && !self.same_source_line(span.lo(), span.hi())
2834        {
2835            return false;
2836        }
2837        if header_len + body_len.unwrap_or_else(|| self.estimate_size(span)) >= self.space_left() {
2838            return false;
2839        }
2840        if let ast::StmtKind::If(_, _, Some(els)) = &stmt.kind {
2841            return self.is_inline_stmt(els, 6, None);
2842        }
2843        true
2844    }
2845
2846    fn inline_stmt_span(stmt: &ast::Stmt<'_>) -> Span {
2847        if let ast::StmtKind::If(cond, then, _) = &stmt.kind {
2848            cond.span.to(then.span)
2849        } else {
2850            stmt.span
2851        }
2852    }
2853
2854    /// Checks if a statement was explicitly written in a new line.
2855    fn is_stmt_in_new_line(&self, cond: Span, then: &'ast ast::Stmt<'ast>) -> bool {
2856        let span_between = cond.between(then.span);
2857        if let Some(snip) = self.snippet(span_between) {
2858            // Check for newlines after the closing parenthesis of the `if (...)`.
2859            if let Some((_, after_paren)) = snip.rsplit_once(')') {
2860                return after_paren.contains('\n');
2861            }
2862        }
2863        false
2864    }
2865
2866    /// Returns true if eliding the braces of `then` would expose an inner `if` to a
2867    /// trailing `else` or change the AST shape on round-trip.
2868    fn then_block_can_capture_trailing_else(
2869        then: &'ast ast::Stmt<'ast>,
2870        has_outer_else: bool,
2871    ) -> bool {
2872        if has_outer_else
2873            && matches!(then.kind, ast::StmtKind::For { .. } | ast::StmtKind::While(..))
2874        {
2875            return true;
2876        }
2877        let ast::StmtKind::Block(block) = &then.kind else { return false };
2878        if block.stmts.len() != 1 {
2879            return false;
2880        }
2881        match &block.stmts[0].kind {
2882            ast::StmtKind::If(_, _, inner_else) => has_outer_else || inner_else.is_some(),
2883            ast::StmtKind::While(..) | ast::StmtKind::For { .. } => has_outer_else,
2884            _ => false,
2885        }
2886    }
2887
2888    /// Checks if a block statement `{ ... }` contains more than one line of actual code.
2889    fn is_multiline_block_stmt(
2890        &mut self,
2891        stmt: &'ast ast::Stmt<'ast>,
2892        empty_as_multiline: bool,
2893    ) -> bool {
2894        match &stmt.kind {
2895            ast::StmtKind::Block(block) => {
2896                self.is_multiline_block(block, empty_as_multiline, false)
2897            }
2898            ast::StmtKind::While(..) => !self.is_single_line_block(stmt).outcome,
2899
2900            // A parent's source-width estimate cannot account for normalized loop clauses.
2901            ast::StmtKind::For { .. } => true,
2902
2903            ast::StmtKind::If(_, _, Some(_)) => true,
2904            ast::StmtKind::If(_, then, None) => {
2905                self.peek_comment_between(stmt.span.lo(), then.span.lo()).is_some()
2906                    || self.is_multiline_block_stmt(then, empty_as_multiline)
2907            }
2908
2909            // these ones always has an inner block, so we mark them as multiline
2910            ast::StmtKind::Assembly(_)
2911            | ast::StmtKind::DoWhile(_, _)
2912            | ast::StmtKind::Try(_)
2913            | ast::StmtKind::UncheckedBlock(_)
2914            | ast::StmtKind::DeclMulti(_, _)
2915            | ast::StmtKind::DeclSingle(_) => true,
2916
2917            ast::StmtKind::Break
2918            | ast::StmtKind::Continue
2919            | ast::StmtKind::Emit(_, _)
2920            | ast::StmtKind::Expr(_)
2921            | ast::StmtKind::Return(_)
2922            | ast::StmtKind::Revert(_, _)
2923            | ast::StmtKind::Placeholder => {
2924                // Internal comments can force hard breaks even when the source occupies one line.
2925                self.peek_comment_between(stmt.span.lo(), stmt.span.hi()).is_some()
2926            }
2927        }
2928    }
2929
2930    /// Checks if a block statement `{ ... }` should be treated as multiline,
2931    /// either because it spans multiple lines or contains multiple statements.
2932    fn is_multiline_block(
2933        &mut self,
2934        block: &'ast ast::Block<'ast>,
2935        empty_as_multiline: bool,
2936        force_single_as_multiline: bool,
2937    ) -> bool {
2938        if block.stmts.is_empty() {
2939            return empty_as_multiline;
2940        }
2941        // A block with multiple statements should never be inlined, regardless of
2942        // whether it was written on a single line in the source.
2943        if block.stmts.len() > 1 {
2944            return true;
2945        }
2946
2947        if force_single_as_multiline {
2948            return true;
2949        }
2950
2951        // Preserve source layout unless Single requests structural inlining. Comments still
2952        // require the source-line check, as they can force breaks in the printed body.
2953        if (!matches!(
2954            self.config.single_line_statement_blocks,
2955            config::SingleLineBlockStyle::Single
2956        ) || self.peek_comment_between(block.span.lo(), block.span.hi()).is_some())
2957            && !self.same_source_line(block.span.lo(), block.span.hi())
2958            && let Some(snip) = self.snippet(block.span)
2959        {
2960            let mut code_lines = snip.lines().filter(|line| {
2961                let trimmed = line.trim();
2962                // Ignore empty lines and lines with only '{' or '}'.
2963                !trimmed.is_empty() && trimmed != "{" && trimmed != "}"
2964            });
2965            if code_lines.nth(1).is_some() {
2966                return true;
2967            }
2968        }
2969
2970        let stmt = &block.stmts[0];
2971        // Removing the outer braces would leave a standalone block that still prints multiline.
2972        if matches!(stmt.kind, ast::StmtKind::Block(_)) {
2973            return true;
2974        }
2975        // Collapsing a nested body can move trailing comments outside its span. Keep the
2976        // enclosing braces independently of how many source lines the child occupies.
2977        if matches!(stmt.kind, ast::StmtKind::If(..) | ast::StmtKind::While(..))
2978            && self.peek_comment_between(block.span.lo(), block.span.hi()).is_some()
2979        {
2980            return true;
2981        }
2982        // Keep comment context stable when wrapping can introduce new lines after the statement.
2983        if self.config.wrap_comments
2984            && self.peek_comment_between(stmt.span.hi(), block.span.hi()).is_some()
2985        {
2986            return true;
2987        }
2988
2989        // Comments can break single-line layout. Mark block as multiline if there is a comment at
2990        // the beginning.
2991        if self.peek_comment_between(block.span.lo(), stmt.span.lo()).is_some() {
2992            return true;
2993        }
2994
2995        self.is_multiline_block_stmt(stmt, empty_as_multiline)
2996    }
2997
2998    fn for_header_span(
2999        span: Span,
3000        init: &Option<&mut ast::Stmt<'_>>,
3001        cond: &Option<&mut ast::Expr<'_>>,
3002        next: &Option<&mut ast::Expr<'_>>,
3003    ) -> Span {
3004        span.with_hi(
3005            next.as_ref()
3006                .map(|expr| expr.span.hi())
3007                .or_else(|| cond.as_ref().map(|expr| expr.span.hi()))
3008                .or_else(|| init.as_ref().map(|stmt| stmt.span.hi()))
3009                .unwrap_or(span.lo()),
3010        )
3011    }
3012
3013    /// Measures the printed clauses, rather than source spelling or whitespace, so normalization
3014    /// cannot change the inline decision on the second pass.
3015    fn estimate_for_header_size(
3016        &self,
3017        init: &'ast Option<&mut ast::Stmt<'ast>>,
3018        cond: &'ast Option<&mut ast::Expr<'ast>>,
3019        next: &'ast Option<&mut ast::Expr<'ast>>,
3020    ) -> usize {
3021        let mut state = self.statement_sizing_state();
3022        if let Some(init) = init {
3023            state.print_stmt_bound(init, Some(init.span.hi()));
3024        } else {
3025            state.word(";");
3026        }
3027        if let Some(cond) = cond {
3028            state.nbsp();
3029            state.print_expr(cond);
3030        }
3031        state.word(";");
3032        if let Some(next) = next {
3033            state.nbsp();
3034            state.print_expr(next);
3035        }
3036        // 'for (' + clauses + ') '.
3037        7 + state.s.eof().len()
3038    }
3039
3040    /// Measures the normalized body without letting a parent's inline decision remove required
3041    /// braces. For an `if`, the `else` branch is measured separately by `is_inline_stmt`.
3042    fn estimate_inline_stmt_size(&self, stmt: &'ast ast::Stmt<'ast>) -> usize {
3043        let mut state = self.statement_sizing_state();
3044        state.single_line_stmt = Some(true);
3045        if let ast::StmtKind::If(cond, then, _) = &stmt.kind {
3046            state.word("if (");
3047            state.print_expr(cond);
3048            state.word(") ");
3049            state.print_stmt_as_block(then, then.span.hi(), true);
3050        } else {
3051            state.print_stmt_as_block(stmt, stmt.span.hi(), true);
3052        }
3053        state.s.eof().len()
3054    }
3055
3056    /// Keeps both the printer and explicit layout decisions unbounded while measuring statements.
3057    fn statement_sizing_state(&self) -> Self {
3058        let mut config = (*self.config).clone();
3059        config.line_length = SIZE_INFINITY as usize;
3060        let mut state = Self::new(self.file, config.into(), Default::default(), Default::default());
3061        // Measure indentation in spaces even when the output uses tabs.
3062        state.s = crate::pp::Printer::new(SIZE_INFINITY as usize, None);
3063        state.inline_assignments = true;
3064        state
3065    }
3066
3067    fn can_header_be_inlined(&mut self, func: &ast::ItemFunction<'_>) -> bool {
3068        self.estimate_header_size(func) <= self.space_left()
3069    }
3070
3071    fn can_header_params_be_inlined(&mut self, func: &ast::ItemFunction<'_>) -> bool {
3072        self.estimate_header_params_size(func) <= self.space_left()
3073    }
3074
3075    fn estimate_header_size(&mut self, func: &ast::ItemFunction<'_>) -> usize {
3076        let ast::ItemFunction { kind: _, ref header, ref body, body_span: _ } = *func;
3077
3078        // ' ' + visibility
3079        let visibility = header.visibility.map_or(0, |v| self.estimate_size(v.span) + 1);
3080        // ' ' + state mutability
3081        let mutability = header.state_mutability.map_or(0, |sm| self.estimate_size(sm.span) + 1);
3082        // ' ' + modifier + (' ' + modifier)
3083        let m = header.modifiers.iter().fold(0, |len, m| len + self.estimate_size(m.span()));
3084        let modifiers = if m != 0 { m + 1 } else { 0 };
3085        // ' ' + override
3086        let override_ = header.override_.as_ref().map_or(0, |o| self.estimate_size(o.span) + 1);
3087        // ' ' + virtual
3088        let virtual_ = if header.virtual_.is_none() { 0 } else { 8 };
3089        // ' returns(' + var + (', ' + var) + ')'
3090        let returns = header.returns.as_ref().map_or(0, |ret| {
3091            ret.vars
3092                .iter()
3093                .fold(0, |len, p| if len != 0 { len + 2 } else { 10 } + self.estimate_size(p.span))
3094        });
3095        // ' {' or ';'
3096        let end = if body.is_some() { 2 } else { 1 };
3097
3098        self.estimate_header_params_size(func)
3099            + visibility
3100            + mutability
3101            + modifiers
3102            + override_
3103            + virtual_
3104            + returns
3105            + end
3106    }
3107
3108    fn estimate_header_params_size(&mut self, func: &ast::ItemFunction<'_>) -> usize {
3109        let ast::ItemFunction { kind, ref header, body: _, body_span: _ } = *func;
3110
3111        let kw = match kind {
3112            ast::FunctionKind::Constructor => 11, // 'constructor'
3113            ast::FunctionKind::Function => 9,     // 'function '
3114            ast::FunctionKind::Modifier => 9,     // 'modifier '
3115            ast::FunctionKind::Fallback => 8,     // 'fallback'
3116            ast::FunctionKind::Receive => 7,      // 'receive'
3117        };
3118
3119        // '(' + param + (', ' + param) + ')'
3120        let params = header
3121            .parameters
3122            .vars
3123            .iter()
3124            .fold(0, |len, p| if len != 0 { len + 2 } else { 2 } + self.estimate_size(p.span));
3125
3126        kw + header.name.map_or(0, |name| self.estimate_size(name.span)) + std::cmp::max(2, params)
3127    }
3128
3129    /// Estimates a comment-free binary expression using the printed operator spacing.
3130    fn estimate_binary_size(&self, expr: &ast::Expr<'_>) -> usize {
3131        match &expr.kind {
3132            ast::ExprKind::Binary(lhs, op, rhs) => {
3133                let spaces = if self.config.pow_no_space && matches!(op.kind, ast::BinOpKind::Pow) {
3134                    0
3135                } else {
3136                    2
3137                };
3138                self.estimate_binary_size(lhs)
3139                    + op.kind.to_str().len()
3140                    + spaces
3141                    + self.estimate_binary_size(rhs)
3142            }
3143            ast::ExprKind::Tuple(exprs) if let [SpannedOption::Some(inner)] = exprs.as_ref() => {
3144                self.estimate_binary_size(inner) + 2
3145            }
3146            _ => self.estimate_size(expr.span),
3147        }
3148    }
3149
3150    fn estimate_lhs_size(&self, expr: &ast::Expr<'_>, parent_op: &ast::BinOp) -> usize {
3151        match &expr.kind {
3152            ast::ExprKind::Binary(lhs, op, _) if op.kind.group() == parent_op.kind.group() => {
3153                self.estimate_lhs_size(lhs, op)
3154            }
3155            _ => self.estimate_size(expr.span),
3156        }
3157    }
3158
3159    fn estimate_call_chain_size(&self, expr: &ast::Expr<'_>) -> Option<usize> {
3160        match &expr.kind {
3161            ast::ExprKind::Call(callee, args) => {
3162                let ast::CallArgsKind::Unnamed(args) = &args.kind else { return None };
3163                let mut size = self.estimate_call_chain_size(callee)? + 2;
3164                for arg in args.iter() {
3165                    size += self.estimate_call_chain_size(arg)?;
3166                }
3167                Some(size + args.len().saturating_sub(1) * 2)
3168            }
3169            ast::ExprKind::Ident(ident) => Some(ident.to_string().len()),
3170            ast::ExprKind::Index(expr, kind) => {
3171                let index_size = match kind {
3172                    ast::IndexKind::Index(Some(index)) => self.estimate_call_chain_size(index)?,
3173                    ast::IndexKind::Index(None) => 0,
3174                    ast::IndexKind::Range(start, end) => {
3175                        let start = match start {
3176                            Some(start) => self.estimate_call_chain_size(start)?,
3177                            None => 0,
3178                        };
3179                        let end = match end {
3180                            Some(end) => self.estimate_call_chain_size(end)?,
3181                            None => 0,
3182                        };
3183                        start + end + 1
3184                    }
3185                };
3186                Some(self.estimate_call_chain_size(expr)? + index_size + 2)
3187            }
3188            // Zero is invariant under all number underscore configurations.
3189            ast::ExprKind::Lit(lit, None)
3190                if matches!(lit.kind, ast::LitKind::Number(_)) && lit.symbol.as_str() == "0" =>
3191            {
3192                Some(1)
3193            }
3194            ast::ExprKind::Member(expr, ident) => {
3195                Some(self.estimate_call_chain_size(expr)? + ident.to_string().len() + 1)
3196            }
3197            ast::ExprKind::Tuple(exprs) if let [SpannedOption::Some(expr)] = exprs.as_ref() => {
3198                Some(self.estimate_call_chain_size(expr)? + 2)
3199            }
3200            _ => None,
3201        }
3202    }
3203
3204    fn has_comments_between_elements<I>(&self, limits: Span, elements: I) -> bool
3205    where
3206        I: IntoIterator<Item = &'ast ast::Expr<'ast>>,
3207    {
3208        let mut last_span_end = limits.lo();
3209        for expr in elements {
3210            if self.has_comment_between(last_span_end, expr.span.lo()) {
3211                return true;
3212            }
3213            last_span_end = expr.span.hi();
3214        }
3215
3216        self.has_comment_between(last_span_end, limits.hi())
3217    }
3218}
3219
3220// -- HELPERS (language-specific) ----------------------------------------------
3221
3222#[derive(Debug)]
3223enum MemberOrCallArgs {
3224    Member(usize),
3225    CallArgs(usize, bool),
3226}
3227
3228impl MemberOrCallArgs {
3229    const fn size(&self) -> usize {
3230        match self {
3231            Self::CallArgs(size, ..) | Self::Member(size) => *size,
3232        }
3233    }
3234
3235    const fn member_size(&self) -> usize {
3236        match self {
3237            Self::CallArgs(..) => 0,
3238            Self::Member(size) => *size,
3239        }
3240    }
3241
3242    const fn has_comments(&self) -> bool {
3243        matches!(self, Self::CallArgs(.., true))
3244    }
3245}
3246
3247#[derive(Debug, Clone)]
3248#[expect(dead_code)]
3249enum AttributeKind<'ast> {
3250    Visibility(ast::Visibility),
3251    StateMutability(ast::StateMutability),
3252    Virtual,
3253    Override(&'ast ast::Override<'ast>),
3254    Modifier(&'ast ast::Modifier<'ast>),
3255}
3256
3257type AttributeCommentMap = HashMap<BytePos, (Vec<Comment>, Vec<Comment>, Vec<Comment>)>;
3258
3259#[derive(Debug, Clone)]
3260struct AttributeInfo<'ast> {
3261    kind: AttributeKind<'ast>,
3262    span: Span,
3263}
3264
3265/// Helper struct to map attributes to their associated comments in function headers.
3266struct AttributeCommentMapper<'ast> {
3267    limit_pos: BytePos,
3268    comments: Vec<Comment>,
3269    attributes: Vec<AttributeInfo<'ast>>,
3270}
3271
3272impl<'ast> AttributeCommentMapper<'ast> {
3273    fn new(returns: Option<&'ast ast::ParameterList<'ast>>, body_pos: BytePos) -> Self {
3274        Self {
3275            comments: Vec::new(),
3276            attributes: Vec::new(),
3277            limit_pos: returns.as_ref().map_or(body_pos, |ret| ret.span.lo()),
3278        }
3279    }
3280
3281    #[allow(clippy::type_complexity)]
3282    fn build(
3283        mut self,
3284        state: &mut State<'_, 'ast>,
3285        header: &'ast ast::FunctionHeader<'ast>,
3286    ) -> (AttributeCommentMap, Vec<AttributeInfo<'ast>>, BytePos) {
3287        let first_attr = self.collect_attributes(header);
3288        if !self.attributes.is_empty() {
3289            self.cache_comments(state);
3290        }
3291        (self.map(), self.attributes, first_attr)
3292    }
3293
3294    fn map(&mut self) -> AttributeCommentMap {
3295        let mut map = HashMap::new();
3296        for a in 0..self.attributes.len() {
3297            let is_last = a == self.attributes.len() - 1;
3298            let (mut before, mut inner, mut after) = (Vec::new(), Vec::new(), Vec::new());
3299
3300            let before_limit = self.attributes[a].span.lo();
3301            let inner_limit = self.attributes[a].span.hi();
3302            let after_limit =
3303                if is_last { self.limit_pos } else { self.attributes[a + 1].span.lo() };
3304
3305            let mut c = 0;
3306            while c < self.comments.len() {
3307                if self.comments[c].pos() <= before_limit {
3308                    before.push(self.comments.remove(c));
3309                } else if self.comments[c].pos() <= inner_limit {
3310                    inner.push(self.comments.remove(c));
3311                } else if (after.is_empty() || is_last) && self.comments[c].pos() <= after_limit {
3312                    after.push(self.comments.remove(c));
3313                } else {
3314                    c += 1;
3315                }
3316            }
3317            map.insert(before_limit, (before, inner, after));
3318        }
3319        map
3320    }
3321
3322    fn collect_attributes(&mut self, header: &'ast ast::FunctionHeader<'ast>) -> BytePos {
3323        let mut first_pos = BytePos(u32::MAX);
3324        if let Some(v) = header.visibility {
3325            if v.span.lo() < first_pos {
3326                first_pos = v.span.lo()
3327            }
3328            self.attributes
3329                .push(AttributeInfo { kind: AttributeKind::Visibility(*v), span: v.span });
3330        }
3331        if let Some(sm) = header.state_mutability {
3332            if sm.span.lo() < first_pos {
3333                first_pos = sm.span.lo()
3334            }
3335            self.attributes
3336                .push(AttributeInfo { kind: AttributeKind::StateMutability(*sm), span: sm.span });
3337        }
3338        if let Some(span) = header.virtual_ {
3339            if span.lo() < first_pos {
3340                first_pos = span.lo()
3341            }
3342            self.attributes.push(AttributeInfo { kind: AttributeKind::Virtual, span });
3343        }
3344        if let Some(ref o) = header.override_ {
3345            if o.span.lo() < first_pos {
3346                first_pos = o.span.lo()
3347            }
3348            self.attributes.push(AttributeInfo { kind: AttributeKind::Override(o), span: o.span });
3349        }
3350        for m in header.modifiers.iter() {
3351            if m.span().lo() < first_pos {
3352                first_pos = m.span().lo()
3353            }
3354            self.attributes
3355                .push(AttributeInfo { kind: AttributeKind::Modifier(m), span: m.span() });
3356        }
3357        self.attributes.sort_by_key(|attr| attr.span.lo());
3358        first_pos
3359    }
3360
3361    fn cache_comments(&mut self, state: &mut State<'_, 'ast>) {
3362        let mut pending = None;
3363        for cmnt in state.comments.iter() {
3364            if cmnt.pos() >= self.limit_pos {
3365                break;
3366            }
3367            match pending {
3368                Some(ref p) => pending = Some(p + 1),
3369                None => pending = Some(0),
3370            }
3371        }
3372        while let Some(p) = pending {
3373            if p == 0 {
3374                pending = None;
3375            } else {
3376                pending = Some(p - 1);
3377            }
3378            let cmnt = state.next_comment().unwrap();
3379            if cmnt.style.is_blank() {
3380                continue;
3381            }
3382            self.comments.push(cmnt);
3383        }
3384    }
3385}
3386
3387const fn stmt_needs_semi(stmt: &ast::StmtKind<'_>) -> bool {
3388    match stmt {
3389        ast::StmtKind::Assembly { .. }
3390        | ast::StmtKind::Block { .. }
3391        | ast::StmtKind::For { .. }
3392        | ast::StmtKind::If { .. }
3393        | ast::StmtKind::Try { .. }
3394        | ast::StmtKind::UncheckedBlock { .. }
3395        | ast::StmtKind::While { .. } => false,
3396
3397        ast::StmtKind::DeclSingle { .. }
3398        | ast::StmtKind::DeclMulti { .. }
3399        | ast::StmtKind::Break { .. }
3400        | ast::StmtKind::Continue { .. }
3401        | ast::StmtKind::DoWhile { .. }
3402        | ast::StmtKind::Emit { .. }
3403        | ast::StmtKind::Expr { .. }
3404        | ast::StmtKind::Return { .. }
3405        | ast::StmtKind::Revert { .. }
3406        | ast::StmtKind::Placeholder { .. } => true,
3407    }
3408}
3409
3410/// Returns `true` if the item needs an isolated line break.
3411fn item_needs_iso(item: &ast::ItemKind<'_>) -> bool {
3412    match item {
3413        ast::ItemKind::Pragma(..)
3414        | ast::ItemKind::Import(..)
3415        | ast::ItemKind::Using(..)
3416        | ast::ItemKind::Variable(..)
3417        | ast::ItemKind::Udvt(..)
3418        | ast::ItemKind::Enum(..)
3419        | ast::ItemKind::Error(..)
3420        | ast::ItemKind::Event(..) => false,
3421
3422        ast::ItemKind::Contract(..) => true,
3423
3424        ast::ItemKind::Struct(strukt) => !strukt.fields.is_empty(),
3425        ast::ItemKind::Function(func) => {
3426            func.body.as_ref().is_some_and(|b| !b.is_empty())
3427                && !matches!(func.kind, ast::FunctionKind::Modifier)
3428        }
3429    }
3430}
3431
3432const fn is_binary_expr(expr_kind: &ast::ExprKind<'_>) -> bool {
3433    matches!(expr_kind, ast::ExprKind::Binary(..))
3434}
3435
3436fn has_complex_successor(expr_kind: &ast::ExprKind<'_>, left: bool) -> bool {
3437    match expr_kind {
3438        ast::ExprKind::Binary(lhs, _, rhs) => {
3439            if left {
3440                has_complex_successor(&lhs.kind, left)
3441            } else {
3442                has_complex_successor(&rhs.kind, left)
3443            }
3444        }
3445        ast::ExprKind::Unary(_, expr) => has_complex_successor(&expr.kind, left),
3446        ast::ExprKind::Lit(..) | ast::ExprKind::Ident(_) => false,
3447        ast::ExprKind::Tuple(..) => false,
3448        _ => true,
3449    }
3450}
3451
3452const fn is_call(expr_kind: &ast::ExprKind<'_>) -> bool {
3453    matches!(expr_kind, ast::ExprKind::Call(..))
3454}
3455
3456/// Returns true if this is a call with named arguments (struct-style syntax).
3457/// Used to determine if `.field` after such a call should avoid breaking.
3458/// E.g., `_lzSend({_dstEid: x, ...}).guid` → true (named args call)
3459/// E.g., `someFunc(a, b).field` → false (positional args)
3460const fn is_call_with_named_args(expr_kind: &ast::ExprKind<'_>) -> bool {
3461    if let ast::ExprKind::Call(_, args) = expr_kind {
3462        matches!(args.kind, ast::CallArgsKind::Named(_))
3463    } else {
3464        false
3465    }
3466}
3467
3468fn is_call_chain(expr_kind: &ast::ExprKind<'_>, must_have_child: bool) -> bool {
3469    match expr_kind {
3470        ast::ExprKind::Index(child, ..) | ast::ExprKind::Member(child, ..) => {
3471            is_call_chain(&child.kind, false)
3472        }
3473        ast::ExprKind::Tuple(exprs) if let [SpannedOption::Some(child)] = exprs.as_ref() => {
3474            is_call_chain(&child.kind, must_have_child)
3475        }
3476        _ => !must_have_child && is_call(expr_kind),
3477    }
3478}
3479
3480fn call_chain_contains_options(expr: &ast::Expr<'_>) -> bool {
3481    match &expr.peel_parens().kind {
3482        ast::ExprKind::CallOptions(..) => true,
3483        ast::ExprKind::Call(expr, ..)
3484        | ast::ExprKind::Index(expr, ..)
3485        | ast::ExprKind::Member(expr, ..) => call_chain_contains_options(expr),
3486        _ => false,
3487    }
3488}
3489
3490fn is_call_with_opts_and_args(expr_kind: &ast::ExprKind<'_>) -> bool {
3491    if let ast::ExprKind::Call(call_expr, call_args) = expr_kind {
3492        matches!(call_expr.kind, ast::ExprKind::CallOptions(..)) && !call_args.is_empty()
3493    } else {
3494        false
3495    }
3496}
3497
3498#[derive(Debug)]
3499struct Decision {
3500    outcome: bool,
3501    is_cached: bool,
3502}
3503
3504#[derive(Clone, Copy, PartialEq, Eq)]
3505pub(crate) enum BinOpGroup {
3506    Arithmetic,
3507    Bitwise,
3508    Comparison,
3509    Logical,
3510}
3511
3512trait BinOpExt {
3513    fn group(&self) -> BinOpGroup;
3514}
3515
3516impl BinOpExt for ast::BinOpKind {
3517    fn group(&self) -> BinOpGroup {
3518        match self {
3519            Self::Or | Self::And => BinOpGroup::Logical,
3520            Self::Eq | Self::Ne | Self::Lt | Self::Le | Self::Gt | Self::Ge => {
3521                BinOpGroup::Comparison
3522            }
3523            Self::BitOr | Self::BitXor | Self::BitAnd | Self::Shl | Self::Shr | Self::Sar => {
3524                BinOpGroup::Bitwise
3525            }
3526            Self::Add | Self::Sub | Self::Mul | Self::Div | Self::Rem | Self::Pow => {
3527                BinOpGroup::Arithmetic
3528            }
3529        }
3530    }
3531}
3532
3533/// Calculates the size the callee's "head," excluding its arguments.
3534///
3535/// # Examples
3536///
3537/// - `myFunction(..)`: 8 (length of `myFunction`)
3538/// - `uint256(..)`: 7 (length of `uint256`)
3539/// - `abi.encode(..)`: 10 (length of `abi.encode`)
3540/// - `foo(..).bar(..)`: 3 (length of `foo`)
3541pub(super) fn get_callee_head_size(callee: &ast::Expr<'_>) -> usize {
3542    match &callee.kind {
3543        ast::ExprKind::Ident(id) => id.as_str().len(),
3544        ast::ExprKind::Type(ast::Type { kind: ast::TypeKind::Elementary(ty), .. }) => {
3545            ty.to_abi_str().len()
3546        }
3547        ast::ExprKind::Index(base, idx) => {
3548            let idx_len = match idx {
3549                ast::IndexKind::Index(expr) => expr.as_ref().map_or(0, |e| get_callee_head_size(e)),
3550                ast::IndexKind::Range(e1, e2) => {
3551                    1 + e1.as_ref().map_or(0, |e| get_callee_head_size(e))
3552                        + e2.as_ref().map_or(0, |e| get_callee_head_size(e))
3553                }
3554            };
3555            get_callee_head_size(base) + 2 + idx_len
3556        }
3557        ast::ExprKind::Member(base, member_ident) => {
3558            match &base.kind {
3559                ast::ExprKind::Ident(..) | ast::ExprKind::Type(..) => {
3560                    get_callee_head_size(base) + 1 + member_ident.as_str().len()
3561                }
3562
3563                // Chainned calls are not traversed, and instead just the member identifier is used
3564                ast::ExprKind::Member(child, ..) if !is_call(&child.kind) => {
3565                    get_callee_head_size(base) + 1 + member_ident.as_str().len()
3566                }
3567                _ => member_ident.as_str().len(),
3568            }
3569        }
3570        ast::ExprKind::Binary(lhs, _, _) => get_callee_head_size(lhs),
3571
3572        // If the callee is not an identifier or member access, it has no "head"
3573        _ => 0,
3574    }
3575}
3576
3577/// Counts member links in an assignment RHS, through calls and indexes.
3578fn assignment_member_depth(expr: &ast::Expr<'_>) -> usize {
3579    match &expr.kind {
3580        ast::ExprKind::Member(child, _) => 1 + assignment_member_depth(child),
3581        ast::ExprKind::Call(child, _) | ast::ExprKind::Index(child, _) => {
3582            assignment_member_depth(child)
3583        }
3584        _ => 0,
3585    }
3586}
3587
3588#[cfg(test)]
3589mod tests {
3590    use super::*;
3591    use crate::{FormatterConfig, InlineConfig};
3592    use foundry_common::comments::Comments;
3593    use solar::{
3594        interface::{Session, source_map::FileName},
3595        sema::Compiler,
3596    };
3597    use std::sync::Arc;
3598
3599    /// This helper extracts function headers from the AST and passes them to the test function.
3600    fn parse_and_test<F>(source: &str, test_fn: F)
3601    where
3602        F: FnOnce(&mut State<'_, '_>, &ast::ItemFunction<'_>) + Send,
3603    {
3604        let session = Session::builder().with_buffer_emitter(Default::default()).build();
3605        let mut compiler = Compiler::new(session);
3606
3607        compiler
3608            .enter_mut(|c| -> solar::interface::Result<()> {
3609                let mut pcx = c.parse();
3610                pcx.set_resolve_imports(false);
3611
3612                // Create a source file using stdin as the filename
3613                let file = c
3614                    .sess()
3615                    .source_map()
3616                    .new_source_file(FileName::Stdin, source)
3617                    .map_err(|e| c.sess().dcx.err(e.to_string()).emit())?;
3618
3619                pcx.add_file(file.clone());
3620                pcx.parse();
3621                c.dcx().has_errors()?;
3622
3623                // Get AST from parsed source and setup the formatter
3624                let gcx = c.gcx();
3625                let (_, source_obj) = gcx.get_ast_source(&file.name).expect("Failed to get AST");
3626                let ast = source_obj.ast.as_ref().expect("No AST found");
3627                let comments =
3628                    Comments::new(&source_obj.file, gcx.sess.source_map(), true, false, None);
3629                let config = Arc::new(FormatterConfig::default());
3630                let inline_config = InlineConfig::default();
3631                let mut state = State::new(&source_obj.file, config, inline_config, comments);
3632
3633                // Extract the first function header (either top-level or inside a contract)
3634                let func = ast
3635                    .items
3636                    .iter()
3637                    .find_map(|item| match &item.kind {
3638                        ast::ItemKind::Function(func) => Some(func),
3639                        ast::ItemKind::Contract(contract) => {
3640                            contract.body.iter().find_map(|contract_item| {
3641                                match &contract_item.kind {
3642                                    ast::ItemKind::Function(func) => Some(func),
3643                                    _ => None,
3644                                }
3645                            })
3646                        }
3647                        _ => None,
3648                    })
3649                    .expect("No function found in source");
3650
3651                // Run the closure
3652                test_fn(&mut state, func);
3653
3654                Ok(())
3655            })
3656            .expect("Test failed");
3657    }
3658
3659    #[test]
3660    fn test_estimate_header_sizes() {
3661        let test_cases = [
3662            ("function foo();", 14, 15),
3663            ("function foo() {}", 14, 16),
3664            ("function foo() public {}", 14, 23),
3665            ("function foo(uint256 a) public {}", 23, 32),
3666            ("function foo(uint256 a, address b, bool c) public {}", 42, 51),
3667            ("function foo() public pure {}", 14, 28),
3668            ("function foo() public virtual {}", 14, 31),
3669            ("function foo() public override {}", 14, 32),
3670            ("function foo() public onlyOwner {}", 14, 33),
3671            ("function foo() public returns(uint256) {}", 14, 40),
3672            ("function foo() public returns(uint256, address) {}", 14, 49),
3673            ("function foo(uint256 a) public virtual override returns(uint256) {}", 23, 66),
3674            ("function foo() external payable {}", 14, 33),
3675            // other function types
3676            ("contract C { constructor() {} }", 13, 15),
3677            ("contract C { constructor(uint256 a) {} }", 22, 24),
3678            ("contract C { modifier onlyOwner() {} }", 20, 22),
3679            ("contract C { modifier onlyRole(bytes32 role) {} }", 31, 33),
3680            ("contract C { fallback() external payable {} }", 10, 29),
3681            ("contract C { receive() external payable {} }", 9, 28),
3682        ];
3683
3684        for (source, expected_params, expected_header) in &test_cases {
3685            parse_and_test(source, |state, func| {
3686                let params_size = state.estimate_header_params_size(func);
3687                assert_eq!(
3688                    params_size, *expected_params,
3689                    "Failed params size: expected {expected_params}, got {params_size} for source: {source}",
3690                );
3691
3692                let header_size = state.estimate_header_size(func);
3693                assert_eq!(
3694                    header_size, *expected_header,
3695                    "Failed header size: expected {expected_header}, got {header_size} for source: {source}",
3696                );
3697            });
3698        }
3699    }
3700}