-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Expand file tree
/
Copy pathsol.rs
More file actions
2940 lines (2711 loc) · 106 KB
/
Copy pathsol.rs
File metadata and controls
2940 lines (2711 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::too_many_arguments)]
use super::{
CommentConfig, Separator, State,
common::{BlockFormat, ListFormat},
};
use crate::{
pp::SIZE_INFINITY,
state::{CallContext, common::LitExt},
};
use foundry_common::{comments::Comment, iter::IterDelimited};
use foundry_config::fmt::{self as config, MultilineFuncHeaderStyle};
use solar::{
ast::BoxSlice,
interface::SpannedOption,
parse::{
ast::{self, Span},
interface::BytePos,
},
};
use std::{collections::HashMap, fmt::Debug};
#[rustfmt::skip]
macro_rules! get_span {
() => { |value| value.span };
(()) => { |value| value.span() };
}
/// Language-specific pretty printing: Solidity.
impl<'ast> State<'_, 'ast> {
pub(crate) fn print_source_unit(&mut self, source_unit: &'ast ast::SourceUnit<'ast>) {
// Figure out if the cursor needs to check for CR (`\r`).
if let Some(item) = source_unit.items.first() {
self.check_crlf(item.span.to(source_unit.items.last().unwrap().span));
}
let mut items = source_unit.items.iter().peekable();
let mut is_first = true;
while let Some(item) = items.next() {
// If imports shouldn't be sorted, or if the item is not an import, print it directly.
if !self.config.sort_imports || !matches!(item.kind, ast::ItemKind::Import(_)) {
self.print_item(item, is_first);
is_first = false;
if let Some(next_item) = items.peek() {
self.separate_items(next_item, false);
}
continue;
}
// Otherwise, collect a group of consecutive imports and sort them before printing.
let mut import_group = vec![item];
while let Some(next_item) = items.peek() {
// Groups end when the next item is not an import or when there is a blank line.
if !matches!(next_item.kind, ast::ItemKind::Import(_))
|| self.has_comment_between(item.span.hi(), next_item.span.lo())
{
break;
}
import_group.push(items.next().unwrap());
}
import_group.sort_by_key(|item| {
if let ast::ItemKind::Import(import) = &item.kind {
import.path.value.as_str()
} else {
unreachable!("Expected an import item")
}
});
for (pos, group_item) in import_group.iter().delimited() {
self.print_item(group_item, is_first);
is_first = false;
if !pos.is_last {
self.hardbreak_if_not_bol();
}
}
if let Some(next_item) = items.peek() {
self.separate_items(next_item, false);
}
}
self.print_remaining_comments(is_first);
}
/// Prints a hardbreak if the item needs an isolated line break.
fn separate_items(&mut self, next_item: &'ast ast::Item<'ast>, advance: bool) {
if !item_needs_iso(&next_item.kind) {
return;
}
let span = next_item.span;
let cmnts = self
.comments
.iter()
.filter_map(|c| if c.pos() < span.lo() { Some(c.style) } else { None })
.collect::<Vec<_>>();
if let Some(first) = cmnts.first()
&& let Some(last) = cmnts.last()
{
if !(first.is_blank() || last.is_blank()) {
self.hardbreak();
return;
}
if advance {
if self.peek_comment_before(span.lo()).is_some() {
self.print_comments(span.lo(), CommentConfig::default());
} else if self.inline_config.is_disabled(span.shrink_to_lo()) {
self.hardbreak();
self.cursor.advance_to(span.lo(), true);
}
}
} else {
self.hardbreak();
}
}
fn print_item(&mut self, item: &'ast ast::Item<'ast>, skip_ws: bool) {
let ast::Item { ref docs, span, ref kind } = *item;
self.print_docs(docs);
if self.handle_span(item.span, skip_ws) {
if !self.print_trailing_comment(span.hi(), None) {
self.print_sep(Separator::Hardbreak);
}
return;
}
if self
.print_comments(
span.lo(),
if skip_ws {
CommentConfig::skip_leading_ws(false)
} else {
CommentConfig::default()
},
)
.is_some_and(|cmnt| cmnt.is_mixed())
{
self.zerobreak();
}
match kind {
ast::ItemKind::Pragma(pragma) => self.print_pragma(pragma),
ast::ItemKind::Import(import) => self.print_import(import),
ast::ItemKind::Using(using) => self.print_using(using),
ast::ItemKind::Contract(contract) => self.print_contract(contract, span),
ast::ItemKind::Function(func) => self.print_function(func),
ast::ItemKind::Variable(var) => self.print_var_def(var),
ast::ItemKind::Struct(strukt) => self.print_struct(strukt, span),
ast::ItemKind::Enum(enm) => self.print_enum(enm, span),
ast::ItemKind::Udvt(udvt) => self.print_udvt(udvt),
ast::ItemKind::Error(err) => self.print_error(err),
ast::ItemKind::Event(event) => self.print_event(event),
}
self.cursor.advance_to(span.hi(), true);
self.print_comments(span.hi(), CommentConfig::default());
self.print_trailing_comment(span.hi(), None);
self.hardbreak_if_not_bol();
self.cursor.next_line(self.is_at_crlf());
}
fn print_pragma(&mut self, pragma: &'ast ast::PragmaDirective<'ast>) {
self.word("pragma ");
match &pragma.tokens {
ast::PragmaTokens::Version(ident, semver_req) => {
self.print_ident(ident);
self.nbsp();
self.word(semver_req.to_string());
}
ast::PragmaTokens::Custom(a, b) => {
self.print_ident_or_strlit(a);
if let Some(b) = b {
self.nbsp();
self.print_ident_or_strlit(b);
}
}
ast::PragmaTokens::Verbatim(tokens) => {
self.print_tokens(tokens);
}
}
self.word(";");
}
fn print_commasep_aliases<'a, I>(&mut self, aliases: I)
where
I: Iterator<Item = &'a (ast::Ident, Option<ast::Ident>)>,
'ast: 'a,
{
for (pos, (ident, alias)) in aliases.delimited() {
self.print_ident(ident);
if let Some(alias) = alias {
self.word(" as ");
self.print_ident(alias);
}
if !pos.is_last {
self.word(",");
self.space();
}
}
}
fn print_import(&mut self, import: &'ast ast::ImportDirective<'ast>) {
let ast::ImportDirective { path, items } = import;
self.word("import ");
match items {
ast::ImportItems::Plain(_) | ast::ImportItems::Glob(_) => {
self.print_ast_str_lit(path);
if let Some(ident) = items.source_alias() {
self.word(" as ");
self.print_ident(&ident);
}
}
ast::ImportItems::Aliases(aliases) => {
self.s.cbox(self.ind);
self.word("{");
self.braces_break();
if self.config.sort_imports {
let mut sorted: Vec<_> = aliases.iter().collect();
sorted.sort_by_key(|(ident, _alias)| ident.name.as_str());
self.print_commasep_aliases(sorted.into_iter());
} else {
self.print_commasep_aliases(aliases.iter());
};
self.braces_break();
self.s.offset(-self.ind);
self.word("}");
self.end();
self.word(" from ");
self.print_ast_str_lit(path);
}
}
self.word(";");
}
fn print_using(&mut self, using: &'ast ast::UsingDirective<'ast>) {
let ast::UsingDirective { list, ty, global } = using;
self.word("using ");
match list {
ast::UsingList::Single(path) => self.print_path(path, true),
ast::UsingList::Multiple(items) => {
self.s.cbox(self.ind);
self.word("{");
self.braces_break();
for (pos, (path, op)) in items.iter().delimited() {
self.print_path(path, true);
if let Some(op) = op {
self.word(" as ");
self.word(op.to_str());
}
if !pos.is_last {
self.word(",");
self.space();
}
}
self.braces_break();
self.s.offset(-self.ind);
self.word("}");
self.end();
}
}
self.word(" for ");
if let Some(ty) = ty {
self.print_ty(ty);
} else {
self.word("*");
}
if *global {
self.word(" global");
}
self.word(";");
}
fn print_contract(&mut self, c: &'ast ast::ItemContract<'ast>, span: Span) {
let ast::ItemContract { kind, name, layout, bases, body } = c;
self.contract = Some(c);
self.cursor.advance_to(span.lo(), true);
self.s.cbox(self.ind);
self.ibox(0);
self.cbox(0);
self.word_nbsp(kind.to_str());
self.print_ident(name);
self.nbsp();
if let Some(layout) = layout
&& !self.handle_span(layout.span, false)
{
self.word("layout at ");
self.print_expr(layout.slot);
self.print_sep(Separator::Space);
}
if let Some(first) = bases.first().map(|base| base.span())
&& let Some(last) = bases.last().map(|base| base.span())
&& self.inline_config.is_disabled(first.to(last))
{
_ = self.handle_span(first.until(last), false);
} else if !bases.is_empty() {
self.word("is");
self.space();
let last = bases.len() - 1;
for (i, base) in bases.iter().enumerate() {
if !self.handle_span(base.span(), false) {
self.print_modifier_call(base, false);
if i != last {
self.word(",");
if self
.print_comments(
bases[i + 1].span().lo(),
CommentConfig::skip_ws().mixed_prev_space().mixed_post_nbsp(),
)
.is_none()
{
self.space();
}
}
}
}
if !self.print_trailing_comment(bases.last().unwrap().span().hi(), None) {
self.space();
}
self.s.offset(-self.ind);
}
self.end();
self.print_word("{");
self.end();
if !body.is_empty() {
// update block depth
self.block_depth += 1;
self.print_sep(Separator::Hardbreak);
if self.config.contract_new_lines {
self.hardbreak();
}
let body_lo = body[0].span.lo();
if self.peek_comment_before(body_lo).is_some() {
self.print_comments(body_lo, CommentConfig::skip_leading_ws(true));
}
let mut is_first = true;
let mut items = body.iter().peekable();
while let Some(item) = items.next() {
self.print_item(item, is_first);
is_first = false;
if let Some(next_item) = items.peek() {
if self.inline_config.is_disabled(next_item.span) {
_ = self.handle_span(next_item.span, false);
} else {
self.separate_items(next_item, true);
}
}
}
if let Some(cmnt) = self.print_comments(span.hi(), CommentConfig::skip_trailing_ws())
&& self.config.contract_new_lines
&& !cmnt.is_blank()
{
self.print_sep(Separator::Hardbreak);
}
self.s.offset(-self.ind);
self.end();
if self.config.contract_new_lines {
self.hardbreak_if_nonempty();
}
// restore block depth
self.block_depth -= 1;
} else {
if self.print_comments(span.hi(), CommentConfig::skip_ws()).is_some() {
self.zerobreak();
} else if self.config.bracket_spacing {
self.nbsp();
};
self.end();
}
self.print_word("}");
self.cursor.advance_to(span.hi(), true);
self.contract = None;
}
fn print_struct(&mut self, strukt: &'ast ast::ItemStruct<'ast>, span: Span) {
let ast::ItemStruct { name, fields } = strukt;
let ind = if self.estimate_size(name.span) + 8 >= self.space_left() { self.ind } else { 0 };
self.s.ibox(self.ind);
self.word("struct");
self.space();
self.print_ident(name);
self.word(" {");
if !fields.is_empty() {
self.break_offset(SIZE_INFINITY as usize, ind);
}
self.s.ibox(0);
for var in fields.iter() {
self.print_var_def(var);
if !self.print_trailing_comment(var.span.hi(), None) {
self.hardbreak();
}
}
self.print_comments(span.hi(), CommentConfig::skip_ws());
if ind == 0 {
self.s.offset(-self.ind);
}
self.end();
self.end();
self.word("}");
}
fn print_enum(&mut self, enm: &'ast ast::ItemEnum<'ast>, span: Span) {
let ast::ItemEnum { name, variants } = enm;
self.s.cbox(self.ind);
self.word("enum ");
self.print_ident(name);
self.word(" {");
self.hardbreak_if_nonempty();
for (pos, ident) in variants.iter().delimited() {
self.print_comments(ident.span.lo(), CommentConfig::default());
self.print_ident(ident);
if !pos.is_last {
self.word(",");
}
if !self.print_trailing_comment(ident.span.hi(), None) {
self.hardbreak();
}
}
self.print_comments(span.hi(), CommentConfig::skip_ws());
self.s.offset(-self.ind);
self.end();
self.word("}");
}
fn print_udvt(&mut self, udvt: &'ast ast::ItemUdvt<'ast>) {
let ast::ItemUdvt { name, ty } = udvt;
self.word("type ");
self.print_ident(name);
self.word(" is ");
self.print_ty(ty);
self.word(";");
}
// NOTE(rusowsky): Functions are the only source unit item that handle inline (disabled) format
fn print_function(&mut self, func: &'ast ast::ItemFunction<'ast>) {
let ast::ItemFunction { kind, ref header, ref body, body_span } = *func;
let ast::FunctionHeader {
name,
ref parameters,
visibility,
state_mutability: sm,
virtual_,
ref override_,
ref returns,
..
} = *header;
self.s.cbox(self.ind);
// Print fn name and params
_ = self.handle_span(self.cursor.span(header.span.lo()), false);
self.print_word(kind.to_str());
if let Some(name) = name {
self.print_sep(Separator::Nbsp);
self.print_ident(&name);
self.cursor.advance_to(name.span.hi(), true);
}
self.s.cbox(-self.ind);
let header_style = self.config.multiline_func_header;
let params_format = match header_style {
MultilineFuncHeaderStyle::ParamsAlways => ListFormat::always_break(),
MultilineFuncHeaderStyle::All
if header.parameters.len() > 1 && !self.can_header_be_inlined(header) =>
{
ListFormat::always_break()
}
MultilineFuncHeaderStyle::AllParams
if !header.parameters.is_empty() && !self.can_header_be_inlined(header) =>
{
ListFormat::always_break()
}
_ => ListFormat::consistent().break_cmnts().break_single(
// ensure fn params are always breakable when there is a single `Contract.Struct`
parameters.len() == 1
&& matches!(
¶meters[0].ty,
ast::Type { kind: ast::TypeKind::Custom(ty), .. } if ty.segments().len() > 1
),
),
};
self.print_parameter_list(parameters, parameters.span, params_format);
self.end();
// Map attributes to their corresponding comments
let (mut map, attributes, first_attrib_pos) =
AttributeCommentMapper::new(returns.as_ref(), body_span.lo()).build(self, header);
let mut handle_pre_cmnts = |this: &mut Self, span: Span| -> bool {
if this.inline_config.is_disabled(span)
// Note: `map` is still captured from the outer scope, which is fine.
&& let Some((pre_cmnts, ..)) = map.remove(&span.lo())
{
for (pos, cmnt) in pre_cmnts.into_iter().delimited() {
if pos.is_first && cmnt.style.is_isolated() && !this.is_bol_or_only_ind() {
this.print_sep(Separator::Hardbreak);
}
if let Some(cmnt) = this.handle_comment(cmnt, false) {
this.print_comment(cmnt, CommentConfig::skip_ws().mixed_post_nbsp());
}
if pos.is_last {
return true;
}
}
}
false
};
let skip_attribs = returns.as_ref().is_some_and(|ret| {
let attrib_span = Span::new(first_attrib_pos, ret.span.lo());
handle_pre_cmnts(self, attrib_span);
self.handle_span(attrib_span, false)
});
let skip_returns = {
let pos = if skip_attribs { self.cursor.pos } else { first_attrib_pos };
let ret_span = Span::new(pos, body_span.lo());
handle_pre_cmnts(self, ret_span);
self.handle_span(ret_span, false)
};
let attrib_box = self.config.multiline_func_header.params_first()
|| (self.config.multiline_func_header.attrib_first()
&& !self.can_header_params_be_inlined(header));
if attrib_box {
self.s.cbox(0);
}
if !(skip_attribs || skip_returns) {
// Print fn attributes in correct order
if let Some(v) = visibility {
self.print_fn_attribute(v.span, &mut map, &mut |s| s.word(v.to_str()));
}
if let Some(sm) = sm
&& !matches!(*sm, ast::StateMutability::NonPayable)
{
self.print_fn_attribute(sm.span, &mut map, &mut |s| s.word(sm.to_str()));
}
if let Some(v) = virtual_ {
self.print_fn_attribute(v, &mut map, &mut |s| s.word("virtual"));
}
if let Some(o) = override_ {
self.print_fn_attribute(o.span, &mut map, &mut |s| s.print_override(o));
}
for m in attributes.iter().filter(|a| matches!(a.kind, AttributeKind::Modifier(_))) {
if let AttributeKind::Modifier(modifier) = m.kind {
let is_base = self.is_modifier_a_base_contract(kind, modifier);
self.print_fn_attribute(m.span, &mut map, &mut |s| {
s.print_modifier_call(modifier, is_base)
});
}
}
}
if !skip_returns
&& let Some(ret) = returns
&& !ret.is_empty()
{
if !self.handle_span(self.cursor.span(ret.span.lo()), false) {
if !self.is_bol_or_only_ind() && !self.last_token_is_space() {
self.print_sep(Separator::Space);
}
self.cursor.advance_to(ret.span.lo(), true);
self.print_word("returns ");
}
self.print_parameter_list(
ret,
ret.span,
ListFormat::consistent(), // .with_cmnts_break(false),
);
}
// Print fn body
if let Some(body) = body {
if self.handle_span(self.cursor.span(body_span.lo()), false) {
// Print spacing if necessary. Updates cursor.
} else {
if let Some(cmnt) = self.peek_comment_before(body_span.lo()) {
if cmnt.style.is_mixed() {
// These shouldn't update the cursor, as we've already dealt with it above
self.space();
self.s.offset(-self.ind);
self.print_comments(body_span.lo(), CommentConfig::skip_ws());
} else {
self.zerobreak();
self.s.offset(-self.ind);
self.print_comments(body_span.lo(), CommentConfig::skip_ws());
self.s.offset(-self.ind);
}
} else {
// If there are no modifiers, overrides, nor returns never break
if header.modifiers.is_empty()
&& header.override_.is_none()
&& returns.as_ref().is_none_or(|r| r.is_empty())
&& (header.visibility().is_none() || body.is_empty())
{
self.nbsp();
} else {
self.space();
self.s.offset(-self.ind);
}
}
self.cursor.advance_to(body_span.lo(), true);
}
self.print_word("{");
self.end();
if attrib_box {
self.end();
}
self.print_block_without_braces(body, body_span.hi(), Some(self.ind));
if self.cursor.enabled || self.cursor.pos < body_span.hi() {
self.print_word("}");
self.cursor.advance_to(body_span.hi(), true);
}
} else {
self.print_comments(body_span.lo(), CommentConfig::skip_ws().mixed_prev_space());
self.end();
if attrib_box {
self.end();
}
self.neverbreak();
self.print_word(";");
}
if let Some(cmnt) = self.peek_trailing_comment(body_span.hi(), None) {
if cmnt.is_doc {
// trailing doc comments after the fn body are isolated
// these shouldn't update the cursor, as this is our own formatting
self.hardbreak();
self.hardbreak();
}
self.print_trailing_comment(body_span.hi(), None);
}
}
fn print_fn_attribute(
&mut self,
span: Span,
map: &mut AttributeCommentMap,
print_fn: &mut dyn FnMut(&mut Self),
) {
match map.remove(&span.lo()) {
Some((pre_cmnts, inner_cmnts, post_cmnts)) => {
// Print preceding comments.
for cmnt in pre_cmnts {
let Some(cmnt) = self.handle_comment(cmnt, false) else {
continue;
};
self.print_comment(cmnt, CommentConfig::default());
}
// Push the inner comments back to the queue, so that they are printed in their
// intended place.
for cmnt in inner_cmnts.into_iter().rev() {
self.comments.push_front(cmnt);
}
let mut enabled = false;
if !self.handle_span(span, false) {
if !self.is_bol_or_only_ind() {
self.space();
}
self.ibox(0);
print_fn(self);
self.cursor.advance_to(span.hi(), true);
enabled = true;
}
// Print subsequent comments.
for cmnt in post_cmnts {
let Some(cmnt) = self.handle_comment(cmnt, false) else {
continue;
};
self.print_comment(cmnt, CommentConfig::default().mixed_prev_space());
}
if enabled {
self.end();
}
}
// Fallback for attributes not in the map (should never happen)
None => {
if !self.is_bol_or_only_ind() {
self.space();
}
print_fn(self);
self.cursor.advance_to(span.hi(), true);
}
}
}
fn is_modifier_a_base_contract(
&self,
kind: ast::FunctionKind,
modifier: &'ast ast::Modifier<'ast>,
) -> bool {
// Add `()` in functions when the modifier is a base contract.
// HACK: heuristics:
// 1. exactly matches the name of a base contract as declared in the `contract is`;
// this does not account for inheritance;
let is_contract_base = self.contract.is_some_and(|contract| {
contract
.bases
.iter()
.any(|contract_base| contract_base.name.to_string() == modifier.name.to_string())
});
// 2. assume that title case names in constructors are bases.
// LEGACY: constructors used to also be `function NameOfContract...`; not checked.
let is_constructor = matches!(kind, ast::FunctionKind::Constructor);
// LEGACY: we are checking the beginning of the path, not the last segment.
is_contract_base
|| (is_constructor
&& modifier.name.first().name.as_str().starts_with(char::is_uppercase))
}
fn print_error(&mut self, err: &'ast ast::ItemError<'ast>) {
let ast::ItemError { name, parameters } = err;
self.word("error ");
self.print_ident(name);
self.print_parameter_list(
parameters,
parameters.span,
if self.config.prefer_compact.errors() {
ListFormat::compact()
} else {
ListFormat::consistent()
},
);
self.word(";");
}
fn print_event(&mut self, event: &'ast ast::ItemEvent<'ast>) {
let ast::ItemEvent { name, parameters, anonymous } = event;
self.word("event ");
self.print_ident(name);
self.print_parameter_list(
parameters,
parameters.span,
if self.config.prefer_compact.events() {
ListFormat::compact().break_cmnts()
} else {
ListFormat::consistent().break_cmnts()
},
);
if *anonymous {
self.word(" anonymous");
}
self.word(";");
}
fn print_var_def(&mut self, var: &'ast ast::VariableDefinition<'ast>) {
self.print_var(var, true);
self.word(";");
}
/// Prints the RHS of an assignment or variable initializer.
fn print_assign_rhs(
&mut self,
rhs: &'ast ast::Expr<'ast>,
lhs_size: usize,
space_left: usize,
ty: Option<&ast::TypeKind<'ast>>,
cache: bool,
) {
// Check if the total expression overflows but the RHS would fit alone on a new line.
// This helps keep the RHS together on a single line when possible.
let rhs_size = self.estimate_size(rhs.span);
let overflows = lhs_size + rhs_size >= space_left;
let fits_alone = rhs_size + self.config.tab_width < space_left;
let fits_alone_no_cmnts =
fits_alone && !self.has_comment_between(rhs.span.lo(), rhs.span.hi());
let force_break = overflows && fits_alone_no_cmnts;
// Set up precall size tracking
if lhs_size <= space_left {
self.neverbreak();
self.call_stack.add_precall(lhs_size + 1);
} else {
self.call_stack.add_precall(space_left + self.config.tab_width);
}
// Handle comments before the RHS expression
if let Some(cmnt) = self.peek_comment_before(rhs.span.lo())
&& self.inline_config.is_disabled(cmnt.span)
{
self.print_sep(Separator::Nbsp);
}
if self
.print_comments(
rhs.span.lo(),
CommentConfig::skip_ws().mixed_no_break().mixed_prev_space(),
)
.is_some_and(|cmnt| cmnt.is_trailing())
{
self.break_offset_if_not_bol(SIZE_INFINITY as usize, self.ind, false);
}
// Match on expression kind to determine formatting strategy
match &rhs.kind {
ast::ExprKind::Lit(lit, ..) if lit.is_str_concatenation() => {
// String concatenations stay on the same line with nbsp
self.print_sep(Separator::Nbsp);
self.neverbreak();
self.s.ibox(self.ind);
self.print_expr(rhs);
self.end();
}
ast::ExprKind::Lit(..) if ty.is_none() && !fits_alone => {
// Long string in assign expr goes on its own line
self.print_sep(Separator::Space);
self.s.offset(self.ind);
self.print_expr(rhs);
}
ast::ExprKind::Binary(lhs, op, _) => {
let print_inline = |this: &mut Self| {
this.print_sep(Separator::Nbsp);
this.neverbreak();
this.print_expr(rhs);
};
let print_with_break = |this: &mut Self, force_break: bool| {
if !this.is_bol_or_only_ind() {
if force_break {
this.print_sep(Separator::Hardbreak);
} else {
this.print_sep(Separator::Space);
}
}
this.s.offset(this.ind);
this.s.ibox(this.ind);
this.print_expr(rhs);
this.end();
};
// Binary expressions: check if we need to break and indent
if force_break {
print_with_break(self, true);
} else if self.estimate_lhs_size(rhs, op) + lhs_size > space_left {
if has_complex_successor(&rhs.kind, true)
&& get_callee_head_size(lhs) + lhs_size <= space_left
{
// Keep complex exprs (where callee fits) inline, as they will have breaks
if matches!(lhs.kind, ast::ExprKind::Call(..)) {
self.s.ibox(-self.ind);
print_inline(self);
self.end();
} else {
print_inline(self);
}
} else {
print_with_break(self, false);
}
}
// Otherwise, if expr fits, ensure no breaks
else {
print_inline(self);
}
}
_ => {
// General case: handle calls, complex successors, and other expressions
let callee_doesnt_fit = if let ast::ExprKind::Call(call_expr, ..) = &rhs.kind {
let callee_size = get_callee_head_size(call_expr);
callee_size + lhs_size > space_left
&& callee_size + self.config.tab_width < space_left
} else {
false
};
if (lhs_size + 1 >= space_left && !is_call_chain(&rhs.kind, false))
|| callee_doesnt_fit
{
self.s.ibox(self.ind);
} else {
self.s.ibox(0);
};
if has_complex_successor(&rhs.kind, true)
&& !matches!(&rhs.kind, ast::ExprKind::Member(..))
{
// delegate breakpoints to `self.commasep(..)` for complex successors
if !self.is_bol_or_only_ind() {
let needs_offset = !callee_doesnt_fit
&& rhs_size + lhs_size + 1 >= space_left
&& fits_alone_no_cmnts;
let separator = if callee_doesnt_fit || needs_offset {
Separator::Space
} else {
Separator::Nbsp
};
self.print_sep(separator);
if needs_offset {
self.s.offset(self.ind);
}
}
} else {
if !self.is_bol_or_only_ind() {
self.print_sep_unhandled(Separator::Space);
}
// apply type-dependent indentation if type info is available
if let Some(ty) = ty
&& matches!(ty, ast::TypeKind::Elementary(..) | ast::TypeKind::Mapping(..))
{
self.s.offset(self.ind);
}
}
self.print_expr(rhs);
self.end();
}
}
self.var_init = cache;
self.call_stack.reset_precall();
}
fn print_var(&mut self, var: &'ast ast::VariableDefinition<'ast>, is_var_def: bool) {
let ast::VariableDefinition {
span,
ty,
visibility,
mutability,
data_location,
override_,
indexed,
name,
initializer,
} = var;
if self.handle_span(*span, false) {
return;
}
// NOTE(rusowsky): this is hacky but necessary to properly estimate if we figure out if we
// have double breaks (which should have double indentation) or not.
// Alternatively, we could achieve the same behavior with a new box group that supports
// "continuation" which would only increase indentation if its parent box broke.
let init_space_left = self.space_left();
let mut pre_init_size = self.estimate_size(ty.span);
// Non-elementary types use commasep which has its own padding.
self.s.ibox(0);
if override_.is_some() {
self.s.cbox(self.ind);
} else {
self.s.ibox(self.ind);
}
self.print_ty(ty);
self.print_attribute(visibility.map(|v| v.to_str()), is_var_def, &mut pre_init_size);
self.print_attribute(mutability.map(|m| m.to_str()), is_var_def, &mut pre_init_size);
self.print_attribute(data_location.map(|d| d.to_str()), is_var_def, &mut pre_init_size);
if let Some(override_) = override_ {
if self
.print_comments(override_.span.lo(), CommentConfig::skip_ws().mixed_prev_space())
.is_none()
{
self.print_sep(Separator::SpaceOrNbsp(is_var_def));
}
self.ibox(0);
self.print_override(override_);
pre_init_size += self.estimate_size(override_.span) + 1;
}
if *indexed {
self.print_attribute(indexed.then_some("indexed"), is_var_def, &mut pre_init_size);
}
if let Some(ident) = name {
self.print_sep(Separator::SpaceOrNbsp(is_var_def && override_.is_none()));
self.print_comments(
ident.span.lo(),
CommentConfig::skip_ws().mixed_no_break().mixed_post_nbsp(),
);
self.print_ident(ident);
pre_init_size += self.estimate_size(ident.span) + 1;
}
if let Some(init) = initializer {
let cache = self.var_init;
self.var_init = true;
pre_init_size += 2;
self.print_word(" =");
if override_.is_some() {
self.end();
}
self.end();
self.print_assign_rhs(init, pre_init_size, init_space_left, Some(&ty.kind), cache);
} else {
self.end();
}
self.end();
}