-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
js_layout_generator.ml
4108 lines (3930 loc) · 138 KB
/
js_layout_generator.ml
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
(*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
module Ast = Flow_ast
open Layout
module Trailing_commas = struct
type t =
| All (** Wherever possible (including function arguments). *)
| ES5 (** Where valid in ES5 (objects, arrays, etc.) *)
| Off (** No trailing commas *)
let enabled_for_function_params = function
| All -> true
| ES5 -> false
| Off -> false
let enabled_for_function_args = function
| All -> true
| ES5 -> true
| Off -> false
let enabled_for_objects = function
| All -> true
| ES5 -> true
| Off -> false
let enabled_for_arrays = function
| All -> true
| ES5 -> true
| Off -> false
let enabled_for_types = function
| All -> true
| ES5 -> true
| Off -> false
end
type opts = {
bracket_spacing: bool;
preserve_formatting: bool;
single_quotes: bool;
trailing_commas: Trailing_commas.t;
}
(* There are some cases where expressions must be wrapped in parens to eliminate
ambiguity. We pass whether we're in one of these special cases down through
the tree as we generate the layout. Note that these are only necessary as
long as the ambiguity can exist, so emitting any wrapper (like a paren or
bracket) is enough to reset the context back to Normal. *)
type expression_context = {
left: expression_context_left;
group: expression_context_group;
}
(** certain contexts where the left parenthesis matters. this is set back to [Normal_left]
as soon as we output something (see [context_after_token]). *)
and expression_context_left =
| Normal_left
| In_expression_statement (** [(function x(){});] would become a declaration w/o the paren **)
| In_tagged_template (** [(new a)``] would become [new (a``)] w/o the paren *)
| In_plus_op (** [x+(+y)] would become [(x++)y] w/o the paren *)
| In_minus_op (** [x-(-y)] would become [(x--)y] w/o the paren *)
and expression_context_group =
| Normal_group
| In_arrow_func (** [() => ({a: b})] would be a block w/ a labeled statement w/o the parens *)
| In_for_init (** [for ((x in y);;);] would become a for-in w/o the parens *)
let default_opts =
{
bracket_spacing = true;
preserve_formatting = false;
single_quotes = false;
trailing_commas = Trailing_commas.All;
}
let normal_context = { left = Normal_left; group = Normal_group }
(** Some contexts only matter to the left-most token. If we output some other
token, like an `=`, then we can reset the context. Note that all contexts
reset when wrapped in parens, brackets, braces, etc, so we don't need to call
this in those cases, we can just set it back to Normal. *)
let context_after_token ctxt = { ctxt with left = Normal_left }
(* JS layout helpers *)
let not_supported loc message = failwith (message ^ " at " ^ Loc.debug_to_string loc)
let with_semicolon node = fuse [node; Atom ";"]
let with_pretty_semicolon node = fuse [node; IfPretty (Atom ";", Empty)]
let wrap_in_parens ?(with_break = false) item =
if with_break then
group [wrap_and_indent ?break:(Some pretty_hardline) (Atom "(", Atom ")") [item]]
else
group [Atom "("; item; Atom ")"]
let wrap_in_parens_on_break item =
group [wrap_and_indent (IfBreak (Atom "(", Empty), IfBreak (Atom ")", Empty)) [item]]
let option f = function
| Some v -> f v
| None -> Empty
let hint f = function
| Ast.Type.Available v -> f v
| Ast.Type.Missing _ -> Empty
let deoptionalize l =
List.rev
(List.fold_left
(fun acc -> function
| None -> acc
| Some x -> x :: acc)
[]
l
)
(* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence *)
let max_precedence = 22
let min_precedence = 1
(* 0 means always parenthesize, which is not a precedence decision *)
let precedence_of_assignment = 3
let precedence_of_expression expr =
let module E = Ast.Expression in
match expr with
(* Expressions that don't involve operators have the highest priority *)
| (_, E.Array _)
| (_, E.Class _)
| (_, E.Function _)
| (_, E.Identifier _)
| (_, E.JSXElement _)
| (_, E.JSXFragment _)
| (_, E.Literal _)
| (_, E.Object _)
| (_, E.Super _)
| (_, E.TemplateLiteral _)
| (_, E.This _)
| (_, E.TypeCast _) ->
max_precedence
(* Expressions involving operators *)
| (_, E.Member _)
| (_, E.OptionalMember _)
| (_, E.MetaProperty _)
| (_, E.Call _)
| (_, E.OptionalCall _)
| (_, E.New { E.New.arguments = Some _; _ }) ->
21
| (_, E.New { E.New.arguments = None; _ }) -> 20
| (_, E.TaggedTemplate _)
| (_, E.Import _) ->
19
| (_, E.Update { E.Update.prefix = false; _ }) -> 18
| (_, E.Update { E.Update.prefix = true; _ })
| (_, E.Unary _) ->
17
| (_, E.Binary { E.Binary.operator; _ }) ->
begin
match operator with
| E.Binary.Exp -> 16
| E.Binary.Mult -> 15
| E.Binary.Div -> 15
| E.Binary.Mod -> 15
| E.Binary.Plus -> 14
| E.Binary.Minus -> 14
| E.Binary.LShift -> 13
| E.Binary.RShift -> 13
| E.Binary.RShift3 -> 13
| E.Binary.LessThan -> 12
| E.Binary.LessThanEqual -> 12
| E.Binary.GreaterThan -> 12
| E.Binary.GreaterThanEqual -> 12
| E.Binary.In -> 12
| E.Binary.Instanceof -> 12
| E.Binary.Equal -> 11
| E.Binary.NotEqual -> 11
| E.Binary.StrictEqual -> 11
| E.Binary.StrictNotEqual -> 11
| E.Binary.BitAnd -> 10
| E.Binary.Xor -> 9
| E.Binary.BitOr -> 8
end
| (_, E.Logical { E.Logical.operator = E.Logical.And; _ }) -> 7
| (_, E.Logical { E.Logical.operator = E.Logical.Or; _ }) -> 6
| (_, E.Logical { E.Logical.operator = E.Logical.NullishCoalesce; _ }) -> 5
| (_, E.Conditional _) -> 4
| (_, E.Assignment _) -> precedence_of_assignment
| (_, E.ArrowFunction _) ->
(* must be >= Assignment, so that `x = () => y = 123` doesn't need parens. It must be lower
than a Conditional so that `(() => {}) ? 1 : 2` doesn't become `() => ({} ? 1 : 2)` *)
precedence_of_assignment
| (_, E.Yield _) -> 2
| (_, E.Sequence _) -> 0
(* Expressions that always need parens (probably) *)
| (_, E.Comprehension _)
| (_, E.Generator _) ->
0
let definitely_needs_parens =
let module E = Ast.Expression in
let context_needs_parens ctxt expr =
match ctxt with
| { group = In_arrow_func; _ } ->
(* an object body expression in an arrow function needs parens to not
make it become a block with label statement. *)
begin
match expr with
| (_, E.Object _) -> true
| _ -> false
end
| { group = In_for_init; _ } ->
(* an `in` binary expression in the init of a for loop needs parens to not
make the for loop become a for-in loop. *)
begin
match expr with
| (_, E.Binary { E.Binary.operator = E.Binary.In; _ }) -> true
| _ -> false
end
| { left = In_expression_statement; _ } ->
(* functions (including async functions, but not arrow functions) and
classes must be wrapped in parens to avoid ambiguity with function and
class declarations. objects must be also, to not be confused with
blocks.
https://tc39.github.io/ecma262/#prod-ExpressionStatement *)
begin
match expr with
| (_, E.Class _)
| (_, E.Function _)
| (_, E.Object _)
| (_, E.Assignment { E.Assignment.left = (_, Ast.Pattern.Object _); _ }) ->
true
| _ -> false
end
| { left = In_tagged_template; _ } ->
begin
match expr with
| (_, E.Class _)
| (_, E.Function _)
| (_, E.New _)
| (_, E.Import _)
| (_, E.Object _) ->
true
| _ -> false
end
| { left = In_minus_op; _ } ->
begin
match expr with
| (_, E.Unary { E.Unary.operator = E.Unary.Minus; _ })
| (_, E.Update { E.Update.operator = E.Update.Decrement; prefix = true; _ }) ->
true
| _ -> false
end
| { left = In_plus_op; _ } ->
begin
match expr with
| (_, E.Unary { E.Unary.operator = E.Unary.Plus; _ })
| (_, E.Update { E.Update.operator = E.Update.Increment; prefix = true; _ }) ->
true
| _ -> false
end
| { left = Normal_left; group = Normal_group } -> false
in
fun ~precedence ctxt expr ->
precedence_of_expression expr < precedence || context_needs_parens ctxt expr
(* TODO: this only needs to be shallow; we don't need to walk into function
or class bodies, for example. *)
class contains_call_mapper result_ref =
object
inherit [Loc.t] Flow_ast_mapper.mapper
method! call _loc expr =
result_ref := true;
expr
end
let contains_call_expression expr =
(* TODO: use a fold *)
let result = ref false in
let _ = (new contains_call_mapper result)#expression expr in
!result
type statement_or_comment =
| Statement of (Loc.t, Loc.t) Ast.Statement.t
| Comment of Loc.t Ast.Comment.t
let better_quote =
let rec count (double, single) str i =
if i < 0 then
(double, single)
else
let acc =
match str.[i] with
| '"' -> (succ double, single)
| '\'' -> (double, succ single)
| _ -> (double, single)
in
count acc str (pred i)
in
fun ~prefer_single_quotes str ->
let (double_count, single_count) = count (0, 0) str (String.length str - 1) in
let double = ("\"", double_count) in
let single = ("'", single_count) in
let (preferred, alternate) =
if prefer_single_quotes then
(single, double)
else
(double, single)
in
if snd preferred > snd alternate then
fst alternate
else
fst preferred
let utf8_escape =
(* a null character can be printed as \x00 or \0. but if the next character is an ASCII digit,
then using \0 would create \01 (for example), which is a legacy octal 1. so, rather than simply
fold over the codepoints, we have to look ahead at the next character as well. *)
let lookahead_fold_wtf_8 :
?pos:int ->
?len:int ->
(next:(int * Wtf8.codepoint) option -> 'a -> int -> Wtf8.codepoint -> 'a) ->
'a ->
string ->
'a =
let lookahead ~f (prev, buf) i cp =
let next = Some (i, cp) in
let buf =
match prev with
| Some (prev_i, prev_cp) -> f ~next buf prev_i prev_cp
| None -> buf
in
(next, buf)
in
fun ?pos ?len f acc str ->
str |> Wtf8.fold_wtf_8 ?pos ?len (lookahead ~f) (None, acc) |> fun (last, acc) ->
match last with
| Some (i, cp) -> f ~next:None acc i cp
| None -> acc
in
let f ~quote ~next buf _i = function
| Wtf8.Malformed -> buf
| Wtf8.Point cp ->
begin
match cp with
(* SingleEscapeCharacter: http://www.ecma-international.org/ecma-262/6.0/#table-34 *)
| 0x0 ->
let zero =
match next with
| Some (_i, Wtf8.Point n) when 0x30 <= n && n <= 0x39 -> "\\x00"
| _ -> "\\0"
in
Buffer.add_string buf zero;
buf
| 0x8 ->
Buffer.add_string buf "\\b";
buf
| 0x9 ->
Buffer.add_string buf "\\t";
buf
| 0xA ->
Buffer.add_string buf "\\n";
buf
| 0xB ->
Buffer.add_string buf "\\v";
buf
| 0xC ->
Buffer.add_string buf "\\f";
buf
| 0xD ->
Buffer.add_string buf "\\r";
buf
| 0x22 when quote = "\"" ->
Buffer.add_string buf "\\\"";
buf
| 0x27 when quote = "'" ->
Buffer.add_string buf "\\'";
buf
| 0x5C ->
Buffer.add_string buf "\\\\";
buf
(* printable ascii *)
| n when 0x1F < n && n < 0x7F ->
Buffer.add_char buf (Char.unsafe_chr cp);
buf
(* basic multilingual plane, 2 digits *)
| n when n < 0x100 ->
Printf.bprintf buf "\\x%02x" n;
buf
(* basic multilingual plane, 4 digits *)
| n when n < 0x10000 ->
Printf.bprintf buf "\\u%04x" n;
buf
(* supplemental planes *)
| n ->
(* ES5 does not support the \u{} syntax, so print surrogate pairs
"\ud83d\udca9" instead of "\u{1f4A9}". if we add a flag to target
ES6, we should change this. *)
let n' = n - 0x10000 in
let hi = 0xD800 lor (n' lsr 10) in
let lo = 0xDC00 lor (n' land 0x3FF) in
Printf.bprintf buf "\\u%4x" hi;
Printf.bprintf buf "\\u%4x" lo;
buf
end
in
fun ~quote str ->
str |> lookahead_fold_wtf_8 (f ~quote) (Buffer.create (String.length str)) |> Buffer.contents
let is_single_linebreak prev next = Loc.(next.start.line = prev._end.line + 1)
let is_multi_linebreak prev next = Loc.(next.start.line > prev._end.line + 1)
let layout_comment loc comment =
let open Ast.Comment in
SourceLocation
( loc,
match comment with
| { kind = Line; text; _ } -> fuse [Atom "//"; Atom text; hardline]
| { kind = Block; text; _ } -> fuse [Atom "/*"; Atom text; Atom "*/"]
)
let layout_from_leading_comment (loc, comment) next_loc =
let open Ast.Comment in
let layout_comment = layout_comment loc comment in
match next_loc with
| None -> layout_comment
| Some next_loc ->
let is_single_linebreak = is_single_linebreak loc next_loc in
let is_multi_linebreak = is_multi_linebreak loc next_loc in
(match comment with
| { kind = Line; _ } when is_multi_linebreak -> fuse [layout_comment; pretty_hardline]
| { kind = Line; _ } -> layout_comment
| { kind = Block; _ } when is_multi_linebreak ->
fuse [layout_comment; pretty_hardline; pretty_hardline]
| { kind = Block; _ } when is_single_linebreak -> fuse [layout_comment; pretty_hardline]
| { kind = Block; _ } -> fuse [layout_comment; pretty_space])
let layout_from_trailing_comment (loc, comment) (prev_loc, prev_comment) =
let open Ast.Comment in
let is_single_linebreak = is_single_linebreak prev_loc loc in
let is_multi_linebreak = is_multi_linebreak prev_loc loc in
let layout_comment = layout_comment loc comment in
match prev_comment with
| Some { kind = Line; _ } when is_multi_linebreak -> fuse [pretty_hardline; layout_comment]
| Some { kind = Line; _ } -> layout_comment
| Some { kind = Block; _ } when is_multi_linebreak ->
fuse [pretty_hardline; pretty_hardline; layout_comment]
| Some { kind = Block; _ } when is_single_linebreak -> fuse [pretty_hardline; layout_comment]
| Some { kind = Block; _ } -> fuse [pretty_space; layout_comment]
| None when is_multi_linebreak -> fuse [pretty_hardline; pretty_hardline; layout_comment]
| None when is_single_linebreak -> fuse [pretty_hardline; layout_comment]
| None -> fuse [pretty_space; layout_comment]
let layout_from_leading_comments comments node_loc =
let rec inner = function
| [] -> []
| [comment] -> [layout_from_leading_comment comment node_loc]
| comment :: ((next_loc, _) :: _ as rest) ->
layout_from_leading_comment comment (Some next_loc) :: inner rest
in
inner comments
let layout_from_trailing_comments comments node_loc =
let rec inner prev_comment = function
| [] -> []
| (loc, comment) :: rest ->
layout_from_trailing_comment (loc, comment) prev_comment :: inner (loc, Some comment) rest
in
inner node_loc comments
let layout_node_with_comments current_loc comments layout_node =
let { Ast.Syntax.leading; trailing; _ } = comments in
let preceding = layout_from_leading_comments leading (Some current_loc) in
let following = layout_from_trailing_comments trailing (current_loc, None) in
Concat (List.concat [preceding; [layout_node]; following])
let layout_node_with_comments_opt current_loc comments layout_node =
match comments with
| Some c -> layout_node_with_comments current_loc c layout_node
| None -> layout_node
let source_location_with_comments ?comments (current_loc, layout_node) =
let layout = SourceLocation (current_loc, layout_node) in
match comments with
| Some comments -> layout_node_with_comments current_loc comments layout
| None -> layout
let internal_comments = function
| None
| Some { Ast.Syntax.internal = []; _ } ->
None
| Some { Ast.Syntax.internal = (first_loc, _) :: _ as internal; _ } ->
Some (first_loc, (None, None), Concat (layout_from_leading_comments internal None))
(* Given a set of comment bounds, determine what separator should be inserted before the
comments to preserve whether the first comment starts on a new line.
- If there are no leading comments return the specified separator.
- If the first leading comment starts on a new line, ignore the specified separator and
return a hard line break.
- If the first leading comment does not start on a new line, return the optional same_line
separator, otherwise return the no_comment separator. *)
let comment_aware_separator ?(same_line = None) ~no_comment comment_bounds =
match comment_bounds with
| (Some (_, { Ast.Comment.on_newline = true; _ }), _) -> pretty_hardline
| (Some (_, { Ast.Comment.on_newline = false; _ }), _) ->
(match same_line with
| None -> no_comment
| Some sep -> sep)
| _ -> no_comment
let identifier_with_comments current_loc name comments =
let node = Identifier (current_loc, name) in
match comments with
| Some comments -> layout_node_with_comments current_loc comments node
| None -> node
(* Generate JS layouts *)
let rec program
?(opts = default_opts)
~preserve_docblock
~checksum
(loc, { Ast.Program.statements; all_comments; _ }) =
let nodes =
if preserve_docblock && all_comments <> [] then
let (directives, statements) = Flow_ast_utils.partition_directives statements in
let all_comments =
match statements with
| [] -> all_comments
| (loc, _) :: _ -> Comment_utils.comments_before_loc loc all_comments
in
[
combine_directives_and_comments ~opts directives all_comments;
fuse (statement_list ~opts statements);
]
else
[fuse (statement_list ~opts statements)]
in
let nodes = group [join pretty_hardline nodes] in
let nodes = maybe_embed_checksum nodes checksum in
let loc = { loc with Loc.start = { Loc.line = 1; column = 0 } } in
source_location_with_comments (loc, nodes)
and program_simple ?(opts = default_opts) (loc, { Ast.Program.statements; _ }) =
let nodes = group [fuse (statement_list ~opts statements)] in
let loc = { loc with Loc.start = { Loc.line = 1; column = 0 } } in
source_location_with_comments (loc, nodes)
and combine_directives_and_comments ~opts directives comments : Layout.layout_node =
let directives = Base.List.map ~f:(fun ((loc, _) as x) -> (loc, Statement x)) directives in
let comments = Base.List.map ~f:(fun ((loc, _) as x) -> (loc, Comment x)) comments in
let merged = List.merge (fun (a, _) (b, _) -> Loc.compare a b) directives comments in
let nodes =
Base.List.map
~f:(function
| (loc, Statement s) ->
(loc, Comment_attachment.statement_comment_bounds s, statement ~opts s)
| (loc, Comment c) -> (loc, (None, None), comment c))
merged
in
fuse (list_with_newlines nodes)
and maybe_embed_checksum nodes checksum =
match checksum with
| Some checksum ->
let comment = Printf.sprintf "/* %s */" checksum in
fuse [nodes; Newline; Atom comment]
| None -> nodes
and comment (loc, comment) =
let open Ast.Comment in
source_location_with_comments
( loc,
match comment with
| { kind = Block; text; _ } -> fuse [Atom "/*"; Atom text; Atom "*/"]
| { kind = Line; text; _ } -> fuse [Atom "//"; Atom text; Newline]
)
(**
* Renders a statement
*
* Set `pretty_semicolon` when a semicolon is only required in pretty mode. For example,
* a semicolon is never required on the last statement of a statement list, so we can set
* `~pretty_semicolon:true` to only print the unnecessary semicolon in pretty mode.
*)
and statement ?(pretty_semicolon = false) ~opts (root_stmt : (Loc.t, Loc.t) Ast.Statement.t) =
let (loc, stmt) = root_stmt in
let module E = Ast.Expression in
let module S = Ast.Statement in
let with_semicolon =
if pretty_semicolon then
with_pretty_semicolon
else
with_semicolon
in
source_location_with_comments
( loc,
match stmt with
| S.Empty { S.Empty.comments } -> layout_node_with_comments_opt loc comments (Atom ";")
| S.Debugger { S.Debugger.comments } ->
layout_node_with_comments_opt loc comments @@ with_semicolon (Atom "debugger")
| S.Block b -> block ~opts (loc, b)
| S.Expression { S.Expression.expression = expr; directive = _; comments } ->
let ctxt = { normal_context with left = In_expression_statement } in
layout_node_with_comments_opt loc comments
@@ with_semicolon (expression_with_parens ~precedence:0 ~ctxt ~opts expr)
| S.If { S.If.test; consequent; alternate; comments } ->
layout_node_with_comments_opt
loc
comments
begin
match alternate with
| Some (loc, ({ S.If.Alternate.body; comments } as alternate)) ->
let alternate_separator =
comment_aware_separator
~no_comment:pretty_space
(Comment_attachment.if_alternate_statement_comment_bounds loc alternate)
in
fuse
[
group
[
statement_with_test "if" (expression ~opts test);
statement_after_test ~opts consequent;
];
alternate_separator;
layout_node_with_comments_opt loc comments
@@ fuse_with_space [Atom "else"; statement ~opts ~pretty_semicolon body];
]
| None ->
group
[
statement_with_test "if" (expression ~opts test);
statement_after_test ~opts ~pretty_semicolon consequent;
]
end
| S.Labeled { S.Labeled.label; body; comments } ->
layout_node_with_comments_opt
loc
comments
(fuse [identifier label; Atom ":"; pretty_space; statement ~opts body])
| S.Break { S.Break.label; comments } ->
let s_break = Atom "break" in
layout_node_with_comments_opt loc comments
@@ with_semicolon
(match label with
| Some l -> fuse [s_break; space; identifier l]
| None -> s_break)
| S.Continue { S.Continue.label; comments } ->
let s_continue = Atom "continue" in
layout_node_with_comments_opt loc comments
@@ with_semicolon
(match label with
| Some l -> fuse [s_continue; space; identifier l]
| None -> s_continue)
| S.With { S.With._object; body; comments } ->
layout_node_with_comments_opt
loc
comments
(fuse
[
statement_with_test "with" (expression ~opts _object); statement_after_test ~opts body;
]
)
| S.Switch { S.Switch.discriminant; cases; comments; exhaustive_out = _ } ->
let case_nodes =
let rec helper acc =
let open Comment_attachment in
function
| [] -> List.rev acc
| [((loc, _) as case)] ->
let case =
(loc, switch_case_comment_bounds case, switch_case ~opts ~last:true case)
in
List.rev (case :: acc)
| ((loc, _) as case) :: rest ->
let case =
(loc, switch_case_comment_bounds case, switch_case ~opts ~last:false case)
in
helper (case :: acc) rest
in
helper [] cases |> list_with_newlines
in
let cases_node =
wrap_and_indent ~break:pretty_hardline (Atom "{", Atom "}") [fuse case_nodes]
in
layout_node_with_comments_opt
loc
comments
(fuse
[
statement_with_test "switch" (expression ~opts discriminant); pretty_space; cases_node;
]
)
| S.Return { S.Return.argument; comments; return_out = _ } ->
let s_return = Atom "return" in
layout_node_with_comments_opt loc comments
@@ with_semicolon
(match argument with
| Some arg ->
let arg =
match arg with
| (_, E.Logical _)
| (_, E.Binary _)
| (_, E.Sequence _)
| (_, E.JSXElement _) ->
wrap_in_parens_on_break (expression ~opts arg)
| _ ->
(* If the return argument has a leading comment then we must wrap the argument
and its comments in parens. Otherwise, the comments could push the argument
to the next line, meaning the return would be parsed without an argument. *)
let (leading, _) = Comment_attachment.expression_comment_bounds arg in
let arg = expression ~opts arg in
if leading = None then
arg
else
wrap_in_parens_on_break arg
in
fuse_with_space [s_return; arg]
| None -> s_return)
| S.Throw { S.Throw.argument; comments } ->
layout_node_with_comments_opt loc comments
@@ with_semicolon
(fuse_with_space [Atom "throw"; wrap_in_parens_on_break (expression ~opts argument)])
| S.Try { S.Try.block = b; handler; finalizer; comments } ->
layout_node_with_comments_opt
loc
comments
(fuse
[
Atom "try";
pretty_space;
block ~opts b;
(match handler with
| Some (loc, { S.Try.CatchClause.param; body; comments }) ->
source_location_with_comments
?comments
( loc,
match param with
| Some p ->
fuse
[
pretty_space;
statement_with_test "catch" (pattern ~ctxt:normal_context ~opts p);
pretty_space;
block ~opts body;
]
| None -> fuse [pretty_space; Atom "catch"; pretty_space; block ~opts body]
)
| None -> Empty);
(match finalizer with
| Some b -> fuse [pretty_space; Atom "finally"; pretty_space; block ~opts b]
| None -> Empty);
]
)
| S.While { S.While.test; body; comments } ->
layout_node_with_comments_opt
loc
comments
(fuse
[
statement_with_test "while" (expression ~opts test);
statement_after_test ~opts ~pretty_semicolon body;
]
)
| S.DoWhile { S.DoWhile.body; test; comments } ->
layout_node_with_comments_opt loc comments
@@ with_semicolon
(fuse
[
fuse_with_space [Atom "do"; statement ~opts body];
pretty_space;
Atom "while";
pretty_space;
group [wrap_and_indent (Atom "(", Atom ")") [expression ~opts test]];
]
)
| S.For { S.For.init; test; update; body; comments } ->
layout_node_with_comments_opt loc comments
@@ fuse
[
statement_with_test
"for"
(join
(fuse [Atom ";"; pretty_line])
[
begin
match init with
| Some (S.For.InitDeclaration decl) ->
let ctxt = { normal_context with group = In_for_init } in
variable_declaration ~ctxt ~opts decl
| Some (S.For.InitExpression expr) ->
let ctxt = { normal_context with group = In_for_init } in
expression_with_parens ~precedence:0 ~ctxt ~opts expr
| None -> Empty
end;
begin
match test with
| Some expr -> expression ~opts expr
| None -> Empty
end;
begin
match update with
| Some expr -> expression ~opts expr
| None -> Empty
end;
]
);
statement_after_test ~opts ~pretty_semicolon body;
]
| S.ForIn { S.ForIn.left; right; body; each; comments } ->
layout_node_with_comments_opt loc comments
@@ fuse
[
Atom "for";
( if each then
fuse [space; Atom "each"]
else
Empty
);
pretty_space;
wrap_in_parens
(fuse_with_space
[
begin
match left with
| S.ForIn.LeftDeclaration decl -> variable_declaration ~opts decl
| S.ForIn.LeftPattern patt -> pattern ~opts patt
end;
Atom "in";
expression ~opts right;
]
);
statement_after_test ~opts ~pretty_semicolon body;
]
| S.FunctionDeclaration func -> function_ ~opts loc func
| S.VariableDeclaration decl ->
let semicolon =
if pretty_semicolon then
Some (IfPretty (Atom ";", Empty))
else
Some (Atom ";")
in
variable_declaration ?semicolon ~opts (loc, decl)
| S.ClassDeclaration class_ -> class_base ~opts loc class_
| S.EnumDeclaration enum -> enum_declaration ~def:(Atom "enum") loc enum
| S.ForOf { S.ForOf.left; right; body; await; comments } ->
layout_node_with_comments_opt loc comments
@@ fuse
[
Atom "for";
( if await then
fuse [space; Atom "await"]
else
Empty
);
pretty_space;
wrap_in_parens
(fuse_with_space
[
begin
match left with
| S.ForOf.LeftDeclaration decl -> variable_declaration ~opts decl
| S.ForOf.LeftPattern
( ( _,
Ast.Pattern.Identifier
{
Ast.Pattern.Identifier.name =
(_, { Ast.Identifier.name = "async"; _ });
annot = Ast.Type.Missing _;
_;
}
) as patt
) ->
wrap_in_parens (pattern ~opts patt)
| S.ForOf.LeftPattern patt -> pattern ~opts patt
end;
Atom "of";
expression ~opts right;
]
);
statement_after_test ~opts ~pretty_semicolon body;
]
| S.ImportDeclaration import -> import_declaration ~opts loc import
| S.ExportNamedDeclaration export -> export_declaration ~opts loc export
| S.ExportDefaultDeclaration export -> export_default_declaration ~opts loc export
| S.TypeAlias typeAlias -> type_alias ~opts ~declare:false loc typeAlias
| S.OpaqueType opaqueType -> opaque_type ~opts ~declare:false loc opaqueType
| S.InterfaceDeclaration interface -> interface_declaration ~opts loc interface
| S.DeclareClass interface -> declare_class ~opts loc interface
| S.DeclareEnum enum -> declare_enum loc enum
| S.DeclareFunction func -> declare_function ~opts loc func
| S.DeclareInterface interface -> declare_interface ~opts loc interface
| S.DeclareVariable var -> declare_variable ~opts loc var
| S.DeclareModuleExports exports -> declare_module_exports ~opts loc exports
| S.DeclareModule m -> declare_module ~opts loc m
| S.DeclareTypeAlias typeAlias -> type_alias ~opts ~declare:true loc typeAlias
| S.DeclareOpaqueType opaqueType -> opaque_type ~opts ~declare:true loc opaqueType
| S.DeclareExportDeclaration export -> declare_export_declaration ~opts loc export
)
(* The beginning of a statement that does a "test", like `if (test)` or `while (test)` *)
and statement_with_test name test =
group [Atom name; pretty_space; wrap_and_indent (Atom "(", Atom ")") [test]]
(* A statement following a "test", like the `statement` in `if (expr) statement` or
`for (...) statement`. Better names for this are welcome! *)
and statement_after_test ?pretty_semicolon ~opts = function
| (_, Ast.Statement.Empty _) as stmt -> statement ?pretty_semicolon ~opts stmt
| (_, Ast.Statement.Block _) as stmt ->
fuse [pretty_space; statement ?pretty_semicolon ~opts stmt]
| stmt -> Indent (fuse [pretty_line; statement ?pretty_semicolon ~opts stmt])
and expression ?(ctxt = normal_context) ~opts (root_expr : (Loc.t, Loc.t) Ast.Expression.t) =
let (loc, expr) = root_expr in
let module E = Ast.Expression in
let precedence = precedence_of_expression (loc, expr) in
source_location_with_comments
( loc,
match expr with
| E.This { E.This.comments } -> layout_node_with_comments_opt loc comments (Atom "this")
| E.Super { E.Super.comments } -> layout_node_with_comments_opt loc comments (Atom "super")
| E.Array { E.Array.elements; comments } ->
let element_loc = function
| E.Array.Hole loc -> loc
| E.Array.Expression (loc, _) -> loc
| E.Array.Spread (loc, _) -> loc
in
let has_trailing_hole =
match List.rev elements with
| E.Array.Hole _ :: _ -> true
| _ -> false
in
let elements =
List.map
(fun element ->
let loc = element_loc element in
( loc,
Comment_attachment.array_element_comment_bounds loc element,
array_element ~ctxt:normal_context ~opts element
))
elements
in
let elements_layout =
list_with_newlines ~sep:(Atom ",") ~sep_linebreak:pretty_line ~skip_empty:false elements
in
(* If the last element is a hole, then we need to manually insert a trailing `,` even in
ugly mode. Otherwise add a trailing comma only in pretty mode. *)
let trailing_comma =
if has_trailing_hole then
Atom ","
else if elements <> [] && Trailing_commas.enabled_for_arrays opts.trailing_commas then
if_break (Atom ",") Empty
else
Empty
in
let elements_layout = elements_layout @ [trailing_comma] in
let elements_layout = list_add_internal_comments elements elements_layout comments in
layout_node_with_comments_opt loc comments
@@ group [wrap_and_indent (Atom "[", Atom "]") elements_layout]
| E.Object { E.Object.properties; comments } ->
let prop_loc = function
| E.Object.Property (loc, _) -> loc
| E.Object.SpreadProperty (loc, _) -> loc
in
let num_props = List.length properties in
let internal_comments =
match internal_comments comments with
| None -> []
| Some comments -> [comments]
in
let props =
Base.List.mapi
~f:(fun i prop ->
(* Add trailing comma to last property *)
let prop_layout =
if
i = num_props - 1
&& internal_comments = []
&& Trailing_commas.enabled_for_objects opts.trailing_commas
then
fuse [object_property ~opts prop; if_break (Atom ",") Empty]
else
object_property ~opts prop
in
(prop_loc prop, Comment_attachment.object_property_comment_bounds prop, prop_layout))
properties
in
let props = props @ internal_comments in