-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
mod.rs
2093 lines (1809 loc) · 72.9 KB
/
mod.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
use std::num::NonZeroU8;
use drop_bomb::DebugDropBomb;
use unicode_width::UnicodeWidthChar;
pub use printer_options::*;
use ruff_text_size::{TextLen, TextSize};
use crate::format_element::document::Document;
use crate::format_element::tag::{Condition, GroupMode};
use crate::format_element::{BestFittingMode, BestFittingVariants, LineMode, PrintMode};
use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind};
use crate::prelude::{tag, TextWidth};
use crate::printer::call_stack::{
CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame,
};
use crate::printer::line_suffixes::{LineSuffixEntry, LineSuffixes};
use crate::printer::queue::{
AllPredicate, FitsEndPredicate, FitsQueue, PrintQueue, Queue, SingleEntryPredicate,
};
use crate::source_code::SourceCode;
use crate::{
ActualStart, FormatElement, GroupId, IndentStyle, InvalidDocumentError, PrintError,
PrintResult, Printed, SourceMarker, TextRange,
};
mod call_stack;
mod line_suffixes;
mod printer_options;
mod queue;
mod stack;
/// Prints the format elements into a string
#[derive(Debug, Default)]
pub struct Printer<'a> {
options: PrinterOptions,
source_code: SourceCode<'a>,
state: PrinterState<'a>,
}
impl<'a> Printer<'a> {
pub fn new(source_code: SourceCode<'a>, options: PrinterOptions) -> Self {
Self {
source_code,
options,
state: PrinterState::with_capacity(source_code.as_str().len()),
}
}
/// Prints the passed in element as well as all its content
pub fn print(self, document: &'a Document) -> PrintResult<Printed> {
self.print_with_indent(document, 0)
}
/// Prints the passed in element as well as all its content,
/// starting at the specified indentation level
#[tracing::instrument(level = "debug", name = "Printer::print", skip_all)]
pub fn print_with_indent(
mut self,
document: &'a Document,
indent: u16,
) -> PrintResult<Printed> {
let indentation = Indention::Level(indent);
self.state.pending_indent = indentation;
let mut stack = PrintCallStack::new(PrintElementArgs::new(indentation));
let mut queue: PrintQueue<'a> = PrintQueue::new(document.as_ref());
loop {
if let Some(element) = queue.pop() {
self.print_element(&mut stack, &mut queue, element)?;
} else {
if !self.flush_line_suffixes(&mut queue, &mut stack, None) {
break;
}
}
}
// Push any pending marker
self.push_marker();
Ok(Printed::new(
self.state.buffer,
None,
self.state.source_markers,
self.state.verbatim_markers,
))
}
/// Prints a single element and push the following elements to queue
fn print_element(
&mut self,
stack: &mut PrintCallStack,
queue: &mut PrintQueue<'a>,
element: &'a FormatElement,
) -> PrintResult<()> {
#[allow(clippy::enum_glob_use)]
use Tag::*;
let args = stack.top();
match element {
FormatElement::Space => self.print_text(Text::Token(" ")),
FormatElement::Token { text } => self.print_text(Text::Token(text)),
FormatElement::Text { text, text_width } => self.print_text(Text::Text {
text,
text_width: *text_width,
}),
FormatElement::SourceCodeSlice { slice, text_width } => {
let text = slice.text(self.source_code);
self.print_text(Text::Text {
text,
text_width: *text_width,
});
}
FormatElement::Line(line_mode) => {
if args.mode().is_flat()
&& matches!(line_mode, LineMode::Soft | LineMode::SoftOrSpace)
{
if line_mode == &LineMode::SoftOrSpace {
self.print_text(Text::Token(" "));
}
} else if self.state.line_suffixes.has_pending() {
self.flush_line_suffixes(queue, stack, Some(element));
} else {
// Only print a newline if the current line isn't already empty
if !self.state.buffer[self.state.line_start..].is_empty() {
self.push_marker();
self.print_char('\n');
}
// Print a second line break if this is an empty line
if line_mode == &LineMode::Empty {
self.push_marker();
self.print_char('\n');
}
self.state.pending_indent = args.indention();
}
}
FormatElement::ExpandParent => {
// Handled in `Document::propagate_expands()
}
FormatElement::SourcePosition(position) => {
// The printer defers printing indents until the next text
// is printed. Pushing the marker now would mean that the
// mapped range includes the indent range, which we don't want.
// Queue the source map position and emit it when printing the next character
self.state.pending_source_position = Some(*position);
}
FormatElement::LineSuffixBoundary => {
const HARD_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard);
self.flush_line_suffixes(queue, stack, Some(HARD_BREAK));
}
FormatElement::BestFitting { variants, mode } => {
self.print_best_fitting(variants, *mode, queue, stack)?;
}
FormatElement::Interned(content) => {
queue.extend_back(content);
}
FormatElement::Tag(StartGroup(group)) => {
let print_mode = match group.mode() {
GroupMode::Expand | GroupMode::Propagated => PrintMode::Expanded,
GroupMode::Flat => {
self.flat_group_print_mode(TagKind::Group, group.id(), args, queue, stack)?
}
};
if let Some(id) = group.id() {
self.state.group_modes.insert_print_mode(id, print_mode);
}
stack.push(TagKind::Group, args.with_print_mode(print_mode));
}
FormatElement::Tag(StartBestFitParenthesize { id }) => {
const OPEN_PAREN: FormatElement = FormatElement::Token { text: "(" };
const INDENT: FormatElement = FormatElement::Tag(Tag::StartIndent);
const HARD_LINE_BREAK: FormatElement = FormatElement::Line(LineMode::Hard);
let fits_flat = self.flat_group_print_mode(
TagKind::BestFitParenthesize,
*id,
args,
queue,
stack,
)? == PrintMode::Flat;
let print_mode = if fits_flat {
PrintMode::Flat
} else {
// Test if the content fits in expanded mode. If not, prefer avoiding the parentheses
// over parenthesizing the expression.
if let Some(id) = id {
self.state
.group_modes
.insert_print_mode(*id, PrintMode::Expanded);
}
stack.push(
TagKind::BestFitParenthesize,
args.with_measure_mode(MeasureMode::AllLines),
);
queue.extend_back(&[OPEN_PAREN, INDENT, HARD_LINE_BREAK]);
let fits_expanded = self.fits(queue, stack)?;
queue.pop_slice();
stack.pop(TagKind::BestFitParenthesize)?;
if fits_expanded {
PrintMode::Expanded
} else {
PrintMode::Flat
}
};
if let Some(id) = id {
self.state.group_modes.insert_print_mode(*id, print_mode);
}
if print_mode.is_expanded() {
// Parenthesize the content. The `EndIndent` is handled inside of the `EndBestFitParenthesize`
queue.extend_back(&[OPEN_PAREN, INDENT, HARD_LINE_BREAK]);
}
stack.push(
TagKind::BestFitParenthesize,
args.with_print_mode(print_mode),
);
}
FormatElement::Tag(EndBestFitParenthesize) => {
if args.mode().is_expanded() {
const HARD_LINE_BREAK: FormatElement = FormatElement::Line(LineMode::Hard);
const CLOSE_PAREN: FormatElement = FormatElement::Token { text: ")" };
// Finish the indent and print the hardline break and closing parentheses.
stack.pop(TagKind::Indent)?;
queue.extend_back(&[HARD_LINE_BREAK, CLOSE_PAREN]);
}
stack.pop(TagKind::BestFitParenthesize)?;
}
FormatElement::Tag(StartConditionalGroup(group)) => {
let condition = group.condition();
let expected_mode = match condition.group_id {
None => args.mode(),
Some(id) => self.state.group_modes.get_print_mode(id)?,
};
if expected_mode == condition.mode {
let print_mode = match group.mode() {
GroupMode::Expand | GroupMode::Propagated => PrintMode::Expanded,
GroupMode::Flat => self.flat_group_print_mode(
TagKind::ConditionalGroup,
None,
args,
queue,
stack,
)?,
};
stack.push(TagKind::ConditionalGroup, args.with_print_mode(print_mode));
} else {
// Condition isn't met, render as normal content
stack.push(TagKind::ConditionalGroup, args);
}
}
FormatElement::Tag(StartFill) => {
self.print_fill_entries(queue, stack)?;
}
FormatElement::Tag(StartIndent) => {
stack.push(
TagKind::Indent,
args.increment_indent_level(self.options.indent_style()),
);
}
FormatElement::Tag(StartDedent(mode)) => {
let args = match mode {
DedentMode::Level => args.decrement_indent(),
DedentMode::Root => args.reset_indent(),
};
stack.push(TagKind::Dedent, args);
}
FormatElement::Tag(StartAlign(align)) => {
stack.push(TagKind::Align, args.set_indent_align(align.count()));
}
FormatElement::Tag(StartConditionalContent(Condition { mode, group_id })) => {
let group_mode = match group_id {
None => args.mode(),
Some(id) => self.state.group_modes.get_print_mode(*id)?,
};
if *mode == group_mode {
stack.push(TagKind::ConditionalContent, args);
} else {
queue.skip_content(TagKind::ConditionalContent);
}
}
FormatElement::Tag(StartIndentIfGroupBreaks(group_id)) => {
let group_mode = self.state.group_modes.get_print_mode(*group_id)?;
let args = match group_mode {
PrintMode::Flat => args,
PrintMode::Expanded => args.increment_indent_level(self.options.indent_style),
};
stack.push(TagKind::IndentIfGroupBreaks, args);
}
FormatElement::Tag(StartLineSuffix { reserved_width }) => {
self.state.line_width += reserved_width;
self.state
.line_suffixes
.extend(args, queue.iter_content(TagKind::LineSuffix));
}
FormatElement::Tag(StartVerbatim(kind)) => {
if let VerbatimKind::Verbatim { length } = kind {
// SAFETY: Ruff only supports formatting files <= 4GB
#[allow(clippy::cast_possible_truncation)]
self.state.verbatim_markers.push(TextRange::at(
TextSize::from(self.state.buffer.len() as u32),
*length,
));
}
stack.push(TagKind::Verbatim, args);
}
FormatElement::Tag(StartFitsExpanded(tag::FitsExpanded { condition, .. })) => {
let condition_met = match condition {
Some(condition) => {
let group_mode = match condition.group_id {
Some(group_id) => self.state.group_modes.get_print_mode(group_id)?,
None => args.mode(),
};
condition.mode == group_mode
}
None => true,
};
if condition_met {
// We measured the inner groups all in expanded. It now is necessary to measure if the inner groups fit as well.
self.state.measured_group_fits = false;
}
stack.push(TagKind::FitsExpanded, args);
}
FormatElement::Tag(
tag @ (StartLabelled(_) | StartEntry | StartBestFittingEntry { .. }),
) => {
stack.push(tag.kind(), args);
}
FormatElement::Tag(
tag @ (EndLabelled
| EndEntry
| EndGroup
| EndConditionalGroup
| EndIndent
| EndDedent
| EndAlign
| EndConditionalContent
| EndIndentIfGroupBreaks
| EndFitsExpanded
| EndVerbatim
| EndLineSuffix
| EndBestFittingEntry
| EndFill),
) => {
stack.pop(tag.kind())?;
}
};
Ok(())
}
fn fits(&mut self, queue: &PrintQueue<'a>, stack: &PrintCallStack) -> PrintResult<bool> {
let mut measure = FitsMeasurer::new(queue, stack, self);
let result = measure.fits(&mut AllPredicate);
measure.finish();
result
}
fn flat_group_print_mode(
&mut self,
kind: TagKind,
id: Option<GroupId>,
args: PrintElementArgs,
queue: &PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<PrintMode> {
let print_mode = match args.mode() {
PrintMode::Flat if self.state.measured_group_fits => {
// A parent group has already verified that this group fits on a single line
// Thus, just continue in flat mode
PrintMode::Flat
}
// The printer is either in expanded mode or it's necessary to re-measure if the group fits
// because the printer printed a line break
_ => {
self.state.measured_group_fits = true;
if let Some(id) = id {
self.state
.group_modes
.insert_print_mode(id, PrintMode::Flat);
}
// Measure to see if the group fits up on a single line. If that's the case,
// print the group in "flat" mode, otherwise continue in expanded mode
stack.push(kind, args.with_print_mode(PrintMode::Flat));
let fits = self.fits(queue, stack)?;
stack.pop(kind)?;
if fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}
}
};
Ok(print_mode)
}
fn print_text(&mut self, text: Text) {
if !self.state.pending_indent.is_empty() {
let (indent_char, repeat_count) = match self.options.indent_style() {
IndentStyle::Tab => ('\t', 1),
IndentStyle::Space => (' ', self.options.indent_width()),
};
let indent = std::mem::take(&mut self.state.pending_indent);
let total_indent_char_count = indent.level() as usize * repeat_count as usize;
self.state
.buffer
.reserve(total_indent_char_count + indent.align() as usize);
for _ in 0..total_indent_char_count {
self.print_char(indent_char);
}
for _ in 0..indent.align() {
self.print_char(' ');
}
}
self.push_marker();
match text {
#[allow(clippy::cast_possible_truncation)]
Text::Token(token) => {
self.state.buffer.push_str(token);
self.state.line_width += token.len() as u32;
}
Text::Text {
text,
text_width: width,
} => {
if let Some(width) = width.width() {
self.state.buffer.push_str(text);
self.state.line_width += width.value();
} else {
for char in text.chars() {
self.print_char(char);
}
}
}
}
}
fn push_marker(&mut self) {
let Some(source_position) = self.state.pending_source_position.take() else {
return;
};
let marker = SourceMarker {
source: source_position,
dest: self.state.buffer.text_len(),
};
if self
.state
.source_markers
.last()
.map_or(true, |last| last != &marker)
{
self.state.source_markers.push(marker);
}
}
fn flush_line_suffixes(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
line_break: Option<&'a FormatElement>,
) -> bool {
let suffixes = self.state.line_suffixes.take_pending();
if suffixes.len() > 0 {
// Print this line break element again once all the line suffixes have been flushed
if let Some(line_break) = line_break {
queue.push(line_break);
}
for entry in suffixes.rev() {
match entry {
LineSuffixEntry::Suffix(suffix) => {
queue.push(suffix);
}
LineSuffixEntry::Args(args) => {
const LINE_SUFFIX_END: &FormatElement =
&FormatElement::Tag(Tag::EndLineSuffix);
stack.push(TagKind::LineSuffix, args);
queue.push(LINE_SUFFIX_END);
}
}
}
true
} else {
false
}
}
fn print_best_fitting(
&mut self,
variants: &'a BestFittingVariants,
mode: BestFittingMode,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<()> {
let args = stack.top();
if args.mode().is_flat() && self.state.measured_group_fits {
queue.extend_back(variants.most_flat());
self.print_entry(queue, stack, args, TagKind::BestFittingEntry)
} else {
self.state.measured_group_fits = true;
let mut variants_iter = variants.into_iter();
let mut current = variants_iter.next().unwrap();
for next in variants_iter {
// Test if this variant fits and if so, use it. Otherwise try the next
// variant.
// Try to fit only the first variant on a single line
if !matches!(
current.first(),
Some(&FormatElement::Tag(Tag::StartBestFittingEntry))
) {
return invalid_start_tag(TagKind::BestFittingEntry, current.first());
}
// Skip the first element because we want to override the args for the entry and the
// args must be popped from the stack as soon as it sees the matching end entry.
let content = ¤t[1..];
let entry_args = args
.with_print_mode(PrintMode::Flat)
.with_measure_mode(MeasureMode::from(mode));
queue.extend_back(content);
stack.push(TagKind::BestFittingEntry, entry_args);
let variant_fits = self.fits(queue, stack)?;
stack.pop(TagKind::BestFittingEntry)?;
// Remove the content slice because printing needs the variant WITH the start entry
let popped_slice = queue.pop_slice();
debug_assert_eq!(popped_slice, Some(content));
if variant_fits {
queue.extend_back(current);
return self.print_entry(
queue,
stack,
args.with_print_mode(PrintMode::Flat),
TagKind::BestFittingEntry,
);
}
current = next;
}
// At this stage current is the most expanded.
// No variant fits, take the last (most expanded) as fallback
queue.extend_back(current);
self.print_entry(
queue,
stack,
args.with_print_mode(PrintMode::Expanded),
TagKind::BestFittingEntry,
)
}
}
/// Tries to fit as much content as possible on a single line.
///
/// `Fill` is a sequence of *item*, *separator*, *item*, *separator*, *item*, ... entries.
/// The goal is to fit as many items (with their separators) on a single line as possible and
/// first expand the *separator* if the content exceeds the print width and only fallback to expanding
/// the *item*s if the *item* or the *item* and the expanded *separator* don't fit on the line.
///
/// The implementation handles the following 5 cases:
///
/// - The *item*, *separator*, and the *next item* fit on the same line.
/// Print the *item* and *separator* in flat mode.
/// - The *item* and *separator* fit on the line but there's not enough space for the *next item*.
/// Print the *item* in flat mode and the *separator* in expanded mode.
/// - The *item* fits on the line but the *separator* does not in flat mode.
/// Print the *item* in flat mode and the *separator* in expanded mode.
/// - The *item* fits on the line but the *separator* does not in flat **NOR** expanded mode.
/// Print the *item* and *separator* in expanded mode.
/// - The *item* does not fit on the line.
/// Print the *item* and *separator* in expanded mode.
fn print_fill_entries(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<()> {
let args = stack.top();
// It's already known that the content fit, print all items in flat mode.
if self.state.measured_group_fits && args.mode().is_flat() {
stack.push(TagKind::Fill, args.with_print_mode(PrintMode::Flat));
return Ok(());
}
stack.push(TagKind::Fill, args);
while matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
let mut measurer = FitsMeasurer::new_flat(queue, stack, self);
// The number of item/separator pairs that fit on the same line.
let mut flat_pairs = 0usize;
let mut item_fits = measurer.fill_item_fits()?;
let last_pair_layout = if item_fits {
// Measure the remaining pairs until the first item or separator that does not fit (or the end of the fill element).
// Optimisation to avoid re-measuring the next-item twice:
// * Once when measuring if the *item*, *separator*, *next-item* fit
// * A second time when measuring if *next-item*, *separator*, *next-next-item* fit.
loop {
// Item that fits without a following separator.
if !matches!(
measurer.queue.top(),
Some(FormatElement::Tag(Tag::StartEntry))
) {
break FillPairLayout::Flat;
}
let separator_fits = measurer.fill_separator_fits(PrintMode::Flat)?;
// Item fits but the flat separator does not.
if !separator_fits {
break FillPairLayout::ItemMaybeFlat;
}
// Last item/separator pair that both fit
if !matches!(
measurer.queue.top(),
Some(FormatElement::Tag(Tag::StartEntry))
) {
break FillPairLayout::Flat;
}
item_fits = measurer.fill_item_fits()?;
if item_fits {
flat_pairs += 1;
} else {
// Item and separator both fit, but the next element doesn't.
// Print the separator in expanded mode and then re-measure if the item now
// fits in the next iteration of the outer loop.
break FillPairLayout::ItemFlatSeparatorExpanded;
}
}
} else {
// Neither item nor separator fit, print both in expanded mode.
FillPairLayout::Expanded
};
measurer.finish();
self.state.measured_group_fits = true;
// Print all pairs that fit in flat mode.
for _ in 0..flat_pairs {
self.print_fill_item(queue, stack, args.with_print_mode(PrintMode::Flat))?;
self.print_fill_separator(queue, stack, args.with_print_mode(PrintMode::Flat))?;
}
let item_mode = match last_pair_layout {
FillPairLayout::Flat | FillPairLayout::ItemFlatSeparatorExpanded => PrintMode::Flat,
FillPairLayout::Expanded => PrintMode::Expanded,
FillPairLayout::ItemMaybeFlat => {
let mut measurer = FitsMeasurer::new_flat(queue, stack, self);
// SAFETY: That the item fits is guaranteed by `ItemMaybeFlat`.
// Re-measuring is required to get the measurer in the correct state for measuring the separator.
assert!(measurer.fill_item_fits()?);
let separator_fits = measurer.fill_separator_fits(PrintMode::Expanded)?;
measurer.finish();
if separator_fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}
}
};
self.print_fill_item(queue, stack, args.with_print_mode(item_mode))?;
if matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
let separator_mode = match last_pair_layout {
FillPairLayout::Flat => PrintMode::Flat,
FillPairLayout::ItemFlatSeparatorExpanded
| FillPairLayout::Expanded
| FillPairLayout::ItemMaybeFlat => PrintMode::Expanded,
};
// Push a new stack frame with print mode `Flat` for the case where the separator gets printed in expanded mode
// but does contain a group to ensure that the group will measure "fits" with the "flat" versions of the next item/separator.
stack.push(TagKind::Fill, args.with_print_mode(PrintMode::Flat));
self.print_fill_separator(queue, stack, args.with_print_mode(separator_mode))?;
stack.pop(TagKind::Fill)?;
}
}
if queue.top() == Some(&FormatElement::Tag(Tag::EndFill)) {
Ok(())
} else {
invalid_end_tag(TagKind::Fill, stack.top_kind())
}
}
/// Semantic alias for [`Self::print_entry`] for fill items.
fn print_fill_item(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
) -> PrintResult<()> {
self.print_entry(queue, stack, args, TagKind::Entry)
}
/// Semantic alias for [`Self::print_entry`] for fill separators.
fn print_fill_separator(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
) -> PrintResult<()> {
self.print_entry(queue, stack, args, TagKind::Entry)
}
/// Fully print an element (print the element itself and all its descendants)
///
/// Unlike [`print_element`], this function ensures the entire element has
/// been printed when it returns and the queue is back to its original state
fn print_entry(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
args: PrintElementArgs,
kind: TagKind,
) -> PrintResult<()> {
let start_entry = queue.top();
if queue
.pop()
.is_some_and(|start| start.tag_kind() == Some(kind))
{
stack.push(kind, args);
} else {
return invalid_start_tag(kind, start_entry);
}
let mut depth = 1u32;
while let Some(element) = queue.pop() {
match element {
FormatElement::Tag(Tag::StartEntry | Tag::StartBestFittingEntry) => {
depth += 1;
}
FormatElement::Tag(end_tag @ (Tag::EndEntry | Tag::EndBestFittingEntry)) => {
depth -= 1;
// Reached the end entry, pop the entry from the stack and return.
if depth == 0 {
stack.pop(end_tag.kind())?;
return Ok(());
}
}
_ => {
// Fall through
}
}
self.print_element(stack, queue, element)?;
}
invalid_end_tag(kind, stack.top_kind())
}
fn print_char(&mut self, char: char) {
if char == '\n' {
self.state
.buffer
.push_str(self.options.line_ending.as_str());
self.state.line_width = 0;
self.state.line_start = self.state.buffer.len();
// Fit's only tests if groups up to the first line break fit.
// The next group must re-measure if it still fits.
self.state.measured_group_fits = false;
} else {
self.state.buffer.push(char);
#[allow(clippy::cast_possible_truncation)]
let char_width = if char == '\t' {
self.options.indent_width.value()
} else {
// SAFETY: A u32 is sufficient to represent the width of a file <= 4GB
char.width().unwrap_or(0) as u32
};
self.state.line_width += char_width;
}
}
}
#[derive(Copy, Clone, Debug)]
enum FillPairLayout {
/// The item, separator, and next item fit. Print the first item and the separator in flat mode.
Flat,
/// The item and separator fit but the next element does not. Print the item in flat mode and
/// the separator in expanded mode.
ItemFlatSeparatorExpanded,
/// The item does not fit. Print the item and any potential separator in expanded mode.
Expanded,
/// The item fits but the separator does not in flat mode. If the separator fits in expanded mode then
/// print the item in flat and the separator in expanded mode, otherwise print both in expanded mode.
ItemMaybeFlat,
}
/// Printer state that is global to all elements.
/// Stores the result of the print operation (buffer and mappings) and at what
/// position the printer currently is.
#[derive(Default, Debug)]
struct PrinterState<'a> {
/// The formatted output.
buffer: String,
/// The source markers that map source positions to formatted positions.
source_markers: Vec<SourceMarker>,
/// The next source position that should be flushed when writing the next text.
pending_source_position: Option<TextSize>,
/// The current indentation that should be written before the next text.
pending_indent: Indention,
/// Caches if the code up to the next newline has been measured to fit on a single line.
/// This is used to avoid re-measuring the same content multiple times.
measured_group_fits: bool,
/// The offset at which the current line in `buffer` starts.
line_start: usize,
/// The accumulated unicode-width of all characters on the current line.
line_width: u32,
/// The line suffixes that should be printed at the end of the line.
line_suffixes: LineSuffixes<'a>,
verbatim_markers: Vec<TextRange>,
group_modes: GroupModes,
// Re-used queue to measure if a group fits. Optimisation to avoid re-allocating a new
// vec every time a group gets measured
fits_stack: Vec<StackFrame>,
fits_queue: Vec<std::slice::Iter<'a, FormatElement>>,
}
impl<'a> PrinterState<'a> {
fn with_capacity(capacity: usize) -> Self {
Self {
buffer: String::with_capacity(capacity),
..Self::default()
}
}
}
/// Tracks the mode in which groups with ids are printed. Stores the groups at `group.id()` index.
/// This is based on the assumption that the group ids for a single document are dense.
#[derive(Debug, Default)]
struct GroupModes(Vec<Option<PrintMode>>);
impl GroupModes {
fn insert_print_mode(&mut self, group_id: GroupId, mode: PrintMode) {
let index = u32::from(group_id) as usize;
if self.0.len() <= index {
self.0.resize(index + 1, None);
}
self.0[index] = Some(mode);
}
fn get_print_mode(&self, group_id: GroupId) -> PrintResult<PrintMode> {
let index = u32::from(group_id) as usize;
match self.0.get(index) {
Some(Some(print_mode)) => Ok(*print_mode),
None | Some(None) => Err(PrintError::InvalidDocument(
InvalidDocumentError::UnknownGroupId { group_id },
)),
}
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum Indention {
/// Indent the content by `count` levels by using the indention sequence specified by the printer options.
Level(u16),
/// Indent the content by n-`level`s using the indention sequence specified by the printer options and `align` spaces.
Align { level: u16, align: NonZeroU8 },
}
impl Indention {
const fn is_empty(self) -> bool {
matches!(self, Indention::Level(0))
}
/// Creates a new indention level with a zero-indent.
const fn new() -> Self {
Indention::Level(0)
}
/// Returns the indention level
fn level(self) -> u16 {
match self {
Indention::Level(count) => count,
Indention::Align { level: indent, .. } => indent,
}
}
/// Returns the number of trailing align spaces or 0 if none
fn align(self) -> u8 {
match self {
Indention::Level(_) => 0,
Indention::Align { align, .. } => align.into(),
}
}
/// Increments the level by one.
///
/// The behaviour depends on the [`indent_style`][IndentStyle] if this is an [`Indent::Align`]:
/// - **Tabs**: `align` is converted into an indent. This results in `level` increasing by two: once for the align, once for the level increment
/// - **Spaces**: Increments the `level` by one and keeps the `align` unchanged.
/// Keeps any the current value is [`Indent::Align`] and increments the level by one.
fn increment_level(self, indent_style: IndentStyle) -> Self {
match self {
Indention::Level(count) => Indention::Level(count + 1),
// Increase the indent AND convert the align to an indent
Indention::Align { level, .. } if indent_style.is_tab() => Indention::Level(level + 2),
Indention::Align {
level: indent,
align,
} => Indention::Align {
level: indent + 1,
align,
},
}
}