forked from hyperledger-solang/solang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter.rs
3942 lines (3579 loc) · 145 KB
/
formatter.rs
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
// SPDX-License-Identifier: Apache-2.0
//! A Solidity formatter
use crate::{
buffer::*,
chunk::*,
comments::{
CommentPosition, CommentState, CommentStringExt, CommentType, CommentWithMetadata, Comments,
},
config::{
FormatterConfig, HexUnderscore, IntTypes, MultilineFuncHeaderStyle, SingleLineBlockStyle,
},
helpers::import_path_string,
macros::*,
solang_ext::{pt::*, *},
string::{QuoteState, QuotedStringExt},
visit::{Visitable, Visitor},
InlineConfig,
};
use alloy_primitives::Address;
use itertools::{Either, Itertools};
use solang_parser::pt::{PragmaDirective, StorageType, VersionComparator};
use std::{fmt::Write, str::FromStr};
use thiserror::Error;
type Result<T, E = FormatterError> = std::result::Result<T, E>;
/// A custom Error thrown by the Formatter
#[derive(Debug, Error)]
pub enum FormatterError {
/// Error thrown by `std::fmt::Write` interfaces
#[error(transparent)]
Fmt(#[from] std::fmt::Error),
/// Encountered invalid parse tree item.
#[error("Encountered invalid parse tree item at {0:?}")]
InvalidParsedItem(Loc),
/// All other errors
#[error(transparent)]
Custom(Box<dyn std::error::Error + Send + Sync>),
}
impl FormatterError {
fn fmt() -> Self {
Self::Fmt(std::fmt::Error)
}
fn custom(err: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::Custom(Box::new(err))
}
}
#[allow(unused_macros)]
macro_rules! format_err {
($msg:literal $(,)?) => {
$crate::formatter::FormatterError::custom($msg.to_string())
};
($err:expr $(,)?) => {
$crate::formatter::FormatterError::custom($err)
};
($fmt:expr, $($arg:tt)*) => {
$crate::formatter::FormatterError::custom(format!($fmt, $($arg)*))
};
}
#[allow(unused_macros)]
macro_rules! bail {
($msg:literal $(,)?) => {
return Err($crate::formatter::format_err!($msg))
};
($err:expr $(,)?) => {
return Err($err)
};
($fmt:expr, $($arg:tt)*) => {
return Err($crate::formatter::format_err!($fmt, $(arg)*))
};
}
// TODO: store context entities as references without copying
/// Current context of the Formatter (e.g. inside Contract or Function definition)
#[derive(Debug, Default)]
struct Context {
contract: Option<ContractDefinition>,
function: Option<FunctionDefinition>,
if_stmt_single_line: Option<bool>,
}
impl Context {
/// Returns true if the current function context is the constructor
pub(crate) fn is_constructor_function(&self) -> bool {
self.function
.as_ref()
.map_or(false, |f| matches!(f.ty, FunctionTy::Constructor))
}
}
/// A Solidity formatter
#[derive(Debug)]
pub struct Formatter<'a, W> {
buf: FormatBuffer<W>,
source: &'a str,
config: FormatterConfig,
temp_bufs: Vec<FormatBuffer<String>>,
context: Context,
comments: Comments,
inline_config: InlineConfig,
}
impl<'a, W: Write> Formatter<'a, W> {
pub fn new(
w: W,
source: &'a str,
comments: Comments,
inline_config: InlineConfig,
config: FormatterConfig,
) -> Self {
Self {
buf: FormatBuffer::new(w, config.tab_width),
source,
config,
temp_bufs: Vec::new(),
context: Context::default(),
comments,
inline_config,
}
}
/// Get the Write interface of the current temp buffer or the underlying Write
fn buf(&mut self) -> &mut dyn Write {
match &mut self.temp_bufs[..] {
[] => &mut self.buf as &mut dyn Write,
[.., buf] => buf as &mut dyn Write,
}
}
/// Casts the current writer `w` as a `String` reference. Should only be used for debugging.
#[allow(dead_code)]
unsafe fn buf_contents(&self) -> &String {
*(&self.buf.w as *const W as *const &mut String)
}
/// Casts the current `W` writer or the current temp buffer as a `String` reference.
/// Should only be used for debugging.
#[allow(dead_code)]
unsafe fn temp_buf_contents(&self) -> &String {
match &self.temp_bufs[..] {
[] => self.buf_contents(),
[.., buf] => &buf.w,
}
}
buf_fn! { fn indent(&mut self, delta: usize) }
buf_fn! { fn dedent(&mut self, delta: usize) }
buf_fn! { fn start_group(&mut self) }
buf_fn! { fn end_group(&mut self) }
buf_fn! { fn create_temp_buf(&self) -> FormatBuffer<String> }
buf_fn! { fn restrict_to_single_line(&mut self, restricted: bool) }
buf_fn! { fn current_line_len(&self) -> usize }
buf_fn! { fn total_indent_len(&self) -> usize }
buf_fn! { fn is_beginning_of_line(&self) -> bool }
buf_fn! { fn last_char(&self) -> Option<char> }
buf_fn! { fn last_indent_group_skipped(&self) -> bool }
buf_fn! { fn set_last_indent_group_skipped(&mut self, skip: bool) }
buf_fn! { fn write_raw(&mut self, s: impl AsRef<str>) -> std::fmt::Result }
/// Do the callback within the context of a temp buffer
fn with_temp_buf(
&mut self,
mut fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<FormatBuffer<String>> {
self.temp_bufs.push(self.create_temp_buf());
let res = fun(self);
let out = self.temp_bufs.pop().unwrap();
res?;
Ok(out)
}
/// Does the next written character require whitespace before
fn next_char_needs_space(&self, next_char: char) -> bool {
if self.is_beginning_of_line() {
return false;
}
let last_char = if let Some(last_char) = self.last_char() {
last_char
} else {
return false;
};
if last_char.is_whitespace() || next_char.is_whitespace() {
return false;
}
match last_char {
'{' => match next_char {
'{' | '[' | '(' => false,
'/' => true,
_ => self.config.bracket_spacing,
},
'(' | '.' | '[' => matches!(next_char, '/'),
'/' => true,
_ => match next_char {
'}' => self.config.bracket_spacing,
')' | ',' | '.' | ';' | ']' => false,
_ => true,
},
}
}
/// Is length of the `text` with respect to already written line <= `config.line_length`
fn will_it_fit(&self, text: impl AsRef<str>) -> bool {
let text = text.as_ref();
if text.is_empty() {
return true;
}
if text.contains('\n') {
return false;
}
let space: usize = self
.next_char_needs_space(text.chars().next().unwrap())
.into();
self.config.line_length
>= self
.total_indent_len()
.saturating_add(self.current_line_len())
.saturating_add(text.chars().count() + space)
}
/// Write empty brackets with respect to `config.bracket_spacing` setting:
/// `"{ }"` if `true`, `"{}"` if `false`
fn write_empty_brackets(&mut self) -> Result<()> {
let brackets = if self.config.bracket_spacing {
"{ }"
} else {
"{}"
};
write_chunk!(self, "{brackets}")?;
Ok(())
}
/// Write semicolon to the buffer
fn write_semicolon(&mut self) -> Result<()> {
write!(self.buf(), ";")?;
Ok(())
}
/// Write whitespace separator to the buffer
/// `"\n"` if `multiline` is `true`, `" "` if `false`
fn write_whitespace_separator(&mut self, multiline: bool) -> Result<()> {
if !self.is_beginning_of_line() {
write!(self.buf(), "{}", if multiline { "\n" } else { " " })?;
}
Ok(())
}
/// Write new line with preserved `last_indent_group_skipped` flag
fn write_preserved_line(&mut self) -> Result<()> {
let last_indent_group_skipped = self.last_indent_group_skipped();
writeln!(self.buf())?;
self.set_last_indent_group_skipped(last_indent_group_skipped);
Ok(())
}
/// Returns number of blank lines in source between two byte indexes
fn blank_lines(&self, start: usize, end: usize) -> usize {
// because of sorting import statements, start can be greater than end
if start > end {
return 0;
}
self.source[start..end]
.trim_comments()
.matches('\n')
.count()
}
/// Get the byte offset of the next line
fn find_next_line(&self, byte_offset: usize) -> Option<usize> {
let mut iter = self.source[byte_offset..].char_indices();
while let Some((_, ch)) = iter.next() {
match ch {
'\n' => return iter.next().map(|(idx, _)| byte_offset + idx),
'\r' => {
return iter.next().and_then(|(idx, ch)| match ch {
'\n' => iter.next().map(|(idx, _)| byte_offset + idx),
_ => Some(byte_offset + idx),
})
}
_ => {}
}
}
None
}
/// Find the next instance of the character in source excluding comments
fn find_next_in_src(&self, byte_offset: usize, needle: char) -> Option<usize> {
self.source[byte_offset..]
.comment_state_char_indices()
.position(|(state, _, ch)| needle == ch && state == CommentState::None)
.map(|p| byte_offset + p)
}
/// Find the start of the next instance of a slice in source
fn find_next_str_in_src(&self, byte_offset: usize, needle: &str) -> Option<usize> {
let subset = &self.source[byte_offset..];
needle.chars().next().and_then(|first_char| {
subset
.comment_state_char_indices()
.position(|(state, idx, ch)| {
first_char == ch
&& state == CommentState::None
&& idx + needle.len() <= subset.len()
&& subset[idx..idx + needle.len()] == *needle
})
.map(|p| byte_offset + p)
})
}
/// Extends the location to the next instance of a character. Returns true if the loc was
/// extended
fn extend_loc_until(&self, loc: &mut Loc, needle: char) -> bool {
if let Some(end) = self
.find_next_in_src(loc.end(), needle)
.map(|offset| offset + 1)
{
*loc = loc.with_end(end);
true
} else {
false
}
}
/// Return the flag whether the attempt should be made
/// to write the block on a single line.
/// If the block style is configured to [SingleLineBlockStyle::Preserve],
/// lookup whether there was a newline introduced in `[start_from, end_at]` range
/// where `end_at` is the start of the block.
fn should_attempt_block_single_line(
&mut self,
stmt: &mut Statement,
start_from: usize,
) -> bool {
match self.config.single_line_statement_blocks {
SingleLineBlockStyle::Single => true,
SingleLineBlockStyle::Multi => false,
SingleLineBlockStyle::Preserve => {
let end_at = match stmt {
Statement::Block { statements, .. } if !statements.is_empty() => {
statements.first().as_ref().unwrap().loc().start()
}
Statement::Expression(loc, _) => loc.start(),
_ => stmt.loc().start(),
};
self.find_next_line(start_from)
.map_or(false, |loc| loc >= end_at)
}
}
}
/// Create a chunk given a string and the location information
fn chunk_at(
&mut self,
byte_offset: usize,
next_byte_offset: Option<usize>,
needs_space: Option<bool>,
content: impl std::fmt::Display,
) -> Chunk {
Chunk {
postfixes_before: self.comments.remove_postfixes_before(byte_offset),
prefixes: self.comments.remove_prefixes_before(byte_offset),
content: content.to_string(),
postfixes: next_byte_offset
.map(|byte_offset| self.comments.remove_postfixes_before(byte_offset))
.unwrap_or_default(),
needs_space,
}
}
/// Create a chunk given a callback
fn chunked(
&mut self,
byte_offset: usize,
next_byte_offset: Option<usize>,
fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<Chunk> {
let postfixes_before = self.comments.remove_postfixes_before(byte_offset);
let prefixes = self.comments.remove_prefixes_before(byte_offset);
let content = self.with_temp_buf(fun)?.w;
let postfixes = next_byte_offset
.map(|byte_offset| self.comments.remove_postfixes_before(byte_offset))
.unwrap_or_default();
Ok(Chunk {
postfixes_before,
prefixes,
content,
postfixes,
needs_space: None,
})
}
/// Create a chunk given a [Visitable] item
fn visit_to_chunk(
&mut self,
byte_offset: usize,
next_byte_offset: Option<usize>,
visitable: &mut impl Visitable,
) -> Result<Chunk> {
self.chunked(byte_offset, next_byte_offset, |fmt| {
visitable.visit(fmt)?;
Ok(())
})
}
/// Transform [Visitable] items to the list of chunks
fn items_to_chunks<'b>(
&mut self,
next_byte_offset: Option<usize>,
items: impl Iterator<Item = (Loc, &'b mut (impl Visitable + 'b))> + 'b,
) -> Result<Vec<Chunk>> {
let mut items = items.peekable();
let mut out = Vec::with_capacity(items.size_hint().1.unwrap_or(0));
while let Some((loc, item)) = items.next() {
let chunk_next_byte_offset = items
.peek()
.map(|(loc, _)| loc.start())
.or(next_byte_offset);
out.push(self.visit_to_chunk(loc.start(), chunk_next_byte_offset, item)?);
}
Ok(out)
}
/// Transform [Visitable] items to a list of chunks and then sort those chunks.
fn items_to_chunks_sorted<'b>(
&mut self,
next_byte_offset: Option<usize>,
items: impl Iterator<Item = &'b mut (impl Visitable + CodeLocation + Ord + 'b)> + 'b,
) -> Result<Vec<Chunk>> {
let mut items = items.peekable();
let mut out = Vec::with_capacity(items.size_hint().1.unwrap_or(0));
while let Some(item) = items.next() {
let chunk_next_byte_offset = items
.peek()
.map(|next| next.loc().start())
.or(next_byte_offset);
let chunk = self.visit_to_chunk(item.loc().start(), chunk_next_byte_offset, item)?;
out.push((item, chunk));
}
out.sort_by(|(a, _), (b, _)| a.cmp(b));
Ok(out.into_iter().map(|(_, c)| c).collect())
}
/// Write a comment to the buffer formatted.
/// WARNING: This may introduce a newline if the comment is a Line comment
/// or if the comment are wrapped
fn write_comment(&mut self, comment: &CommentWithMetadata, is_first: bool) -> Result<()> {
if self.inline_config.is_disabled(comment.loc) {
return self.write_raw_comment(comment);
}
match comment.position {
CommentPosition::Prefix => self.write_prefix_comment(comment, is_first),
CommentPosition::Postfix => self.write_postfix_comment(comment),
}
}
/// Write a comment with position [CommentPosition::Prefix]
fn write_prefix_comment(
&mut self,
comment: &CommentWithMetadata,
is_first: bool,
) -> Result<()> {
if !self.is_beginning_of_line() {
self.write_preserved_line()?;
}
if !is_first && comment.has_newline_before {
self.write_preserved_line()?;
}
if matches!(comment.ty, CommentType::DocBlock) {
let mut lines = comment.contents().trim().lines();
writeln!(self.buf(), "{}", comment.start_token())?;
lines.try_for_each(|l| self.write_doc_block_line(comment, l))?;
write!(self.buf(), " {}", comment.end_token().unwrap())?;
self.write_preserved_line()?;
return Ok(());
}
write!(self.buf(), "{}", comment.start_token())?;
let mut wrapped = false;
let contents = comment.contents();
let mut lines = contents.lines().peekable();
while let Some(line) = lines.next() {
wrapped |= self.write_comment_line(comment, line)?;
if lines.peek().is_some() {
self.write_preserved_line()?;
}
}
if let Some(end) = comment.end_token() {
// Check if the end token in the original comment was on the separate line
if !wrapped && comment.comment.lines().count() > contents.lines().count() {
self.write_preserved_line()?;
}
write!(self.buf(), "{end}")?;
}
if self.find_next_line(comment.loc.end()).is_some() {
self.write_preserved_line()?;
}
Ok(())
}
/// Write a comment with position [CommentPosition::Postfix]
fn write_postfix_comment(&mut self, comment: &CommentWithMetadata) -> Result<()> {
let indented = self.is_beginning_of_line();
self.indented_if(indented, 1, |fmt| {
if !indented && fmt.next_char_needs_space('/') {
fmt.write_whitespace_separator(false)?;
}
write!(fmt.buf(), "{}", comment.start_token())?;
let start_token_pos = fmt.current_line_len();
let mut lines = comment.contents().lines().peekable();
fmt.grouped(|fmt| {
while let Some(line) = lines.next() {
fmt.write_comment_line(comment, line)?;
if lines.peek().is_some() {
fmt.write_whitespace_separator(true)?;
}
}
Ok(())
})?;
if let Some(end) = comment.end_token() {
// If comment is not multiline, end token has to be aligned with the start
if fmt.is_beginning_of_line() {
write!(fmt.buf(), "{}{end}", " ".repeat(start_token_pos))?;
} else {
write!(fmt.buf(), "{end}")?;
}
}
if comment.is_line() {
fmt.write_whitespace_separator(true)?;
}
Ok(())
})
}
/// Write the line of a doc block comment line
fn write_doc_block_line(&mut self, comment: &CommentWithMetadata, line: &str) -> Result<()> {
if line.trim().starts_with('*') {
let line = line.trim().trim_start_matches('*');
let needs_space = line.chars().next().map_or(false, |ch| !ch.is_whitespace());
write!(self.buf(), " *{}", if needs_space { " " } else { "" })?;
self.write_comment_line(comment, line)?;
self.write_whitespace_separator(true)?;
return Ok(());
}
let indent_whitespace_count = line
.char_indices()
.take_while(|(idx, ch)| ch.is_whitespace() && *idx <= self.buf.current_indent_len())
.count();
let to_skip = indent_whitespace_count - indent_whitespace_count % self.config.tab_width;
write!(self.buf(), " *")?;
let content = &line[to_skip..];
if !content.trim().is_empty() {
write!(self.buf(), " ")?;
self.write_comment_line(comment, &line[to_skip..])?;
}
self.write_whitespace_separator(true)?;
Ok(())
}
/// Write a comment line that might potentially overflow the maximum line length
/// and, if configured, will be wrapped to the next line.
fn write_comment_line(&mut self, comment: &CommentWithMetadata, line: &str) -> Result<bool> {
if self.will_it_fit(line) || !self.config.wrap_comments {
let start_with_ws = line
.chars()
.next()
.map(|ch| ch.is_whitespace())
.unwrap_or_default();
if !self.is_beginning_of_line() || !start_with_ws {
write!(self.buf(), "{line}")?;
return Ok(false);
}
// if this is the beginning of the line,
// the comment should start with at least an indent
let indent = self.buf.current_indent_len();
let mut chars = line
.char_indices()
.skip_while(|(idx, ch)| ch.is_whitespace() && *idx < indent)
.map(|(_, ch)| ch);
let padded = format!("{}{}", " ".repeat(indent), chars.join(""));
self.write_raw(padded)?;
return Ok(false);
}
let mut words = line.split(' ').peekable();
while let Some(word) = words.next() {
if self.is_beginning_of_line() {
write!(self.buf(), "{}", word.trim_start())?;
} else {
self.write_raw(word)?;
}
if let Some(next) = words.peek() {
if !word.is_empty() && !self.will_it_fit(next) {
// the next word doesn't fit on this line,
// write remaining words on the next
self.write_whitespace_separator(true)?;
// write newline wrap token
write!(self.buf(), "{}", comment.wrap_token())?;
self.write_comment_line(comment, &words.join(" "))?;
return Ok(true);
}
self.write_whitespace_separator(false)?;
}
}
Ok(false)
}
/// Write a raw comment. This is like [`write_comment`](Self::write_comment) but won't do any
/// formatting or worry about whitespace behind the comment.
fn write_raw_comment(&mut self, comment: &CommentWithMetadata) -> Result<()> {
self.write_raw(&comment.comment)?;
if comment.is_line() {
self.write_preserved_line()?;
}
Ok(())
}
// TODO handle whitespace between comments for disabled sections
/// Write multiple comments
fn write_comments<'b>(
&mut self,
comments: impl IntoIterator<Item = &'b CommentWithMetadata>,
) -> Result<()> {
let mut comments = comments.into_iter().peekable();
let mut last_byte_written = match comments.peek() {
Some(comment) => comment.loc.start(),
None => return Ok(()),
};
let mut is_first = true;
for comment in comments {
let unwritten_whitespace_loc = Loc::File(
comment.loc.file_no(),
last_byte_written,
comment.loc.start(),
);
if self.inline_config.is_disabled(unwritten_whitespace_loc) {
self.write_raw(&self.source[unwritten_whitespace_loc.range()])?;
self.write_raw_comment(comment)?;
last_byte_written = if comment.is_line() {
self.find_next_line(comment.loc.end())
.unwrap_or_else(|| comment.loc.end())
} else {
comment.loc.end()
};
} else {
self.write_comment(comment, is_first)?;
}
is_first = false;
}
Ok(())
}
/// Write a postfix comments before a given location
fn write_postfix_comments_before(&mut self, byte_end: usize) -> Result<()> {
let comments = self.comments.remove_postfixes_before(byte_end);
self.write_comments(&comments)
}
/// Write all prefix comments before a given location
fn write_prefix_comments_before(&mut self, byte_end: usize) -> Result<()> {
let comments = self.comments.remove_prefixes_before(byte_end);
self.write_comments(&comments)
}
/// Check if a chunk will fit on the current line
fn will_chunk_fit(&mut self, format_string: &str, chunk: &Chunk) -> Result<bool> {
if let Some(chunk_str) = self.simulate_to_single_line(|fmt| fmt.write_chunk(chunk))? {
Ok(self.will_it_fit(format_string.replacen("{}", &chunk_str, 1)))
} else {
Ok(false)
}
}
/// Check if a separated list of chunks will fit on the current line
fn are_chunks_separated_multiline<'b>(
&mut self,
format_string: &str,
items: impl IntoIterator<Item = &'b Chunk>,
separator: &str,
) -> Result<bool> {
let items = items.into_iter().collect_vec();
if let Some(chunks) = self.simulate_to_single_line(|fmt| {
fmt.write_chunks_separated(items.iter().copied(), separator, false)
})? {
Ok(!self.will_it_fit(format_string.replacen("{}", &chunks, 1)))
} else {
Ok(true)
}
}
/// Write the chunk and any surrounding comments into the buffer
/// This will automatically add whitespace before the chunk given the rule set in
/// `next_char_needs_space`. If the chunk does not fit on the current line it will be put on
/// to the next line
fn write_chunk(&mut self, chunk: &Chunk) -> Result<()> {
// handle comments before chunk
self.write_comments(&chunk.postfixes_before)?;
self.write_comments(&chunk.prefixes)?;
// trim chunk start
let content = if chunk.content.starts_with('\n') {
let mut chunk = chunk.content.trim_start().to_string();
chunk.insert(0, '\n');
chunk
} else if chunk.content.starts_with(' ') {
let mut chunk = chunk.content.trim_start().to_string();
chunk.insert(0, ' ');
chunk
} else {
chunk.content.clone()
};
if !content.is_empty() {
// add whitespace if necessary
let needs_space = chunk
.needs_space
.unwrap_or_else(|| self.next_char_needs_space(content.chars().next().unwrap()));
if needs_space {
if self.will_it_fit(&content) {
write!(self.buf(), " ")?;
} else {
writeln!(self.buf())?;
}
}
// write chunk
write!(self.buf(), "{content}")?;
}
// write any postfix comments
self.write_comments(&chunk.postfixes)?;
Ok(())
}
/// Write chunks separated by a separator. If `multiline`, each chunk will be written to a
/// separate line
fn write_chunks_separated<'b>(
&mut self,
chunks: impl IntoIterator<Item = &'b Chunk>,
separator: &str,
multiline: bool,
) -> Result<()> {
let mut chunks = chunks.into_iter().peekable();
while let Some(chunk) = chunks.next() {
let mut chunk = chunk.clone();
// handle postfixes before and add newline if necessary
self.write_comments(&std::mem::take(&mut chunk.postfixes_before))?;
if multiline && !self.is_beginning_of_line() {
writeln!(self.buf())?;
}
// remove postfixes so we can add separator between
let postfixes = std::mem::take(&mut chunk.postfixes);
self.write_chunk(&chunk)?;
// add separator
if chunks.peek().is_some() {
write!(self.buf(), "{separator}")?;
self.write_comments(&postfixes)?;
if multiline && !self.is_beginning_of_line() {
writeln!(self.buf())?;
}
} else {
self.write_comments(&postfixes)?;
}
}
Ok(())
}
/// Apply the callback indented by the indent size
fn indented(&mut self, delta: usize, fun: impl FnMut(&mut Self) -> Result<()>) -> Result<()> {
self.indented_if(true, delta, fun)
}
/// Apply the callback indented by the indent size if the condition is true
fn indented_if(
&mut self,
condition: bool,
delta: usize,
mut fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<()> {
if condition {
self.indent(delta);
}
let res = fun(self);
if condition {
self.dedent(delta);
}
res?;
Ok(())
}
/// Apply the callback into an indent group. The first line of the indent group is not
/// indented but lines thereafter are
fn grouped(&mut self, mut fun: impl FnMut(&mut Self) -> Result<()>) -> Result<bool> {
self.start_group();
let res = fun(self);
let indented = !self.last_indent_group_skipped();
self.end_group();
res?;
Ok(indented)
}
/// Add a function context around a procedure and revert the context at the end of the procedure
/// regardless of the response
fn with_function_context(
&mut self,
context: FunctionDefinition,
mut fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<()> {
self.context.function = Some(context);
let res = fun(self);
self.context.function = None;
res
}
/// Add a contract context around a procedure and revert the context at the end of the procedure
/// regardless of the response
fn with_contract_context(
&mut self,
context: ContractDefinition,
mut fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<()> {
self.context.contract = Some(context);
let res = fun(self);
self.context.contract = None;
res
}
/// Create a transaction. The result of the transaction is not applied to the buffer unless
/// `Transacton::commit` is called
fn transact<'b>(
&'b mut self,
fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<Transaction<'b, 'a, W>> {
Transaction::new(self, fun)
}
/// Do the callback and return the result on the buffer as a string
fn simulate_to_string(&mut self, fun: impl FnMut(&mut Self) -> Result<()>) -> Result<String> {
Ok(self.transact(fun)?.buffer)
}
/// Turn a chunk and its surrounding comments into a string
fn chunk_to_string(&mut self, chunk: &Chunk) -> Result<String> {
self.simulate_to_string(|fmt| fmt.write_chunk(chunk))
}
/// Try to create a string based on a callback. If the string does not fit on a single line
/// this will return `None`
fn simulate_to_single_line(
&mut self,
mut fun: impl FnMut(&mut Self) -> Result<()>,
) -> Result<Option<String>> {
let mut single_line = false;
let tx = self.transact(|fmt| {
fmt.restrict_to_single_line(true);
single_line = match fun(fmt) {
Ok(()) => true,
Err(FormatterError::Fmt(_)) => false,
Err(err) => bail!(err),
};
Ok(())
})?;
Ok(if single_line && tx.will_it_fit(&tx.buffer) {
Some(tx.buffer)
} else {
None
})
}
/// Try to apply a callback to a single line. If the callback cannot be applied to a single
/// line the callback will not be applied to the buffer and `false` will be returned. Otherwise
/// `true` will be returned
fn try_on_single_line(&mut self, mut fun: impl FnMut(&mut Self) -> Result<()>) -> Result<bool> {
let mut single_line = false;
let tx = self.transact(|fmt| {
fmt.restrict_to_single_line(true);
single_line = match fun(fmt) {
Ok(()) => true,
Err(FormatterError::Fmt(_)) => false,
Err(err) => bail!(err),
};
Ok(())
})?;
Ok(if single_line && tx.will_it_fit(&tx.buffer) {
tx.commit()?;
true
} else {
false
})
}
/// Surrounds a callback with parentheses. The callback will try to be applied to a single
/// line. If the callback cannot be applied to a single line the callback will applied to the
/// nextline indented. The callback receives a `multiline` hint as the second argument which
/// receives `true` in the latter case
fn surrounded(
&mut self,
first: SurroundingChunk,
last: SurroundingChunk,
mut fun: impl FnMut(&mut Self, bool) -> Result<()>,
) -> Result<()> {
let first_chunk = self.chunk_at(
first.loc_before(),
first.loc_next(),
first.spaced,
first.content,
);
self.write_chunk(&first_chunk)?;
let multiline = !self.try_on_single_line(|fmt| {
fun(fmt, false)?;
let last_chunk = fmt.chunk_at(
last.loc_before(),
last.loc_next(),
last.spaced,
&last.content,
);
fmt.write_chunk(&last_chunk)?;
Ok(())
})?;
if multiline {
self.indented(1, |fmt| {
fmt.write_whitespace_separator(true)?;
let stringified = fmt.with_temp_buf(|fmt| fun(fmt, true))?.w;
write_chunk!(fmt, "{}", stringified.trim_start())
})?;
if !last.content.trim_start().is_empty() {
self.indented(1, |fmt| fmt.write_whitespace_separator(true))?;
}
let last_chunk = self.chunk_at(
last.loc_before(),
last.loc_next(),
last.spaced,
&last.content,
);
self.write_chunk(&last_chunk)?;
}
Ok(())
}
/// Write each [Visitable] item on a separate line. The function will check if there are any
/// blank lines between each visitable statement and will apply a single blank line if there
/// exists any. The `needs_space` callback can force a newline and is given the last_item if
/// any and the next item as arguments
fn write_lined_visitable<'b, I, V, F>(
&mut self,
loc: Loc,
items: I,
needs_space_fn: F,
) -> Result<()>
where
I: Iterator<Item = &'b mut V> + 'b,
V: Visitable + CodeLocation + 'b,
F: Fn(&V, &V) -> bool,
{
let mut items = items.collect::<Vec<_>>();
items.reverse();
// get next item
let pop_next = |fmt: &mut Self, items: &mut Vec<&'b mut V>| {
let comment = fmt
.comments
.iter()
.next()
.filter(|comment| comment.loc.end() < loc.end());
let item = items.last();
if let (Some(comment), Some(item)) = (comment, item) {
if comment.loc < item.loc() {
Some(Either::Left(fmt.comments.pop().unwrap()))
} else {
Some(Either::Right(items.pop().unwrap()))
}
} else if comment.is_some() {
Some(Either::Left(fmt.comments.pop().unwrap()))
} else if item.is_some() {
Some(Either::Right(items.pop().unwrap()))
} else {