This repository has been archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 660
/
mod.rs
1504 lines (1298 loc) · 48.5 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
mod call_stack;
mod line_suffixes;
mod printer_options;
mod queue;
mod stack;
pub use printer_options::*;
use crate::format_element::{BestFitting, LineMode, PrintMode};
use crate::{
ActualStart, FormatElement, GroupId, IndentStyle, InvalidDocumentError, PrintError,
PrintResult, Printed, SourceMarker, TextRange,
};
use crate::format_element::document::Document;
use crate::format_element::tag::Condition;
use crate::prelude::tag::{DedentMode, Tag, TagKind, VerbatimKind};
use crate::prelude::Tag::EndFill;
use crate::printer::call_stack::{
CallStack, FitsCallStack, PrintCallStack, PrintElementArgs, StackFrame,
};
use crate::printer::line_suffixes::{LineSuffixEntry, LineSuffixes};
use crate::printer::queue::{
AllPredicate, FitsPredicate, FitsQueue, PrintQueue, Queue, SeparatorItemPairPredicate,
SingleEntryPredicate,
};
use rome_rowan::{TextLen, TextSize};
use std::num::NonZeroU8;
/// Prints the format elements into a string
#[derive(Debug, Default)]
pub struct Printer<'a> {
options: PrinterOptions,
state: PrinterState<'a>,
}
impl<'a> Printer<'a> {
pub fn new(options: PrinterOptions) -> Self {
Self {
options,
state: PrinterState::default(),
}
}
/// 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
pub fn print_with_indent(
mut self,
document: &'a Document,
indent: u16,
) -> PrintResult<Printed> {
tracing::debug_span!("Printer::print").in_scope(move || {
let mut stack = PrintCallStack::new(PrintElementArgs::new(Indention::Level(indent)));
let mut queue: PrintQueue<'a> = PrintQueue::new(document.as_ref());
while let Some(element) = queue.pop() {
self.print_element(&mut stack, &mut queue, element)?;
if queue.is_empty() {
self.flush_line_suffixes(&mut queue, &mut stack, None);
}
}
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<()> {
use Tag::*;
let args = stack.top();
match element {
FormatElement::Space => {
if self.state.line_width > 0 {
self.state.pending_space = true;
}
}
FormatElement::Text(token) => {
if !self.state.pending_indent.is_empty() {
let (indent_char, repeat_count) = match self.options.indent_style() {
IndentStyle::Tab => ('\t', 1),
IndentStyle::Space(count) => (' ', count),
};
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(' ');
}
}
// Print pending spaces
if self.state.pending_space {
self.print_str(" ");
self.state.pending_space = false;
}
// Insert source map markers before and after the token
//
// If the token has source position information the start marker
// will use the start position of the original token, and the end
// marker will use that position + the text length of the token
//
// If the token has no source position (was created by the formatter)
// both the start and end marker will use the last known position
// in the input source (from state.source_position)
if let Some(source) = token.source_position() {
self.state.source_position = *source;
}
self.push_marker(SourceMarker {
source: self.state.source_position,
dest: self.state.buffer.text_len(),
});
self.print_str(token);
if token.source_position().is_some() {
self.state.source_position += TextSize::of(&**token);
}
self.push_marker(SourceMarker {
source: self.state.source_position,
dest: self.state.buffer.text_len(),
});
}
FormatElement::Line(line_mode) => {
if args.mode().is_flat()
&& matches!(line_mode, LineMode::Soft | LineMode::SoftOrSpace)
{
if line_mode == &LineMode::SoftOrSpace && self.state.line_width > 0 {
self.state.pending_space = true;
}
} 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.line_width > 0 {
self.print_str("\n");
}
// Print a second line break if this is an empty line
if line_mode == &LineMode::Empty && !self.state.has_empty_line {
self.print_str("\n");
self.state.has_empty_line = true;
}
self.state.pending_space = false;
self.state.pending_indent = args.indention();
}
}
FormatElement::ExpandParent => {
// Handled in `Document::propagate_expands()
}
FormatElement::LineSuffixBoundary => {
const HARD_BREAK: &FormatElement = &FormatElement::Line(LineMode::Hard);
self.flush_line_suffixes(queue, stack, Some(HARD_BREAK));
}
FormatElement::BestFitting(best_fitting) => {
self.print_best_fitting(best_fitting, queue, stack)?;
}
FormatElement::Interned(content) => {
queue.extend_back(content);
}
FormatElement::Tag(StartGroup(group)) => {
let group_mode = if !group.mode().is_flat() {
PrintMode::Expanded
} else {
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;
// 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(TagKind::Group, args.with_print_mode(PrintMode::Flat));
let fits = fits_on_line(AllPredicate, queue, stack, self)?;
stack.pop(TagKind::Group)?;
if fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}
}
}
};
stack.push(TagKind::Group, args.with_print_mode(group_mode));
if let Some(id) = group.id() {
self.state.group_modes.insert_print_mode(id, group_mode);
}
}
FormatElement::Tag(StartFill) => {
stack.push(TagKind::Fill, args);
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.unwrap_print_mode(*id, element),
};
if group_mode != *mode {
queue.skip_content(TagKind::ConditionalContent);
} else {
stack.push(TagKind::ConditionalContent, args);
}
}
FormatElement::Tag(StartIndentIfGroupBreaks(group_id)) => {
let group_mode = self.state.group_modes.unwrap_print_mode(*group_id, element);
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) => {
self.state
.line_suffixes
.extend(args, queue.iter_content(TagKind::LineSuffix));
}
FormatElement::Tag(StartVerbatim(kind)) => {
if let VerbatimKind::Verbatim { length } = kind {
self.state.verbatim_markers.push(TextRange::at(
TextSize::from(self.state.buffer.len() as u32),
*length,
));
}
stack.push(TagKind::Verbatim, args);
}
FormatElement::Tag(tag @ (StartLabelled(_) | StartEntry)) => {
stack.push(tag.kind(), args);
}
FormatElement::Tag(
tag @ (EndLabelled
| EndEntry
| EndGroup
| EndIndent
| EndDedent
| EndAlign
| EndConditionalContent
| EndIndentIfGroupBreaks
| EndVerbatim
| EndLineSuffix
| EndFill),
) => {
stack.pop(tag.kind())?;
}
};
Ok(())
}
fn push_marker(&mut self, marker: SourceMarker) {
if let Some(last) = self.state.source_markers.last() {
if last != &marker {
self.state.source_markers.push(marker)
}
} else {
self.state.source_markers.push(marker);
}
}
fn flush_line_suffixes(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
line_break: Option<&'a FormatElement>,
) {
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) => {
stack.push(TagKind::LineSuffix, args);
const LINE_SUFFIX_END: &FormatElement =
&FormatElement::Tag(Tag::EndLineSuffix);
queue.push(LINE_SUFFIX_END);
}
}
}
}
}
fn print_best_fitting(
&mut self,
best_fitting: &'a BestFitting,
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(best_fitting.most_flat());
self.print_entry(queue, stack, args)
} else {
self.state.measured_group_fits = true;
let normal_variants = &best_fitting.variants()[..best_fitting.variants().len() - 1];
for variant in normal_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!(variant.first(), Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, variant.first());
}
let entry_args = args.with_print_mode(PrintMode::Flat);
// 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 = &variant[1..];
queue.extend_back(content);
stack.push(TagKind::Entry, entry_args);
let variant_fits = fits_on_line(AllPredicate, queue, stack, self)?;
stack.pop(TagKind::Entry)?;
// 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(variant);
return self.print_entry(queue, stack, entry_args);
}
}
// No variant fits, take the last (most expanded) as fallback
let most_expanded = best_fitting.most_expanded();
queue.extend_back(most_expanded);
self.print_entry(queue, stack, args.with_print_mode(PrintMode::Expanded))
}
}
/// Tries to fit as much content as possible on a single line.
/// Each item forms a virtual group that is either printed in flat or expanded mode.
/// It handles three different cases:
///
/// * The first and second content fit on a single line. It prints the content and separator in flat mode.
/// * The first content fits on a single line, but the second doesn't. It prints the content in flat and the separator in expanded mode.
/// * Neither the first nor the second content fit on the line. It brings the first content and the separator in expanded mode.
fn print_fill_entries(
&mut self,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<()> {
let args = stack.top();
if matches!(queue.top(), Some(FormatElement::Tag(Tag::EndFill))) {
// Empty fill
return Ok(());
}
// Print the first item
let mut current_fits =
self.fits_fill_entry(SingleEntryPredicate::default(), queue, stack)?;
self.state.measured_group_fits = current_fits;
self.print_entry(
queue,
stack,
args.with_print_mode(if current_fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}),
)?;
// Process remaining items, it's a sequence of separator, item, separator, item...
while matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
// A line break in expanded mode is always necessary if the current item didn't fit.
// otherwise see if both contents fit on the line.
let all_fits = if current_fits {
self.fits_fill_entry(SeparatorItemPairPredicate::default(), queue, stack)?
} else {
false
};
self.state.measured_group_fits = all_fits;
let separator_mode = if all_fits {
PrintMode::Flat
} else {
PrintMode::Expanded
};
// Separator
self.print_entry(queue, stack, args.with_print_mode(separator_mode))?;
// If this was a trailing separator, exit
if !matches!(queue.top(), Some(FormatElement::Tag(Tag::StartEntry))) {
break;
}
if all_fits {
// Item
self.print_entry(queue, stack, args.with_print_mode(PrintMode::Flat))?;
} else {
// Test if item fits now
let next_fits =
self.fits_fill_entry(SingleEntryPredicate::default(), queue, stack)?;
self.state.measured_group_fits = next_fits;
self.print_entry(
queue,
stack,
args.with_print_mode(if next_fits {
PrintMode::Flat
} else {
PrintMode::Expanded
}),
)?;
current_fits = next_fits;
}
}
if queue.top() == Some(&FormatElement::Tag(EndFill)) {
Ok(())
} else {
invalid_end_tag(TagKind::Fill, stack.top_kind())
}
}
fn fits_fill_entry<P>(
&mut self,
predicate: P,
queue: &mut PrintQueue<'a>,
stack: &mut PrintCallStack,
) -> PrintResult<bool>
where
P: FitsPredicate,
{
let start_entry = queue.top();
if !matches!(start_entry, Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, start_entry);
}
stack.push(TagKind::Fill, stack.top().with_print_mode(PrintMode::Flat));
let fits = fits_on_line(predicate, queue, stack, self)?;
stack.pop(TagKind::Fill)?;
Ok(fits)
}
/// 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,
) -> PrintResult<()> {
let start_entry = queue.top();
if !matches!(start_entry, Some(&FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, start_entry);
}
let mut depth = 0;
while let Some(element) = queue.pop() {
match element {
FormatElement::Tag(Tag::StartEntry) => {
// Handle the start of the first element by pushing the args on the stack.
if depth == 0 {
depth = 1;
stack.push(TagKind::Entry, args);
continue;
}
depth += 1;
}
FormatElement::Tag(Tag::EndEntry) => {
depth -= 1;
// Reached the end entry, pop the entry from the stack and return.
if depth == 0 {
stack.pop(TagKind::Entry)?;
return Ok(());
}
}
_ => {
// Fall through
}
}
self.print_element(stack, queue, element)?;
}
invalid_end_tag(TagKind::Entry, stack.top_kind())
}
fn print_str(&mut self, content: &str) {
for char in content.chars() {
self.print_char(char);
self.state.has_empty_line = false;
}
}
fn print_char(&mut self, char: char) {
if char == '\n' {
self.state
.buffer
.push_str(self.options.line_ending.as_str());
self.state.generated_line += 1;
self.state.generated_column = 0;
self.state.line_width = 0;
// 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);
self.state.generated_column += 1;
let char_width = if char == '\t' {
self.options.tab_width as usize
} else {
1
};
self.state.line_width += char_width;
}
}
}
/// 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> {
buffer: String,
source_markers: Vec<SourceMarker>,
source_position: TextSize,
pending_indent: Indention,
pending_space: bool,
measured_group_fits: bool,
generated_line: usize,
generated_column: usize,
line_width: usize,
has_empty_line: bool,
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 everytime a group gets measured
fits_stack: Vec<StackFrame>,
fits_queue: Vec<&'a [FormatElement]>,
}
/// 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) -> Option<PrintMode> {
let index = u32::from(group_id) as usize;
self.0
.get(index)
.and_then(|option| option.as_ref().copied())
}
fn unwrap_print_mode(&self, group_id: GroupId, next_element: &FormatElement) -> PrintMode {
self.get_print_mode(group_id).unwrap_or_else(|| {
panic!("Expected group with id {group_id:?} to exist but it wasn't present in the document. Ensure that a group with such a document appears in the document before the element {next_element:?}.")
})
}
}
#[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,
},
}
}
/// Decrements the indent by one by:
/// * Reducing the level by one if this is [Indent::Level]
/// * Removing the `align` if this is [Indent::Align]
///
/// No-op if the level is already zero.
fn decrement(self) -> Self {
match self {
Indention::Level(level) => Indention::Level(level.saturating_sub(1)),
Indention::Align { level, .. } => Indention::Level(level),
}
}
/// Adds an `align` of `count` spaces to the current indention.
///
/// It increments the `level` value if the current value is [Indent::IndentAlign].
fn set_align(self, count: NonZeroU8) -> Self {
match self {
Indention::Level(indent_count) => Indention::Align {
level: indent_count,
align: count,
},
// Convert the existing align to an indent
Indention::Align { level: indent, .. } => Indention::Align {
level: indent + 1,
align: count,
},
}
}
}
impl Default for Indention {
fn default() -> Self {
Indention::new()
}
}
/// Tests if it's possible to print the content of the queue up to the first hard line break
/// or the end of the document on a single line without exceeding the line width.
fn fits_on_line<'a, 'print, P>(
predicate: P,
print_queue: &'print PrintQueue<'a>,
stack: &'print PrintCallStack,
printer: &mut Printer<'a>,
) -> PrintResult<bool>
where
P: FitsPredicate,
{
let saved_stack = std::mem::take(&mut printer.state.fits_stack);
let saved_queue = std::mem::take(&mut printer.state.fits_queue);
debug_assert!(saved_stack.is_empty());
debug_assert!(saved_queue.is_empty());
let mut fits_queue = FitsQueue::new(print_queue, saved_queue);
let mut fits_stack = FitsCallStack::new(stack, saved_stack);
let mut fits_state = FitsState {
pending_indent: printer.state.pending_indent,
pending_space: printer.state.pending_space,
must_be_flat: matches!(fits_stack.top_kind(), Some(TagKind::Fill)),
line_width: printer.state.line_width,
has_line_suffix: printer.state.line_suffixes.has_pending(),
group_modes: &mut printer.state.group_modes,
};
let result = all_fit(
predicate,
&mut fits_state,
&mut fits_queue,
&mut fits_stack,
&printer.options,
);
printer.state.fits_stack = fits_stack.finish();
printer.state.fits_queue = fits_queue.finish();
printer.state.fits_stack.clear();
printer.state.fits_queue.clear();
result.map(|fits| match fits {
Fits::Maybe | Fits::Yes => true,
Fits::No => false,
})
}
/// Tests if it's possible to print the content of the queue up to the first hard line break
/// or the end of the document on a single line without exceeding the line width.
fn all_fit<'a, 'print, P>(
mut predicate: P,
fits_state: &mut FitsState,
queue: &mut FitsQueue<'a, 'print>,
stack: &mut FitsCallStack<'print>,
options: &PrinterOptions,
) -> PrintResult<Fits>
where
P: FitsPredicate,
{
while let Some(element) = queue.pop() {
if !predicate.apply(element)? {
break;
}
match fits_element_on_line(element, fits_state, queue, stack, options)? {
Fits::Yes => {
return Ok(Fits::Yes);
}
Fits::No => {
return Ok(Fits::No);
}
Fits::Maybe => {
continue;
}
}
}
Ok(Fits::Maybe)
}
/// Tests if the passed element fits on the current line or not.
fn fits_element_on_line<'a, 'rest>(
element: &'a FormatElement,
state: &mut FitsState,
queue: &mut FitsQueue<'a, 'rest>,
stack: &mut FitsCallStack<'rest>,
options: &PrinterOptions,
) -> PrintResult<Fits> {
use Tag::*;
let args = stack.top();
match element {
FormatElement::Space => {
if state.line_width > 0 {
state.pending_space = true;
}
}
FormatElement::Line(line_mode) => {
if args.mode().is_flat() {
match line_mode {
LineMode::SoftOrSpace => {
state.pending_space = true;
}
LineMode::Soft => {}
LineMode::Hard | LineMode::Empty => {
return Ok(if state.must_be_flat {
Fits::No
} else {
Fits::Yes
});
}
}
} else {
// Reachable if the restQueue contains an element with mode expanded because Expanded
// is what the mode's initialized to by default
// This means, the printer is outside of the current element at this point and any
// line break should be printed as regular line break -> Fits
return Ok(Fits::Yes);
}
}
FormatElement::Text(token) => {
let indent = std::mem::take(&mut state.pending_indent);
state.line_width +=
indent.level() as usize * options.indent_width() as usize + indent.align() as usize;
if state.pending_space {
state.line_width += 1;
}
for c in token.chars() {
let char_width = match c {
'\t' => options.tab_width,
'\n' => {
return Ok(if state.must_be_flat {
Fits::No
} else {
Fits::Yes
});
}
_ => 1,
};
state.line_width += char_width as usize;
}
if state.line_width > options.print_width.into() {
return Ok(Fits::No);
}
state.pending_space = false;
}
FormatElement::LineSuffixBoundary => {
if state.has_line_suffix {
return Ok(Fits::No);
}
}
FormatElement::ExpandParent => {
if state.must_be_flat {
return Ok(Fits::No);
}
}
FormatElement::BestFitting(best_fitting) => {
let slice = match args.mode() {
PrintMode::Flat => best_fitting.most_flat(),
PrintMode::Expanded => best_fitting.most_expanded(),
};
if !matches!(slice.first(), Some(FormatElement::Tag(Tag::StartEntry))) {
return invalid_start_tag(TagKind::Entry, slice.first());
}
stack.push(TagKind::Entry, args.with_print_mode(args.mode()));
queue.extend_back(&slice[1..]);
}
FormatElement::Interned(content) => queue.extend_back(content),
FormatElement::Tag(StartIndent) => {
stack.push(
TagKind::Indent,
args.increment_indent_level(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(StartGroup(group)) => {
if state.must_be_flat && !group.mode().is_flat() {
return Ok(Fits::No);
}
let group_mode = if !group.mode().is_flat() {
PrintMode::Expanded
} else {
args.mode()
};
stack.push(TagKind::Group, args.with_print_mode(group_mode));
if let Some(id) = group.id() {
state.group_modes.insert_print_mode(id, group_mode);
}
}
FormatElement::Tag(StartConditionalContent(condition)) => {
let group_mode = match condition.group_id {
None => args.mode(),
Some(group_id) => state
.group_modes
.get_print_mode(group_id)
.unwrap_or_else(|| args.mode()),
};
if group_mode != condition.mode {
queue.skip_content(TagKind::ConditionalContent);
} else {
stack.push(TagKind::ConditionalContent, args);
}
}
FormatElement::Tag(StartIndentIfGroupBreaks(id)) => {
let group_mode = state