-
Notifications
You must be signed in to change notification settings - Fork 435
Expand file tree
/
Copy pathreason_pprint_ast.ml
More file actions
6636 lines (6104 loc) · 263 KB
/
Copy pathreason_pprint_ast.ml
File metadata and controls
6636 lines (6104 loc) · 263 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
(*
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
* Forked from OCaml, which is provided under the license below:
*
* Xavier Leroy, projet Cristal, INRIA Rocquencourt
*
* Copyright © 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Inria
*
* Permission is hereby granted, free of charge, to the Licensee obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense
* under any license of the Licensee's choice, and/or sell copies of the
* Software, subject to the following conditions:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 3. All advertising materials mentioning features or use of the Software
* must display the following acknowledgement: This product includes all or
* parts of the Caml system developed by Inria and its contributors.
* 4. Other than specified in clause 3, neither the name of Inria nor the
* names of its contributors may be used to endorse or promote products
* derived from the Software without specific prior written permission.
*
* Disclaimer
*
* This software is provided by Inria and contributors “as is” and any express
* or implied warranties, including, but not limited to, the implied
* warranties of merchantability and fitness for a particular purpose are
* disclaimed. in no event shall Inria or its contributors be liable for any
* direct, indirect, incidental, special, exemplary, or consequential damages
* (including, but not limited to, procurement of substitute goods or
* services; loss of use, data, or profits; or business interruption) however
* caused and on any theory of liability, whether in contract, strict
* liability, or tort (including negligence or otherwise) arising in any way
* out of the use of this software, even if advised of the possibility of such
* damage.
*
*)
(* TODO more fine-grained precedence pretty-printing *)
open Ast_404
open Asttypes
open Location
open Longident
open Parsetree
open Easy_format
open Reason_syntax_util
module Comment = Reason_comment
module Layout = Reason_layout
let source_map = Layout.source_map
exception NotPossible of string
let commaTrail = Layout.SepFinal (",", Reason_syntax_util.TrailingCommaMarker.string)
let commaSep = Layout.Sep (",")
type ruleInfoData = {
reducePrecedence: precedence;
shiftPrecedence: precedence;
}
and ruleCategory =
(* Printing will be parsed with very high precedence, so not much need to
worry about ensuring it will reduce correctly. In short, you can put
`FunctionApplication` content anywhere around an infix identifier without
wrapping in parens. For example `myFunc x y z` or `if x {y} else {z}`
The layout is kept in list form only to allow for elegant wrapping rules
to take into consideration the *number* of high precedence parsed items. *)
| FunctionApplication of Layout.t list
(* Care should be taken to ensure the rule that caused it to be parsed will
reduce again on the printed output - context should carefully consider
wrapping in parens according to the ruleInfoData. *)
| SpecificInfixPrecedence of ruleInfoData * resolvedRule
(* Not safe to include anywhere between infix operators without wrapping in
parens. This describes expressions like `fun x => x` which doesn't fit into
our simplistic algorithm for printing function applications separated by infix.
It might be possible to include these in between infix, but there are
tricky rules to determining when these must be guarded by parens (it
depends highly on context that is hard to reason about). It's so nuanced
that it's easier just to always wrap them in parens. *)
| PotentiallyLowPrecedence of Layout.t
(* Simple means it is clearly one token (such as (anything) or [anything] or identifier *)
| Simple of Layout.t
(* Represents a ruleCategory where the precedence has been resolved.
* The precedence of a ruleCategory gets resolved in `ensureExpression` or
* `ensureContainingRule`. The result is either a plain Layout.t (where
* parens probably have been applied) or an InfixTree containing the operator and
* a left & right resolvedRule. The latter indicates that the precedence has been resolved,
* but the actual formatting is deferred to a later stadium.
* Think `let x = foo |> f |> z |>`, which requires a certain formatting style when
* things break over multiple lines. *)
and resolvedRule =
| LayoutNode of Layout.t
| InfixTree of string * resolvedRule * resolvedRule
and associativity =
| Right
| Nonassoc
| Left
and precedenceEntryType =
| TokenPrecedence
| CustomPrecedence
and precedence =
| Token of string
| Custom of string
(* Describes the "fixity" of a token, and stores its *printed* representation
should it be rendered as infix/prefix (This rendering may be different than
how it is stored in the AST). *)
and tokenFixity =
(* Such as !simple_expr and ~!simple_expr. These function applications are
considered *almost* "simple" because they may be allowed anywhere a simple
expression is accepted, except for when on the left hand side of a
dot/send. *)
| AlmostSimplePrefix of string
| UnaryPlusPrefix of string
| UnaryMinusPrefix of string
| UnaryNotPrefix of string
| UnaryPostfix of string
| Infix of string
| Normal
(* Type which represents a resolvedRule's InfixTree flattened *)
type infixChain =
| InfixToken of string
| Layout of Layout.t
(* Helpers for dealing with extension nodes (%expr) *)
let expression_extension_sugar x =
if x.pexp_attributes <> [] then None
else match x.pexp_desc with
| Pexp_extension (name, PStr [{pstr_desc = Pstr_eval(expr, [])}])
when name.txt <> "bs.obj" ->
Some (name, expr)
| _ -> None
let expression_immediate_extension_sugar x =
match expression_extension_sugar x with
| None -> (None, x)
| Some (name, expr) ->
match expr.pexp_desc with
| Pexp_for _ | Pexp_while _ | Pexp_ifthenelse _
| Pexp_fun _ | Pexp_function _ | Pexp_newtype _
| Pexp_try _ | Pexp_match _ ->
(Some name, expr)
| _ -> (None, x)
let expression_not_immediate_extension_sugar x =
match expression_immediate_extension_sugar x with
| (Some _, _) -> None
| (None, _) -> expression_extension_sugar x
let add_extension_sugar keyword = function
| None -> keyword
| Some str -> keyword ^ "%" ^ str.txt
let string_equal : string -> string -> bool = (=)
let longident_same l1 l2 =
let rec equal l1 l2 =
match l1, l2 with
| Lident l1, Lident l2 -> string_equal l1 l2
| Ldot (path1, l1), Ldot (path2, l2) ->
equal path1 path2 && string_equal l1 l2
| Lapply (l11, l12), Lapply (l21, l22) ->
equal l11 l21 && equal l12 l22
| _ -> false
in
equal l1.txt l2.txt
(* A variant of List.for_all2 that returns false instead of failing on lists
of different size *)
let for_all2' pred l1 l2 =
List.length l1 = List.length l2 &&
List.for_all2 pred l1 l2
(*
Checks to see if two types are the same modulo the process of varification
which turns abstract types into type variables of the same name.
For example, [same_ast_modulo_varification] would consider (a => b) and ('a
=> 'b) to have the same ast. This is useful in recovering syntactic sugar
for explicit polymorphic types with locally abstract types.
Does not compare attributes, or extensions intentionally.
TODO: This has one more issue: We need to compare only accepting t1's type
variables, to be considered compatible with t2's type constructors - not the
other way around.
*)
let same_ast_modulo_varification_and_extensions t1 t2 =
let rec loop t1 t2 = match (t1.ptyp_desc, t2.ptyp_desc) with
(* Importantly, cover the case where type constructors (of the form [a])
are converted to type vars of the form ['a].
*)
| (Ptyp_constr({txt=Lident s1}, []), Ptyp_var s2) -> string_equal s1 s2
(* Now cover the case where type variables (of the form ['a]) are
converted to type constructors of the form [a].
*)
| (Ptyp_var s1, Ptyp_constr({txt=Lident s2}, [])) -> string_equal s1 s2
(* Now cover the typical case *)
| (Ptyp_constr(longident1, lst1), Ptyp_constr(longident2, lst2)) ->
longident_same longident1 longident2 &&
for_all2' loop lst1 lst2
| (Ptyp_any, Ptyp_any) -> true
| (Ptyp_var x1, Ptyp_var x2) -> string_equal x1 x2
| (Ptyp_arrow (label1, core_type1, core_type1'), Ptyp_arrow (label2, core_type2, core_type2')) ->
begin
match label1, label2 with
| Nolabel, Nolabel -> true
| Labelled s1, Labelled s2 -> string_equal s1 s2
| Optional s1, Optional s2 -> string_equal s1 s2
| _ -> false
end &&
loop core_type1 core_type2 &&
loop core_type1' core_type2'
| (Ptyp_tuple lst1, Ptyp_tuple lst2) -> for_all2' loop lst1 lst2
| (Ptyp_object (lst1, o1), Ptyp_object (lst2, o2)) ->
let tester = fun (s1, attrs1, t1) (s2, attrs2, t2) ->
string_equal s1 s2 &&
loop t1 t2
in
for_all2' tester lst1 lst2 && o1 = o2
| (Ptyp_class (longident1, lst1), Ptyp_class (longident2, lst2)) ->
longident_same longident1 longident2 &&
for_all2' loop lst1 lst2
| (Ptyp_alias(core_type1, string1), Ptyp_alias(core_type2, string2)) ->
loop core_type1 core_type2 &&
string_equal string1 string2
| (Ptyp_variant(row_field_list1, flag1, lbl_lst_option1), Ptyp_variant(row_field_list2, flag2, lbl_lst_option2)) ->
for_all2' rowFieldEqual row_field_list1 row_field_list2 &&
flag1 = flag2 &&
lbl_lst_option1 = lbl_lst_option2
| (Ptyp_poly (string_lst1, core_type1), Ptyp_poly (string_lst2, core_type2))->
for_all2' string_equal string_lst1 string_lst2 &&
loop core_type1 core_type2
| (Ptyp_package(longident1, lst1), Ptyp_package (longident2, lst2)) ->
longident_same longident1 longident2 &&
for_all2' testPackageType lst1 lst2
| (Ptyp_extension (s1, arg1), Ptyp_extension (s2, arg2)) ->
string_equal s1.txt s2.txt
| _ -> false
and testPackageType (lblLongIdent1, ct1) (lblLongIdent2, ct2) =
longident_same lblLongIdent1 lblLongIdent2 &&
loop ct1 ct2
and rowFieldEqual f1 f2 = match (f1, f2) with
| ((Rtag(label1, attrs1, flag1, lst1)), (Rtag (label2, attrs2, flag2, lst2))) ->
string_equal label1 label2 &&
flag1 = flag2 &&
for_all2' loop lst1 lst2
| (Rinherit t1, Rinherit t2) -> loop t1 t2
| _ -> false
in
loop t1 t2
let expandLocation pos ~expand:(startPos, endPos) =
{ pos with
loc_start = {
pos.loc_start with
Lexing.pos_cnum = pos.loc_start.Lexing.pos_cnum + startPos
};
loc_end = {
pos.loc_end with
Lexing.pos_cnum = pos.loc_end.Lexing.pos_cnum + endPos
}
}
(** Kinds of attributes *)
type attributesPartition = {
arityAttrs : attributes;
docAttrs : attributes;
stdAttrs : attributes;
jsxAttrs : attributes;
literalAttrs : attributes;
uncurried : bool
}
(** Partition attributes into kinds *)
let rec partitionAttributes ?(allowUncurry=true) attrs : attributesPartition =
match attrs with
| [] ->
{arityAttrs=[]; docAttrs=[]; stdAttrs=[]; jsxAttrs=[]; literalAttrs=[]; uncurried = false}
| (({txt = "bs"}, PStr []) as attr)::atTl ->
let partition = partitionAttributes ~allowUncurry atTl in
if allowUncurry then
{partition with uncurried = true}
else {partition with stdAttrs=attr::partition.stdAttrs}
| (({txt="JSX"; loc}, _) as jsx)::atTl ->
let partition = partitionAttributes ~allowUncurry atTl in
{partition with jsxAttrs=jsx::partition.jsxAttrs}
| (({txt="explicit_arity"; loc}, _) as arity_attr)::atTl
| (({txt="implicit_arity"; loc}, _) as arity_attr)::atTl ->
let partition = partitionAttributes ~allowUncurry atTl in
{partition with arityAttrs=arity_attr::partition.arityAttrs}
(*| (({txt="ocaml.text"; loc}, _) as doc)::atTl
| (({txt="ocaml.doc"; loc}, _) as doc)::atTl ->
let partition = partitionAttributes atTl in
{partition with docAttrs=doc::partition.docAttrs}*)
| (({txt="reason.raw_literal"; _}, _) as attr) :: atTl ->
let partition = partitionAttributes ~allowUncurry atTl in
{partition with literalAttrs=attr::partition.literalAttrs}
| atHd :: atTl ->
let partition = partitionAttributes ~allowUncurry atTl in
{partition with stdAttrs=atHd::partition.stdAttrs}
let extractStdAttrs attrs =
(partitionAttributes attrs).stdAttrs
let extract_raw_literal attrs =
let rec loop acc = function
| ({txt="reason.raw_literal"; loc},
PStr [{pstr_desc = Pstr_eval({pexp_desc = Pexp_constant(Pconst_string(text, None)); _}, _); _}])
:: rest ->
(Some text, List.rev_append acc rest)
| [] -> (None, List.rev acc)
| attr :: rest -> loop (attr :: acc) rest
in
loop [] attrs
let rec sequentialIfBlocks x =
match x with
| Some ({pexp_desc=Pexp_ifthenelse (e1, e2, els)}) -> (
let (nestedIfs, finalExpression) = (sequentialIfBlocks els) in
((e1, e2)::nestedIfs, finalExpression)
)
| Some e -> ([], Some e)
| None -> ([], None)
(*
TODO: IDE integration beginning with Vim:
- Create recovering version of parser that creates regions of "unknown"
content in between let sequence bindings (anything between semicolons,
really).
- Use Easy_format's "style" features to tag each known node.
- Turn those style annotations into editor highlight commands.
- Editors have a set of keys that retrigger the parsing/rehighlighting
process (typically newline/semi/close-brace).
- On every parsing/rehighlighting, this pretty printer can be used to
determine the highlighting of recovered regions, and the editor plugin can
relegate highlighting of malformed regions to the editor which mostly does
so based on token patterns.
*)
(*
@avoidSingleTokenWrapping
+-----------------------------+
|+------+ | Another label
|| let ( \ |
|| a | Label |
|| o | | The thing to the right of any label must be a
|| p _+ label RHS | list in order for it to wrap correctly. Lists
|| ): / v | will wrap if they need to/can. NON-lists will
|+--+ sixteenTuple = echoTuple|( wrap (indented) even though they're no lists!
+---/ 0,\---------------------+ To prevent a single item from wrapping, make
0, an unbreakable list via ensureSingleTokenSticksToLabel.
0
); In general, the best approach for indenting
let bindings is to keep building up labels from
the "let", always ensuring things that you want
to wrap will either be lists or guarded in
[ensureSingleTokenSticksToLabel].
If you must join several lists together (via =)
(or colon), ensure that joining is done via
[makeList] (which won't break), and that new
list is always appended to the left
hand side of the label. (So that the right hand
side may always be the untouched list that you want
to wrap with aligned closing).
Always make sure rhs of the label are the
Creating nested labels will preserve the original
indent location ("let" in this
case) as long as that nesting is
done on the left hand side of the labels.
*)
(*
Table 2.1. Precedence and associativity.
Precedence from highest to lowest: From RWOC, modified to include !=
---------------------------------------
Operator prefix Associativity
!..., ?..., ~... Prefix
., .(, .[ -
function application, constructor, assert, lazy Left associative
-, -. Prefix
**..., lsl, lsr, asr Right associative
*..., /..., %..., mod, land, lor, lxor Left associative
+..., -... Left associative
:: Right associative
@..., ^... Right associative
---
!= Left associative (INFIXOP0 listed first in lexer)
=..., <..., >..., |..., &..., $... Left associative (INFIXOP0)
=, <, > Left associative (IN SAME row as INFIXOP0 listed after)
---
&, && Right associative
or, || Right associative
, -
:=, = Right associative
if -
; Right associative
Note: It would be much better if &... and |... were in separate precedence
groups just as & and | are. This way, we could encourage custom infix
operators to use one of the two precedences and no one would be confused as
to precedence (leading &, | are intuitive). Two precedence classes for the
majority of infix operators is totally sufficient.
TODO: Free up the (&) operator from pervasives so it can be reused for
something very common such as string concatenation or list appending.
let x = tail & head;
*)
(* "Almost Simple Prefix" function applications parse with the rule:
`PREFIXOP simple_expr %prec below_DOT_AND_SHARP`, which in turn is almost
considered a "simple expression" (it's acceptable anywhere a simple
expression is except in a couple of edge cases.
"Unary Prefix" function applications parse with the rule:
`MINUS epxr %prec prec_unary_minus`, which in turn is considered an
"expression" (not simple). All unary operators are mapped into an identifier
beginning with "~".
TODO: Migrate all "almost simple prefix" to "unsary prefix". When `!`
becomes "not", then it will make more sense that !myFunc (arg) is parsed as
!(myFunc arg) instead of (!myFunc) arg.
*)
let almost_simple_prefix_symbols = [ '!'; '?'; '~'] ;;
(* Subset of prefix symbols that have special "unary precedence" *)
let unary_minus_prefix_symbols = [ "~-"; "~-."] ;;
let unary_plus_prefix_symbols = ["~+"; "~+." ] ;;
let infix_symbols = [ '='; '<'; '>'; '@'; '^'; '|'; '&'; '+'; '-'; '*'; '/';
'$'; '%'; '\\'; '#' ]
let special_infix_strings =
["asr"; "land"; "lor"; "lsl"; "lsr"; "lxor"; "mod"; "or"; ":="; "!="; "!=="]
let updateToken = "="
let requireIndentFor = [updateToken; ":="]
let namedArgSym = "~"
let getPrintableUnaryIdent s =
if List.mem s unary_minus_prefix_symbols ||
List.mem s unary_plus_prefix_symbols
then String.sub s 1 (String.length s -1)
else s
(* determines if the string is an infix string.
checks backwards, first allowing a renaming postfix ("_102") which
may have resulted from Pexp -> Texp -> Pexp translation, then checking
if all the characters in the beginning of the string are valid infix
characters. *)
let printedStringAndFixity = function
| s when List.mem s special_infix_strings -> Infix s
| "^" -> UnaryPostfix "^"
| s when List.mem s.[0] infix_symbols -> Infix s
(* Correctness under assumption that unary operators are stored in AST with
leading "~" *)
| s when List.mem s.[0] almost_simple_prefix_symbols &&
not (List.mem s special_infix_strings) &&
not (s = "?") -> (
(* What *kind* of prefix fixity? *)
if List.mem s unary_plus_prefix_symbols then
UnaryPlusPrefix (getPrintableUnaryIdent s)
else if List.mem s unary_minus_prefix_symbols then
UnaryMinusPrefix (getPrintableUnaryIdent s)
else if s = "!" then
UnaryNotPrefix "!"
else
AlmostSimplePrefix s
)
| _ -> Normal
(* Also, this doesn't account for != and !== being infixop!!! *)
let isSimplePrefixToken s = match printedStringAndFixity s with
| AlmostSimplePrefix _ | UnaryPostfix "^" -> true
| _ -> false
(* Convenient bank of information that represents the parser's precedence
rankings. Each instance describes a precedence table entry. The function
tests either a token string encountered by the parser, or (in the case of
`CustomPrecedence`) the string name of a custom rule precedence declared
using %prec *)
let rules = [
[
(TokenPrecedence, (fun s -> (Nonassoc, isSimplePrefixToken s)));
];
[
(CustomPrecedence, (fun s -> (Nonassoc, s = "prec_unary")));
];
(* Note the special case for "*\*", BARBAR, and LESSMINUS, AMPERSAND(s) *)
[
(TokenPrecedence, (fun s -> (Right, s = "**")));
(TokenPrecedence, (fun s -> (Right, String.length s > 1 && s.[0] == '*' && s.[1] == '\\' && s.[2] == '*')));
(TokenPrecedence, (fun s -> (Right, s = "lsl")));
(TokenPrecedence, (fun s -> (Right, s = "lsr")));
(TokenPrecedence, (fun s -> (Right, s = "asr")));
];
[
(TokenPrecedence, (fun s -> (Left, s.[0] == '*' && (String.length s == 1 || s != "*\\*"))));
(TokenPrecedence, (fun s -> (Left, s.[0] == '/')));
(TokenPrecedence, (fun s -> (Left, s.[0] == '%' )));
(TokenPrecedence, (fun s -> (Left, s = "mod" )));
(TokenPrecedence, (fun s -> (Left, s = "land" )));
(TokenPrecedence, (fun s -> (Left, s = "lor" )));
(TokenPrecedence, (fun s -> (Left, s = "lxor" )));
];
[
(* Even though these use the same *tokens* as unary plus/minus at parse
time, when unparsing infix -/+, the CustomPrecedence rule would be
incorrect to use, and instead we need a rule that models what infix
parsing would use - just the regular token precedence without a custom
precedence. *)
(TokenPrecedence,
(fun s -> (
Left,
if String.length s > 1 && s.[0] == '+' && s.[1] == '+' then
(*
Explicitly call this out as false because the other ++ case below
should have higher *lexing* priority. ++operator_chars* is considered an
entirely different token than +(non_plus_operator_chars)*
*)
false
else
s.[0] == '+'
)));
(TokenPrecedence ,(fun s -> (Left, s.[0] == '-' )));
(TokenPrecedence ,(fun s -> (Left, s = "!" )));
];
[
(TokenPrecedence, (fun s -> (Right, s = "::")));
];
[
(TokenPrecedence, (fun s -> (Right, s.[0] == '@')));
(TokenPrecedence, (fun s -> (Right, s.[0] == '^')));
(TokenPrecedence, (fun s -> (Right, String.length s > 1 && s.[0] == '+' && s.[1] == '+')));
];
[
(TokenPrecedence, (fun s -> (Left, s.[0] == '=' && not (s = "=") && not (s = "=>"))));
(TokenPrecedence, (fun s -> (Left, s.[0] == '<' && not (s = "<"))));
(TokenPrecedence, (fun s -> (Left, s.[0] == '>' && not (s = ">"))));
(TokenPrecedence, (fun s -> (Left, s = "!="))); (* Not preset in the RWO table! *)
(TokenPrecedence, (fun s -> (Left, s = "!=="))); (* Not preset in the RWO table! *)
(TokenPrecedence, (fun s -> (Left, s = "==")));
(TokenPrecedence, (fun s -> (Left, s = "===")));
(TokenPrecedence, (fun s -> (Left, s = "<")));
(TokenPrecedence, (fun s -> (Left, s = ">")));
(TokenPrecedence, (fun s -> (Left, s.[0] == '|' && not (s = "||"))));
(TokenPrecedence, (fun s -> (Left, s.[0] == '&' && not (s = "&") && not (s = "&&"))));
(TokenPrecedence, (fun s -> (Left, s.[0] == '$')));
];
[
(TokenPrecedence, (fun s -> (Right, s = "&")));
(TokenPrecedence, (fun s -> (Right, s = "&&")));
];
[
(TokenPrecedence, (fun s -> (Right, s = "or")));
(TokenPrecedence, (fun s -> (Right, s = "||")));
];
[
(* The Left shouldn't ever matter in practice. Should never get in a
situation with two consecutive infix ? - the colon saves us. *)
(TokenPrecedence, (fun s -> (Left, s = "?")));
];
[
(TokenPrecedence, (fun s -> (Right, s = ":=")));
];
[
(TokenPrecedence, (fun s -> (Right, s = updateToken)));
];
(* It's important to account for ternary ":" being lower precedence than "?" *)
[
(TokenPrecedence, (fun s -> (Right, s = ":")))
];
[
(TokenPrecedence, (fun s -> (Nonassoc, s = "=>")));
];
]
(* remove all prefixing backslashes, e.g. \=== becomes === *)
let without_prefixed_backslashes str =
if str = "" then str
else if String.get str 0 = '\\' then String.sub str 1 (String.length str - 1)
else str
let indexOfFirstMatch ~prec lst =
let rec aux n = function
| [] -> None
| [] :: tl -> aux (n + 1) tl
| ((kind, tester) :: hdTl) :: tl ->
match prec, kind with
| Token str, TokenPrecedence | Custom str, CustomPrecedence ->
let associativity, foundMatch = tester str in
if foundMatch
then Some (associativity, n)
else aux n (hdTl::tl)
| _ -> aux n (hdTl::tl)
in
aux 0 lst
(* Assuming it's an infix function application. *)
let precedenceInfo ~prec =
(* Removes prefixed backslashes in order to do proper conversion *)
let prec = match prec with
| Token str -> Token (without_prefixed_backslashes str)
| Custom str -> prec
in
indexOfFirstMatch ~prec rules
let isLeftAssociative ~prec = match precedenceInfo ~prec with
| None -> false
| Some (Left, _) -> true
| Some (Right, _) -> false
| Some (Nonassoc, _) -> false
let isRightAssociative ~prec = match precedenceInfo ~prec with
| None -> false
| Some (Right, _) -> true
| Some (Left, _) -> false
| Some (Nonassoc, _) -> false
let higherPrecedenceThan c1 c2 = match ((precedenceInfo c1), (precedenceInfo c2)) with
| (_, None)
| (None, _) ->
let (str1, str2) = match (c1, c2) with
| (Token s1, Token s2) -> ("Token " ^ s1, "Token " ^ s2)
| (Token s1, Custom s2) -> ("Token " ^ s1, "Custom " ^ s2)
| (Custom s1, Token s2) -> ("Custom " ^ s1, "Token " ^ s2)
| (Custom s1, Custom s2) -> ("Custom " ^ s1, "Custom " ^ s2)
in
raise (NotPossible ("Cannot determine precedence of two checks " ^ str1 ^ " vs. " ^ str2))
| (Some (_, p1), Some (_, p2)) -> p1 < p2
let printedStringAndFixityExpr = function
| {pexp_desc = Pexp_ident {txt=Lident l}} -> printedStringAndFixity l
| _ -> Normal
(* which identifiers are in fact operators needing parentheses *)
let needs_parens txt =
match printedStringAndFixity txt with
| Infix _ -> true
| UnaryPostfix _ -> true
| UnaryPlusPrefix _ -> true
| UnaryMinusPrefix _ -> true
| UnaryNotPrefix _ -> true
| AlmostSimplePrefix _ -> true
| Normal -> false
(* some infixes need spaces around parens to avoid clashes with comment
syntax. This isn't needed for comment syntax /* */ *)
let needs_spaces txt =
txt.[0]='*' || txt.[String.length txt - 1] = '*'
let rec orList = function (* only consider ((A|B)|C)*)
| {ppat_desc = Ppat_or (p1, p2)} -> (orList p1) @ (orList p2)
| x -> [x]
let override = function
| Override -> "!"
| Fresh -> ""
(* variance encoding: need to sync up with the [parser.mly] *)
let type_variance = function
| Invariant -> ""
| Covariant -> "+"
| Contravariant -> "-"
type construct =
[ `cons of expression list
| `list of expression list
| `nil
| `normal
| `simple of Longident.t
| `tuple ]
let view_expr x =
match x.pexp_desc with
| Pexp_construct ( {txt= Lident "()"; _},_) -> `tuple
| Pexp_construct ( {txt= Lident "[]"},_) -> `nil
| Pexp_construct ( {txt= Lident"::"},Some _) ->
let rec loop exp acc = match exp with
| {pexp_desc=Pexp_construct ({txt=Lident "[]"},_)} ->
(List.rev acc,true)
| {pexp_desc=
Pexp_construct ({txt=Lident "::"},
Some ({pexp_desc= Pexp_tuple([e1;e2])}))} ->
loop e2 (e1::acc)
| e -> (List.rev (e::acc),false) in
let (ls,b) = loop x [] in
if b
then `list ls
else `cons ls
| Pexp_construct (x,None) -> `simple x.txt
| _ -> `normal
let is_simple_list_expr x =
match view_expr x with
| `list _ | `cons _ -> true
| _ -> false
let is_simple_construct : construct -> bool = function
| `nil | `tuple | `list _ | `simple _ | `cons _ -> true
| `normal -> false
let uncurriedTable = Hashtbl.create 42
(* Determines if a list of expressions contains a single unit construct
* e.g. used to check: MyConstructor() -> exprList == [()]
* useful to determine if MyConstructor(()) should be printed as MyConstructor()
* *)
let is_single_unit_construct exprList =
match exprList with
| x::[] ->
let view = view_expr x in
(match view with
| `tuple -> true
| _ -> false)
| _ -> false
let detectTernary l = match l with
| [{
pc_lhs={ppat_desc=Ppat_construct ({txt=Lident "true"}, _)};
pc_guard=None;
pc_rhs=ifTrue
};
{
pc_lhs={ppat_desc=Ppat_construct ({txt=Lident "false"}, _)};
pc_guard=None;
pc_rhs=ifFalse
}] -> Some (ifTrue, ifFalse)
| _ -> None
type funcApplicationLabelStyle =
(* No attaching to the label, but if the entire application fits on one line,
the entire application will appear next to the label as you 'd expect. *)
| NeverWrapFinalItem
(* Attach the first term if there are exactly two terms involved in the
application.
let x = firstTerm (secondTerm_1 secondTerm_2) thirdTerm;
Ideally, we'd be able to attach all but the last argument into the label any
time all but the last term will fit - and *not* when (attaching all but
the last term isn't enough to prevent a wrap) - But there's no way to tell
ahead of time if it would prevent a wrap.
However, the number two is somewhat convenient. This models the
indentation that you'd prefer in non-curried syntax languages like
JavaScript, where application only ever has two terms.
*)
| WrapFinalListyItemIfFewerThan of int
type formatSettings = {
(* Whether or not to expect that the original parser that generated the AST
would have annotated constructor argument tuples with explicit arity to
indicate that they are multiple arguments. (True if parsed in original
OCaml AST, false if using Reason parser).
*)
constructorTupleImplicitArity: bool;
space: int;
(* For curried arguments in function *definitions* only: Number of [space]s
to offset beyond the [let] keyword. Default 1.
*)
listsRecordsIndent: int;
indentWrappedPatternArgs: int;
indentMatchCases: int;
(* Amount to indent in label-like constructs such as wrapped function
applications, etc - or even record fields. This is not the same concept as an
indented curried argument list. *)
indentAfterLabels: int;
(* Amount to indent after the opening brace of switch/try.
Here's an example of what it would look like w/ [trySwitchIndent = 2]:
Sticks the expression to the last item in a sequence in several [X | Y | Z
=> expr], and forces X, Y, Z to be split onto several lines. (Otherwise,
sticking to Z would result in hanging expressions). TODO: In the first case,
it's clear that we want patterns to have an "extra" indentation with matching
in a "match". Create extra config param to pass to [self#pattern] for extra
indentation in this one case.
switch x {
| TwoCombos
(HeresTwoConstructorArguments x y)
(HeresTwoConstructorArguments a b) =>
((a + b) + x) + y;
| Short
| AlsoHasARecord a b {x, y} => (
retOne,
retTwo
)
| AlsoHasARecord a b {x, y} =>
callMyFunction
withArg
withArg
withArg
withArg;
}
*)
trySwitchIndent: int;
(* In the case of two term function application (when flattened), the first
term should become part of the label, and the second term should be able to wrap
This doesn't effect n != 2.
[true]
let x = reallyShort allFitsOnOneLine;
let x = someFunction {
reallyLongObject: true,
thatWouldntFitOnThe: true,
firstLine: true
};
[false]
let x = reallyShort allFitsOnOneLine;
let x =
someFunction
{
reallyLongObject: true,
thatWouldntFitOnThe: true,
firstLine: true
};
*)
funcApplicationLabelStyle: funcApplicationLabelStyle;
funcCurriedPatternStyle: funcApplicationLabelStyle;
width: int;
assumeExplicitArity: bool;
constructorLists: string list;
}
let defaultSettings = {
constructorTupleImplicitArity = false;
space = 1;
listsRecordsIndent = 2;
indentWrappedPatternArgs = 2;
indentMatchCases = 2;
indentAfterLabels = 2;
trySwitchIndent = 0;
funcApplicationLabelStyle = WrapFinalListyItemIfFewerThan 3;
(* WrapFinalListyItemIfFewerThan is currently a bad idea for curried
arguments: It looks great in some cases:
let myFun (a:int) :(
int,
string
) => (a, "this is a");
But horrible in others:
let myFun
{
myField,
yourField
} :someReturnType => myField + yourField;
let myFun
{ // Curried arg wraps
myField,
yourField
} : ( // But the last is "listy" so it docks
int, // To the [let].
int,
int
) => myField + yourField;
We probably want some special listy label docking/wrapping mode for
curried function bindings.
*)
funcCurriedPatternStyle = NeverWrapFinalItem;
width = 80;
assumeExplicitArity = false;
constructorLists = [];
}
let configuredSettings = ref defaultSettings
let configure ~width ~assumeExplicitArity ~constructorLists = (
configuredSettings := {defaultSettings with width; assumeExplicitArity; constructorLists}
)
let createFormatter () =
let module Formatter = struct
let settings = !configuredSettings
(* How do we make
this a label?
/---------------------\
let myVal = (oneThing, {
field: [],
anotherField: blah
});
But in this case, this wider region a label?
/------------------------------------------------------\
let myVal = callSomeFunc (oneThing, {field: [], anotherField: blah}, {
boo: 'hi'
});
This is difficult. You must form a label from the preorder traversal of every
node - except the last encountered in the traversal. An easier heuristic is:
- The last argument to a functor application is expanded.
React.CreateClass SomeThing {
let render {props} => {
};
}
- The last argument to a function application is expanded on the same line.
- Only if it's not curried with another invocation.
-- Optionally: "only if everything else is an atom"
-- Optionally: "only if there are no other args"
React.createClass someThing {
render: fn x => y,
}
!!! NOT THIS
React.createClass someThing {
render: fn x => y,
}
somethingElse
*)
let isArityClear attrs =
(!configuredSettings).assumeExplicitArity ||
List.exists
(function
| ({txt="explicit_arity"; loc}, _) -> true
| _ -> false
)
attrs
let default_indent_body =
settings.listsRecordsIndent * settings.space
let makeList
(* Allows a fallback in the event that comments were interleaved with the
* list *)
?(newlinesAboveItems=0)
?(newlinesAboveComments=0)
?(newlinesAboveDocComments=0)
?listConfigIfCommentsInterleaved
?listConfigIfEolCommentsInterleaved
?(break=Layout.Never)
?(wrap=("", ""))
?(inline=(true, false))
?(sep=Layout.NoSep)
?(indent=default_indent_body)
?(sepLeft=true)
?(preSpace=false)
?(postSpace=false)
?(pad=(false,false))
lst =
let config =
{ Layout.
newlinesAboveItems; newlinesAboveComments; newlinesAboveDocComments;
listConfigIfCommentsInterleaved; listConfigIfEolCommentsInterleaved;
break; wrap; inline; sep; indent; sepLeft; preSpace; postSpace; pad;
}
in
Layout.Sequence (config, lst)