forked from gleam-lang/gleam
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
4384 lines (4014 loc) · 155 KB
/
Copy pathlib.rs
File metadata and controls
4384 lines (4014 loc) · 155 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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2020 The Gleam contributors
#[cfg(test)]
mod tests;
use camino::Utf8Path;
use ecow::{EcoString, eco_format};
use gleam_core::{
Error, Result,
ast::{
CustomType, Import, ModuleConstant, TypeAlias, TypeAstConstructor, TypeAstFn, TypeAstHole,
TypeAstTuple, TypeAstVar, *,
},
build::Target,
io::Utf8Writer,
parse::extra::{Comment, ModuleExtra},
type_::Deprecation,
warning::WarningEmitter,
};
use itertools::Itertools;
use pretty_arena::*;
use std::cmp::Ordering;
use vec1::Vec1;
const INDENT: isize = 2;
pub fn pretty(writer: &mut impl Utf8Writer, src: &EcoString, path: &Utf8Path) -> Result<()> {
let parsed = gleam_core::parse::parse_module(path.to_owned(), src, &WarningEmitter::null())
.map_err(|error| Error::Parse {
path: path.to_path_buf(),
src: src.clone(),
error: Box::new(error),
})?;
let intermediate = Intermediate::from_extra(&parsed.extra, src);
let arena = DocumentArena::new();
Formatter::with_comments(&intermediate)
.module(&arena, &parsed.module)
.pretty_print(80, writer)
.map_err(|error| writer.convert_err(error))
}
pub(crate) struct Intermediate<'a> {
comments: Vec<Comment<'a>>,
doc_comments: Vec<Comment<'a>>,
module_comments: Vec<Comment<'a>>,
empty_lines: &'a [u32],
new_lines: &'a [u32],
trailing_commas: &'a [u32],
}
impl<'a> Intermediate<'a> {
pub fn from_extra(extra: &'a ModuleExtra, src: &'a EcoString) -> Intermediate<'a> {
Intermediate {
comments: extra
.comments
.iter()
.map(|span| Comment::from((span, src)))
.collect(),
doc_comments: extra
.doc_comments
.iter()
.map(|span| Comment::from((span, src)))
.collect(),
empty_lines: &extra.empty_lines,
module_comments: extra
.module_comments
.iter()
.map(|span| Comment::from((span, src)))
.collect(),
new_lines: &extra.new_lines,
trailing_commas: &extra.trailing_commas,
}
}
}
#[derive(Debug)]
enum FnCapturePosition {
RightHandSideOfPipe,
EverywhereElse,
}
#[derive(Debug)]
/// One of the pieces making a record update arg list: it could be the starting
/// record being updated, or one of the subsequent arguments.
///
enum RecordUpdatePiece<'a, A> {
Record(&'a RecordBeingUpdated<A>),
Argument(&'a RecordUpdateArg<A>),
}
impl<A> HasLocation for RecordUpdatePiece<'_, A> {
fn location(&self) -> SrcSpan {
match self {
RecordUpdatePiece::Record(record) => record.location,
RecordUpdatePiece::Argument(arg) => arg.location,
}
}
}
type UntypedRecordUpdatePiece<'a> = RecordUpdatePiece<'a, UntypedExpr>;
/// Hayleigh's bane
#[derive(Debug)]
pub struct Formatter<'a> {
comments: &'a [Comment<'a>],
doc_comments: &'a [Comment<'a>],
module_comments: &'a [Comment<'a>],
empty_lines: &'a [u32],
new_lines: &'a [u32],
trailing_commas: &'a [u32],
}
impl<'a, 'doc> Formatter<'a> {
pub(crate) fn with_comments(extra: &'a Intermediate<'a>) -> Self {
Self {
comments: &extra.comments,
doc_comments: &extra.doc_comments,
module_comments: &extra.module_comments,
empty_lines: extra.empty_lines,
new_lines: extra.new_lines,
trailing_commas: extra.trailing_commas,
}
}
/// Returns true if there's any comment that comes before the given
/// position.
///
fn any_comments(&self, limit: u32) -> bool {
self.comments
.first()
.is_some_and(|comment| comment.start < limit)
}
/// Returns true if there's any comment that appears inside the given span.
///
fn any_comment_between(&self, start: u32, end: u32) -> bool {
self.comments
.binary_search_by(|comment| {
if comment.start < start {
Ordering::Less
} else if comment.start > end {
Ordering::Greater
} else {
Ordering::Equal
}
})
.is_ok()
}
fn any_empty_lines(&self, limit: u32) -> bool {
self.empty_lines.first().is_some_and(|line| *line < limit)
}
/// Pop comments that occur before a byte-index in the source, consuming
/// and retaining any empty lines contained within.
/// Returns an iterator of comments with their start position.
fn pop_comments_with_position(
&mut self,
limit: u32,
) -> impl Iterator<Item = (u32, Option<&'a str>)> + use<'a> {
let (popped, rest, empty_lines) =
comments_before(self.comments, self.empty_lines, limit, true);
self.comments = rest;
self.empty_lines = empty_lines;
popped
}
/// Pop comments that occur before a byte-index in the source, consuming
/// and retaining any empty lines contained within.
fn pop_comments(&mut self, limit: u32) -> impl Iterator<Item = Option<&'a str>> + use<'a> {
self.pop_comments_with_position(limit)
.map(|(_position, comment)| comment)
}
/// Pop doc comments that occur before a byte-index in the source, consuming
/// and dropping any empty lines contained within.
fn pop_doc_comments(&mut self, limit: u32) -> impl Iterator<Item = Option<&'a str>> + use<'a> {
let (popped, rest, empty_lines) =
comments_before(self.doc_comments, self.empty_lines, limit, false);
self.doc_comments = rest;
self.empty_lines = empty_lines;
popped.map(|(_position, comment)| comment)
}
/// Remove between 0 and `limit` empty lines following the current position,
/// returning true if any empty lines were removed.
fn pop_empty_lines(&mut self, limit: u32) -> bool {
let mut end = 0;
for (i, &position) in self.empty_lines.iter().enumerate() {
if position > limit {
break;
}
end = i + 1;
}
self.empty_lines = self
.empty_lines
.get(end..)
.expect("Pop empty lines slicing");
end != 0
}
fn targeted_definition(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
definition: &'a TargetedDefinition,
) -> Document<'a, 'doc> {
let target = definition.target;
let definition = &definition.definition;
let start = definition.location().start;
let comments = self.pop_comments_with_position(start);
let comments = self.printed_documented_comments(arena, comments);
let document = self.documented_definition(arena, definition);
let document = match target {
None => document,
Some(Target::Erlang) => {
docvec![arena, "@target(erlang)", LINE_DOCUMENT, document]
}
Some(Target::JavaScript) => {
docvec![arena, "@target(javascript)", LINE_DOCUMENT, document]
}
};
let document = document.group(arena);
match comments {
Some(comments) => comments.append(arena, document),
None => document,
}
}
pub(crate) fn module(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
module: &'a UntypedModule,
) -> Document<'a, 'doc> {
let mut documents = vec![];
let mut previous_was_a_definition = false;
// Here we take consecutive groups of imports so that they can be sorted
// alphabetically.
for (is_import_group, definitions) in &module
.definitions
.iter()
.chunk_by(|definition| definition.definition.is_import())
{
if is_import_group {
if previous_was_a_definition {
documents.push(TWO_LINES_DOCUMENT);
}
documents.append(&mut self.imports(arena, definitions.collect_vec()));
previous_was_a_definition = false;
} else {
for definition in definitions {
if !documents.is_empty() {
documents.push(TWO_LINES_DOCUMENT);
}
documents.push(self.targeted_definition(arena, definition));
}
previous_was_a_definition = true;
}
}
let definitions = arena.concat(documents);
// Now that definitions has been collected, only freestanding comments (//)
// and doc comments (///) remain. Freestanding comments aren't associated
// with any statement, and are moved to the bottom of the module.
let doc_comments = arena.join(
self.doc_comments.iter().map(|comment| {
DOC_COMMENT_DOCUMENT
.to_doc(arena)
.append(arena, arena.zero_width_str(comment.content))
}),
LINE_DOCUMENT,
);
let comments = self.pop_comments(u32::MAX);
let comments = match printed_comments(arena, comments, false) {
Some(comments) => comments,
None => EMPTY_DOCUMENT,
};
let module_comments = if !self.module_comments.is_empty() {
let comments = self.module_comments.iter().map(|s| {
MODULE_COMMENT_DOCUMENT
.to_doc(arena)
.append(arena, arena.zero_width_str(s.content))
});
arena
.join(comments, LINE_DOCUMENT)
.append(arena, LINE_DOCUMENT)
} else {
EMPTY_DOCUMENT
};
let non_empty = vec![module_comments, definitions, doc_comments, comments]
.into_iter()
.filter(|doc| !doc.is_empty());
arena
.join(non_empty, LINE_DOCUMENT)
.append(arena, LINE_DOCUMENT)
}
/// Separates the imports in groups delimited by comments or empty lines and
/// sorts each group alphabetically.
///
/// The formatter needs to play nicely with import groups defined by the
/// programmer. If one puts a comment before an import then that's a clue
/// for the formatter that it has run into a gorup of related imports.
///
/// So we can't just sort `imports` and format each one, we have to be a
/// bit smarter and see if each import is preceded by a comment.
/// Once we find a comment we know we're done with the current import
/// group and a new one has started.
///
/// ```gleam
/// // This is an import group.
/// import gleam/int
/// import gleam/string
///
/// // This marks the beginning of a new import group that can't
/// // be mushed together with the previous one!
/// import wibble
/// import wobble
/// ```
fn imports(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
imports: Vec<&'a TargetedDefinition>,
) -> Vec<Document<'a, 'doc>> {
let mut import_groups_docs = vec![];
let mut current_group = vec![];
let mut current_group_delimiter = EMPTY_DOCUMENT;
for import in imports {
let start = import.definition.location().start;
// We need to start a new group if the `import` is preceded by one or
// more empty lines or a `//` comment.
let start_new_group = self.any_comments(start) || self.any_empty_lines(start);
if start_new_group {
// First we print the previous group and clear it out to start a
// new empty group containing the import we've just ran into.
if !current_group.is_empty() {
import_groups_docs.push(docvec![
arena,
current_group_delimiter,
self.sorted_import_group(arena, ¤t_group)
]);
current_group.clear();
}
// Now that we've taken care of the previous group we can start
// the new one. We know it's preceded either by an empty line or
// some comments se we have to be a bit more precise and save the
// actual delimiter that we're going to put at the top of this
// group.
let comments = self.pop_comments(start);
let _ = self.pop_empty_lines(start);
current_group_delimiter =
printed_comments(arena, comments, true).unwrap_or(EMPTY_DOCUMENT);
}
// Lastly we add the import to the group.
current_group.push(import);
}
// Let's not forget about the last import group!
if !current_group.is_empty() {
import_groups_docs.push(docvec![
arena,
current_group_delimiter,
self.sorted_import_group(arena, ¤t_group)
]);
}
// We want all consecutive import groups to be separated by an empty line.
// This should really be `.intersperse(LINE_DOCUMENT)` but I can't do that
// because of https://github.com/rust-lang/rust/issues/48919.
Itertools::intersperse(import_groups_docs.into_iter(), TWO_LINES_DOCUMENT).collect_vec()
}
/// Prints the imports as a single sorted group of import statements.
///
fn sorted_import_group(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
imports: &[&'a TargetedDefinition],
) -> Document<'a, 'doc> {
let imports = imports
.iter()
.sorted_by(|one, other| match (&one.definition, &other.definition) {
(Definition::Import(one), Definition::Import(other)) => {
one.module.cmp(&other.module)
}
// It shouldn't really be possible for a non import to be here so
// we just return a default value.
_ => Ordering::Equal,
})
.map(|import| self.targeted_definition(arena, import));
arena.join(imports, LINE_DOCUMENT)
}
fn unqualified_import(
&self,
arena: &'doc DocumentArena<'a, 'doc>,
unqualified_import: &'a UnqualifiedImport,
) -> Document<'a, 'doc> {
unqualified_import.name.as_ref().to_doc(arena).append(
arena,
match &unqualified_import.as_name {
None => EMPTY_DOCUMENT,
Some(s) if s == &unqualified_import.name => EMPTY_DOCUMENT,
Some(s) => " as ".to_doc(arena).append(arena, s.as_str()),
},
)
}
fn definition(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
statement: &'a UntypedDefinition,
) -> Document<'a, 'doc> {
match statement {
Definition::Function(function) => self.statement_fn(arena, function),
Definition::TypeAlias(alias) => self.type_alias(arena, alias),
Definition::CustomType(custom_type) => self.custom_type(arena, custom_type),
Definition::Import(Import {
module,
as_name,
unqualified_values,
unqualified_types,
..
}) => {
let second = if unqualified_values.is_empty() && unqualified_types.is_empty() {
EMPTY_DOCUMENT
} else {
let unqualified_types = unqualified_types
.iter()
.sorted_by(|a, b| a.name.cmp(&b.name))
.map(|import_| {
docvec![
arena,
TYPE_SPACE_DOCUMENT,
self.unqualified_import(arena, import_)
]
});
let unqualified_values = unqualified_values
.iter()
.sorted_by(|a, b| a.name.cmp(&b.name))
.map(|import_| self.unqualified_import(arena, import_));
let unqualified = arena.join(
unqualified_types.chain(unqualified_values),
FLEX_COMMA_DOCUMENT,
);
let unqualified = EMPTY_BREAK_DOCUMENT
.append(arena, unqualified)
.nest(arena, INDENT)
.append(arena, TRAILING_COMMA_BREAK_DOCUMENT)
.group(arena);
".{".to_doc(arena)
.append(arena, unqualified)
.append(arena, CLOSE_CURLY_DOCUMENT)
};
let doc = docvec![arena, IMPORT_SPACE_DOCUMENT, module.as_str(), second];
let default_module_access_name = module.split('/').next_back().map(EcoString::from);
match (default_module_access_name, as_name) {
// If the `as name` is the same as the module name that would be
// used anyways we won't render it. For example:
// ```gleam
// import gleam/int as int
// ^^^^^^ this is redundant and removed
// ```
(Some(module_name), Some((AssignName::Variable(name), _)))
if &module_name == name =>
{
doc
}
(_, None) => doc,
(_, Some((AssignName::Variable(name) | AssignName::Discard(name), _))) => doc
.append(arena, SPACE_AS_SPACE_DOCUMENT)
.append(arena, name),
}
}
Definition::ModuleConstant(ModuleConstant {
publicity,
name,
annotation,
value,
deprecation,
documentation: _,
location: _,
name_location: _,
type_: _,
implementations: _,
}) => {
let attributes = AttributesPrinter::new()
.set_internal(*publicity)
.set_deprecation(deprecation)
.to_doc(arena);
let head = attributes
.append(arena, pub_(*publicity))
.append(arena, CONST_SPACE_DOCUMENT)
.append(arena, name.as_str());
let head = match annotation {
None => head,
Some(type_) => head
.append(arena, COLON_SPACE_DOCUMENT)
.append(arena, self.type_ast(arena, type_)),
};
head.append(arena, SPACE_EQUAL_SPACE_DOCUMENT)
.append(arena, self.const_expr(arena, value).group(arena))
}
}
}
fn const_expr<A>(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
value: &'a Constant<A>,
) -> Document<'a, 'doc> {
let comments = self.pop_comments(value.location().start);
let document = match value {
Constant::Todo { message, .. } => {
self.append_as_message_constant(arena, TODO_DOCUMENT, message.as_deref())
}
Constant::Int { value, .. } => self.int(arena, value),
Constant::Float { value, .. } => self.float(arena, value),
Constant::String { value, .. } => self.string(arena, value),
Constant::List {
elements,
location,
tail,
..
} => self.const_list(arena, elements, location, tail),
Constant::Tuple {
elements, location, ..
} => self.const_tuple(arena, elements, location),
Constant::BitArray {
segments, location, ..
} => {
let segment_docs = segments
.iter()
.map(|segment| {
bit_array_segment(arena, segment, |expression| {
self.const_expr(arena, expression)
})
})
.collect_vec();
let packing = self.items_sequence_packing(
segments,
None,
|segment| segment.value.can_have_multiple_per_line(),
*location,
);
self.bit_array(arena, segment_docs, packing, location)
}
Constant::Record {
name,
arguments: None,
module: None,
..
} => name.to_doc(arena),
Constant::Record {
name,
arguments: None,
module: Some((module, _)),
..
} => module
.to_doc(arena)
.append(arena, DOT_DOCUMENT)
.append(arena, name.as_str()),
Constant::Record {
name,
arguments: Some(arguments),
module: None,
location,
..
} => {
let arguments = arguments
.iter()
.map(|argument| self.constant_call_arg(arena, argument))
.collect_vec();
name.to_doc(arena)
.append(arena, self.wrap_arguments(arena, arguments, location.end))
.group(arena)
}
Constant::Record {
name,
arguments: Some(arguments),
module: Some((module, _)),
location,
..
} => {
let arguments = arguments
.iter()
.map(|argument| self.constant_call_arg(arena, argument))
.collect_vec();
module
.to_doc(arena)
.append(arena, DOT_DOCUMENT)
.append(arena, name.as_str())
.append(arena, self.wrap_arguments(arena, arguments, location.end))
.group(arena)
}
Constant::Var {
name, module: None, ..
} => name.to_doc(arena),
Constant::Var {
name,
module: Some((module, _)),
..
} => docvec![arena, module, DOT_DOCUMENT, name],
Constant::StringConcatenation { left, right, .. } => self
.const_expr(arena, left)
.append(
arena,
BREAKABLE_SPACE_DOCUMENT.append(arena, CONCAT_DOCUMENT),
)
.nest(arena, INDENT)
.append(arena, SPACE_DOCUMENT)
.append(arena, self.const_expr(arena, right)),
Constant::RecordUpdate {
module,
name,
record,
arguments,
location,
..
} => self.const_record_update(arena, module, name, record, arguments, location),
Constant::Invalid { .. } => panic!("invalid constants can not be in an untyped ast"),
};
commented(arena, document, comments)
}
fn const_list<A>(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
elements: &'a [Constant<A>],
location: &SrcSpan,
tail: &'a Option<Box<Constant<A>>>,
) -> Document<'a, 'doc> {
if elements.is_empty() {
// We take all comments that come _before_ the end of the list,
// that is all comments that are inside "[" and "]", if there's
// any comment we want to put it inside the empty list!
let comments = self.pop_comments(location.end);
return match printed_comments(arena, comments, false) {
None => OPEN_CLOSE_SQUARE_DOCUMENT,
Some(comments) => OPEN_SQUARE_DOCUMENT
.append(arena, EMPTY_BREAK_DOCUMENT.nest(arena, INDENT))
.append(arena, comments)
.append(arena, EMPTY_BREAK_DOCUMENT)
.append(arena, CLOSE_SQUARE_DOCUMENT)
// vvv We want to make sure the comments are on a separate
// line from the opening and closing brackets so we
// force the breaks to be split on newlines.
.force_break(arena),
};
}
let list_packing = self.items_sequence_packing(
elements,
tail.as_deref(),
|element| element.can_have_multiple_per_line(),
*location,
);
let comma = match list_packing {
ItemsPacking::FitMultiplePerLine => FLEX_COMMA_DOCUMENT,
ItemsPacking::FitOnePerLine | ItemsPacking::BreakOnePerLine => COMMA_BREAK_DOCUMENT,
};
let mut is_empty = true;
let mut elements_doc = EMPTY_DOCUMENT;
for element in elements.iter() {
let empty_lines = self.pop_empty_lines(element.location().start);
let element_doc = self.const_expr(arena, element);
elements_doc = if is_empty {
is_empty = false;
element_doc
} else if empty_lines {
// If there's empty lines before the list item we want to add an
// empty line here. Notice how we're making sure no nesting is
// added after the comma, otherwise we would be adding needless
// whitespace in the empty line!
docvec![
arena,
elements_doc,
comma.set_nesting(arena, 0),
LINE_DOCUMENT,
element_doc
]
} else {
docvec![arena, elements_doc, comma, element_doc]
};
}
elements_doc = elements_doc.next_break_fits(arena, NextBreakFitsMode::Disabled);
let doc = OPEN_SQUARE_BREAK_DOCUMENT.append(arena, elements_doc);
let (doc, final_break) = match tail {
None => (doc.nest(arena, INDENT), TRAILING_COMMA_BREAK_DOCUMENT),
Some(tail) => {
let comments = self.pop_comments(tail.location().start);
let tail = commented(
arena,
docvec![arena, DOT_DOT_DOCUMENT, self.const_expr(arena, tail)],
comments,
);
(
doc.append(arena, COMMA_BREAK_DOCUMENT)
.append(arena, tail)
.nest(arena, INDENT),
EMPTY_BREAK_DOCUMENT,
)
}
};
// We get all remaining comments that come before the list's closing
// square bracket.
// If there's any we add those before the closing square bracket instead
// of moving those out of the list.
// Otherwise those would be moved out of the list.
let comments = self.pop_comments(location.end);
let doc = match printed_comments(arena, comments, false) {
None => doc
.append(arena, final_break)
.append(arena, CLOSE_SQUARE_DOCUMENT),
Some(comment) => doc
.append(arena, final_break.nest(arena, INDENT))
// ^ See how here we're adding the missing indentation to the
// final break so that the final comment is as indented as the
// list's items.
.append(arena, comment.nest(arena, INDENT))
.append(arena, LINE_DOCUMENT)
.append(arena, CLOSE_SQUARE_DOCUMENT)
.force_break(arena),
};
match list_packing {
ItemsPacking::FitOnePerLine | ItemsPacking::FitMultiplePerLine => doc.group(arena),
ItemsPacking::BreakOnePerLine => doc.force_break(arena),
}
}
pub fn const_tuple<A>(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
elements: &'a [Constant<A>],
location: &SrcSpan,
) -> Document<'a, 'doc> {
if elements.is_empty() {
// We take all comments that come _before_ the end of the tuple,
// that is all comments that are inside "#(" and ")", if there's
// any comment we want to put it inside the empty list!
let comments = self.pop_comments(location.end);
return match printed_comments(arena, comments, false) {
None => EMPTY_TUPLE_DOCUMENT,
Some(comments) => OPEN_TUPLE_DOCUMENT
.append(arena, EMPTY_BREAK_DOCUMENT.nest(arena, INDENT))
.append(arena, comments)
.append(arena, EMPTY_BREAK_DOCUMENT)
.append(arena, CLOSE_PAREN_DOCUMENT)
// vvv We want to make sure the comments are on a separate
// line from the opening and closing parentheses so we
// force the breaks to be split on newlines.
.force_break(arena),
};
}
let arguments_docs = elements
.iter()
.map(|element| self.const_expr(arena, element));
let tuple_doc = OPEN_TUPLE_BREAK_DOCUMENT
.append(
arena,
arena
.join(arguments_docs, COMMA_BREAK_DOCUMENT)
.next_break_fits(arena, NextBreakFitsMode::Disabled),
)
.nest(arena, INDENT);
let comments = self.pop_comments(location.end);
match printed_comments(arena, comments, false) {
None => tuple_doc
.append(arena, TRAILING_COMMA_BREAK_DOCUMENT)
.append(arena, CLOSE_PAREN_DOCUMENT)
.group(arena),
Some(comments) => tuple_doc
.append(arena, TRAILING_COMMA_BREAK_DOCUMENT.nest(arena, INDENT))
.append(arena, comments.nest(arena, INDENT))
.append(arena, LINE_DOCUMENT)
.append(arena, CLOSE_PAREN_DOCUMENT)
.force_break(arena),
}
}
fn documented_definition(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
definition: &'a UntypedDefinition,
) -> Document<'a, 'doc> {
let comments = self.doc_comments(arena, definition.location().start);
comments
.append(arena, self.definition(arena, definition).group(arena))
.group(arena)
}
fn doc_comments(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
limit: u32,
) -> Document<'a, 'doc> {
let mut comments = self.pop_doc_comments(limit).peekable();
match comments.peek() {
None => EMPTY_DOCUMENT,
Some(_) => arena
.join(
comments.map(|comment| match comment {
Some(comment) => {
DOC_COMMENT_DOCUMENT.append(arena, arena.zero_width_str(comment))
}
None => unreachable!("empty lines dropped by pop_doc_comments"),
}),
LINE_DOCUMENT,
)
.append(arena, LINE_DOCUMENT)
.force_break(arena),
}
}
fn type_ast_constructor(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
name: &'a TypeAstConstructorName,
arguments: &'a [TypeAst],
location: &SrcSpan,
) -> Document<'a, 'doc> {
let head = match name {
TypeAstConstructorName::Unqualified { name, .. } => name.to_doc(arena),
TypeAstConstructorName::Qualified { module, name, .. } => {
module.to_doc(arena).append(arena, DOT_DOCUMENT).append(
arena,
name.as_ref()
.map_or(EMPTY_DOCUMENT, |(name, _name_location)| name.to_doc(arena)),
)
}
};
if arguments.is_empty() {
head
} else {
head.append(arena, self.type_arguments(arena, arguments, location))
}
}
fn type_ast(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
type_: &'a TypeAst,
) -> Document<'a, 'doc> {
let comments = self.pop_comments(type_.location().start);
let type_ = match type_ {
TypeAst::Hole(TypeAstHole { name, .. }) => name.to_doc(arena),
TypeAst::Constructor(TypeAstConstructor {
name,
arguments,
location,
start_parentheses: _,
}) => self.type_ast_constructor(arena, name, arguments, location),
TypeAst::Fn(TypeAstFn {
arguments,
return_,
location,
}) => FN_DOCUMENT
.append(arena, self.type_arguments(arena, arguments, location))
.group(arena)
.append(arena, SPACE_RIGHT_ARROW_DOCUMENT)
.append(
arena,
BREAKABLE_SPACE_DOCUMENT
.append(arena, self.type_ast(arena, return_))
.group(arena)
.nest(arena, INDENT),
),
TypeAst::Var(TypeAstVar { name, .. }) => name.to_doc(arena),
TypeAst::Tuple(TypeAstTuple { elements, location }) => {
HASHTAG_DOCUMENT.append(arena, self.type_arguments(arena, elements, location))
}
};
commented(arena, type_.group(arena), comments)
}
fn type_arguments(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
arguments: &'a [TypeAst],
location: &SrcSpan,
) -> Document<'a, 'doc> {
let arguments = arguments
.iter()
.map(|type_| self.type_ast(arena, type_))
.collect_vec();
self.wrap_arguments(arena, arguments, location.end)
}
pub fn type_alias<A>(
&mut self,
arena: &'doc DocumentArena<'a, 'doc>,
alias: &'a TypeAlias<A>,
) -> Document<'a, 'doc> {
let TypeAlias {
alias: name,
parameters: arguments,
type_ast: type_,
publicity,
deprecation,
location,
name_location: _,
type_: _,
documentation: _,
} = alias;
let attributes = AttributesPrinter::new()
.set_deprecation(deprecation)
.set_internal(*publicity)
.to_doc(arena);
let head = docvec![
arena,
attributes,
pub_(*publicity),
TYPE_SPACE_DOCUMENT,
name
];
let head = if arguments.is_empty() {
head
} else {
let arguments = arguments.iter().map(|(_, e)| e.to_doc(arena)).collect_vec();
head.append(
arena,
self.wrap_arguments(arena, arguments, location.end)
.group(arena),
)
};
head.append(arena, SPACE_EQUAL_DOCUMENT).append(
arena,
LINE_DOCUMENT
.append(arena, self.type_ast(arena, type_))
.group(arena)
.nest(arena, INDENT),
)
}
fn argument_names(
&self,
arena: &'doc DocumentArena<'a, 'doc>,
argument_names: &'a ArgNames,
) -> Document<'a, 'doc> {
match argument_names {
ArgNames::Named { name, .. } | ArgNames::Discard { name, .. } => name.to_doc(arena),
ArgNames::LabelledDiscard { label, name, .. }
| ArgNames::NamedLabelled { label, name, .. } => {
docvec![arena, label, " ", name]
}
}