-
Notifications
You must be signed in to change notification settings - Fork 41
/
Chiron.fs
2003 lines (1651 loc) · 86.9 KB
/
Chiron.fs
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
namespace Chiron
type JsonMemberType =
| Object
| Array
| String
| Number
| Bool
| Null
type [<StructuralEquality;NoComparison>] Json =
| Object of properties: JsonObject
| Array of elements: Json list
| String of string
| Number of number:string
| True
| False
| Null
and [<CustomEquality;NoComparison>] JsonObject =
| WriteObject of propList: (string * Json) list
| ReadObject of propList: (string * Json) list * propMap: Map<string,Json>
override x.Equals(o) =
match o with
| :? JsonObject as y -> (x :> System.IEquatable<JsonObject>).Equals(y)
| _ -> false
override x.GetHashCode() =
match x with
| WriteObject ps -> Map.ofList (List.rev ps) |> hash
| ReadObject (_, mps) -> mps |> hash
interface System.IEquatable<JsonObject> with
member x.Equals(y) =
match x, y with
| WriteObject xps, WriteObject yps -> Map.ofList (List.rev xps) = Map.ofList (List.rev yps)
| ReadObject (_, mps), WriteObject ps -> Map.ofList (List.rev ps) = mps
| WriteObject ps, ReadObject (_, mps) -> Map.ofList (List.rev ps) = mps
| ReadObject (_, xps), ReadObject (_, yps) -> xps = yps
[<RequireQualifiedAccess>]
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module JsonMemberType =
let ofJson = function
| Json.Object _ -> JsonMemberType.Object
| Json.Array _ -> JsonMemberType.Array
| Json.String _ -> JsonMemberType.String
| Json.Number _ -> JsonMemberType.Number
| Json.True -> JsonMemberType.Bool
| Json.False -> JsonMemberType.Bool
| Json.Null -> JsonMemberType.Null
let describe = function
| JsonMemberType.Object -> "an object"
| JsonMemberType.Array -> "an array"
| JsonMemberType.String -> "a string"
| JsonMemberType.Number -> "a number"
| JsonMemberType.Bool -> "a boolean"
| JsonMemberType.Null -> "null"
type JsonFailureTag =
| PropertyTag of propertyName: string
| IndexTag of index: uint32
| ChoiceTag of choice: uint32
type JsonFailureReason =
| OtherError of err: exn
| PropertyNotFound of name: string
| TypeMismatch of expected: JsonMemberType * actual: JsonMemberType
| DeserializationError of targetType: System.Type * err: exn
| InvalidJson of err: string
| NoInput
type JsonFailure =
| Tagged of tag: JsonFailureTag * jFail: JsonFailure
| SingleFailure of jFail: JsonFailureReason
| PairedFailures of leftFail: JsonFailure * rightFail: JsonFailure
| MultipleFailures of jFails: JsonFailure list
type ChironErrorPolicy =
| StopOnFirstError
| ContinueOnError
type JsonResult<'a> =
| JPass of 'a
| JFail of JsonFailure
[<RequireQualifiedAccess>]
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module JsonFailureTag =
let toString = function
| PropertyTag p -> p
| IndexTag i -> System.String.Concat ("[", string i, "]")
| ChoiceTag c -> System.String.Concat ("(Choice #", string (c + 1u), ")")
let toTagPathString prefixO tag =
match prefixO, tag with
| Some prefix, PropertyTag p -> System.String.Concat (prefix, ".", p)
| Some prefix, IndexTag i -> System.String.Concat (prefix, "[", string i, "]")
| Some prefix, ChoiceTag c -> System.String.Concat (prefix, "(Choice #", string (c + 1u), ")")
| None, _ -> toString tag
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module JsonFailureReason =
let toString = function
| OtherError e -> string e
| PropertyNotFound k -> "Failed to find expected property: " + k
| TypeMismatch (e,a) -> System.String.Concat ("Expected to find ", JsonMemberType.describe e, ", but instead found ", JsonMemberType.describe a)
| DeserializationError (t,e) -> System.String.Concat ("Unable to deserialize value as '", t.FullName, "': ", string e)
| InvalidJson e -> "Invalid JSON, failed to parse: " + e
| NoInput -> "No input was provided"
let toStringWithPath pathO jFail =
let path = (match pathO with Some p -> p; | _ -> System.String.Empty)// |> Option.defaultValue System.String.Empty
System.String.Concat (path, ": ", toString jFail)
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module JsonFailure =
let mappend jFail1 jFail2 =
PairedFailures (jFail1, jFail2)
let tag (t: JsonFailureTag) (f: JsonFailure) =
Tagged (t, f)
let toStrings jFail =
let rec inner (prefix: string option) = function
| Tagged (tag, innerFail) ->
inner (JsonFailureTag.toTagPathString prefix tag |> Some) innerFail
| SingleFailure jfr ->
[ JsonFailureReason.toStringWithPath prefix jfr ]
| PairedFailures (jFail1, jFail2) ->
[ jFail1; jFail2 ] |> List.collect (inner prefix)
| MultipleFailures jFails ->
jFails |> List.rev |> List.collect (inner prefix)
inner None jFail
let summarize jFail =
match toStrings jFail with
| [] -> "No errors"
| [e] -> sprintf "Found 1 error:\n %s" <| e
| errs ->
let sb = System.Text.StringBuilder()
sb.AppendLine(sprintf "Found %i errors:" (List.length errs)) |> ignore
errs |> List.iter (fun e -> sb.Append(" ").AppendLine(e) |> ignore)
sb.ToString()
module JsonResult =
let inline pass a = JPass a
let inline fail f = JFail f
let inline fails fs = JFail (MultipleFailures fs)
let getOrThrow : JsonResult<'a> -> 'a = function
| JPass x -> x
| JFail f -> failwith (JsonFailure.toStrings f |> String.concat "\n")
let toResult : JsonResult<'a> -> Result<'a, JsonFailure> = function
| JPass x -> Ok x
| JFail f -> Error f
let raise e = fail (SingleFailure (OtherError e))
let typeMismatch expected json = fail (SingleFailure (TypeMismatch (expected, JsonMemberType.ofJson json)))
let deserializationError<'a> exn : JsonResult<'a> = fail (SingleFailure (DeserializationError (typeof<'a>, exn)))
let invalidJson err : JsonResult<'a> = fail (SingleFailure (InvalidJson err))
let noInput<'a> : JsonResult<'a> = fail (SingleFailure NoInput)
let propertyNotFound f : JsonResult<'a> = fail (SingleFailure (PropertyNotFound f))
let failWithTag t f : JsonResult<'a> = fail (Tagged (t, f))
let inline bind (a2bR: 'a -> JsonResult<'b>) (aR : JsonResult<'a>) : JsonResult<'b> =
match aR with
| JPass a -> a2bR a
| JFail x -> fail x
let inline map (a2b: 'a -> 'b) (aR : JsonResult<'a>) : JsonResult<'b> =
match aR with
| JPass a -> pass (a2b a)
| JFail x -> fail x
let inline apply (aR: JsonResult<'a>) (a2Rb: JsonResult<'a -> 'b>) : JsonResult<'b> =
match a2Rb, aR with
| JPass a2b, JPass a -> pass (a2b a)
| JFail e1, JFail e2 -> fail (JsonFailure.mappend e1 e2)
| JFail e, _ | _, JFail e -> fail e
let applyDelayedWithPolicy (policy: ChironErrorPolicy) (c2aR: 'c -> JsonResult<'a>) (c: 'c) (a2Rb: JsonResult<'a -> 'b>) : JsonResult<'b> =
match a2Rb with
| JPass a2b ->
match c2aR c with
| JPass a -> pass (a2b a)
| JFail e -> fail e
| JFail e1 ->
match policy with
| StopOnFirstError -> fail e1
| ContinueOnError ->
match c2aR c with
| JPass a -> fail e1
| JFail e2 -> fail (JsonFailure.mappend e1 e2)
let applyDelayedWithPolicyAlt (policy: ChironErrorPolicy) : ('c -> JsonResult<'a>) -> 'c -> JsonResult<'a -> 'b> -> JsonResult<'b> =
match policy with
| StopOnFirstError ->
fun c2aR c a2Rb ->
match a2Rb with
| JPass a2b ->
match c2aR c with
| JPass a -> pass (a2b a)
| JFail e -> fail e
| JFail e1 -> fail e1
| ContinueOnError ->
fun c2aR c a2Rb -> apply (c2aR c) a2Rb
type Decoder<'s,'a> = 's -> JsonResult<'a>
type ObjectReader<'a> = Decoder<JsonObject,'a>
type ObjectBuilder<'a> = 'a -> JsonObject -> JsonObject
type JsonDecoder<'a> = Decoder<Json,'a>
type JsonEncoder<'a> = 'a -> Json
module Decoder =
let alwaysPass (a: 'a) : Decoder<'s,'a> =
fun s -> JsonResult.pass a
let alwaysFail (e: JsonFailure) : Decoder<'s,'a> =
fun s -> JsonResult.fail e
let always result : Decoder<'s,'a> =
fun s -> result
let inline bind (a2s2bR: 'a -> Decoder<'s,'b>) (s2aR: Decoder<'s,'a>): Decoder<'s,'b> =
fun s ->
s2aR s
|> JsonResult.bind (fun a -> a2s2bR a s)
let inline map (a2b: 'a -> 'b) (s2aR: Decoder<'s,'a>) : Decoder<'s,'b> =
fun s ->
s2aR s
|> JsonResult.map a2b
let inline compose (b2cR: Decoder<'b,'c>) (a2bR: Decoder<'a,'b>) : Decoder<'a,'c> =
fun a ->
a2bR a
|> JsonResult.bind b2cR
let inline applyWithContinueOnError (s2aR: Decoder<'s,'a>) (s2Ra2b: Decoder<'s,'a -> 'b>) : Decoder<'s,'b> =
fun s ->
match s2Ra2b s, s2aR s with
| JPass a2b, JPass a -> JsonResult.pass (a2b a)
| JFail e1, JFail e2 -> JsonResult.fail (JsonFailure.mappend e1 e2)
| JFail e, _ | _, JFail e -> JsonResult.fail e
let inline applyWithStopOnFirstError (s2aR: Decoder<'s,'a>) (s2Ra2b: Decoder<'s,'a -> 'b>) : Decoder<'s,'b> =
fun s ->
match s2Ra2b s with
| JPass a2b -> s2aR s |> JsonResult.map a2b
| JFail e -> JsonResult.fail e
let applyWithPolicy (policy: ChironErrorPolicy) : Decoder<'s,'a> -> Decoder<'s,'a -> 'b> -> Decoder<'s,'b> =
match policy with
| StopOnFirstError -> applyWithStopOnFirstError
| ContinueOnError -> applyWithContinueOnError
let inline apply (s2aR: Decoder<'s,'a>) (s2Ra2b: Decoder<'s,'a -> 'b>) : Decoder<'s,'b> =
applyWithContinueOnError s2aR s2Ra2b
let map2 (a2b2c: 'a -> 'b -> 'c) (s2aR: Decoder<'s,'a>) (s2bR: Decoder<'s,'b>) : Decoder<'s,'c> =
map a2b2c s2aR
|> apply s2bR
let map3 (a2b2c2d: 'a -> 'b -> 'c -> 'd) (s2aR: Decoder<'s,'a>) (s2bR: Decoder<'s,'b>) (s2cR: Decoder<'s,'c>) : Decoder<'s,'d> =
map a2b2c2d s2aR
|> apply s2bR
|> apply s2cR
let map4 (a2b2c2d2x: 'a -> 'b -> 'c -> 'd -> 'x) (s2aR: Decoder<'s,'a>) (s2bR: Decoder<'s,'b>) (s2cR: Decoder<'s,'c>) (s2dR: Decoder<'s,'d>) : Decoder<'s,'x> =
map a2b2c2d2x s2aR
|> apply s2bR
|> apply s2cR
|> apply s2dR
let map5 (a2b2c2d2x2y: 'a -> 'b -> 'c -> 'd -> 'x -> 'y) (s2aR: Decoder<'s,'a>) (s2bR: Decoder<'s,'b>) (s2cR: Decoder<'s,'c>) (s2dR: Decoder<'s,'d>) (s2xR: Decoder<'s,'x>) : Decoder<'s,'y> =
map a2b2c2d2x2y s2aR
|> apply s2bR
|> apply s2cR
|> apply s2dR
|> apply s2xR
let map6 (a2b2c2d2x2y2z: 'a -> 'b -> 'c -> 'd -> 'x -> 'y -> 'z) (s2aR: Decoder<'s,'a>) (s2bR: Decoder<'s,'b>) (s2cR: Decoder<'s,'c>) (s2dR: Decoder<'s,'d>) (s2xR: Decoder<'s,'x>) (s2yR: Decoder<'s,'y>) : Decoder<'s,'z> =
map a2b2c2d2x2y2z s2aR
|> apply s2bR
|> apply s2cR
|> apply s2dR
|> apply s2xR
|> apply s2yR
let withPropertyTag p (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (PropertyTag p) f
let withIndexTag i (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (IndexTag i) f
let withChoiceTag c (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (ChoiceTag c) f
let inline fromThrowingConverter (convert: 's -> 'a) : Decoder<'s,'a> =
fun s ->
try
JsonResult.pass (convert s)
with e -> JsonResult.deserializationError<'a> e
let inline withPropertyTagInline p (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (PropertyTag p) f
let inline withIndexTagInline i (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (IndexTag i) f
let inline withChoiceTagInline c (s2aR : Decoder<'s,'a>) : Decoder<'s,'a> =
fun s ->
match s2aR s with
| JPass a -> JsonResult.pass a
| JFail f -> JsonResult.failWithTag (ChoiceTag c) f
let inline fromThrowingConverterInline (convert: 's -> 'a) : Decoder<'s,'a> =
fun s ->
try
JsonResult.pass (convert s)
with e -> JsonResult.deserializationError<'a> e
module Operators =
let inline (<!>) (a2b: 'a -> 'b) (s2aR: Decoder<'s,'a>) = Decoder.map a2b s2aR
let inline (<*>) (s2Ra2b: Decoder<'s,'a -> 'b>) (s2aR: Decoder<'s,'a>) = Decoder.apply s2aR s2Ra2b
let inline (>=>) (a2bR: Decoder<'a,'b>) (b2cR: Decoder<'b,'c>) = Decoder.compose b2cR a2bR
let inline (>->) (s2aR: Decoder<'s,'a>) (a2b: 'a -> 'b) = Decoder.map a2b s2aR
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>]
module JsonObject =
let empty = WriteObject []
module PropertyList =
let inline add k v ps = (k, v) :: ps
let remove k ps = List.filter (fun kvp -> fst kvp <> k) ps
let upsert k v ps =
let mutable found = false
let newList = List.map (fun kvp -> if fst kvp = k then found <- true; (fst kvp, v) else kvp) ps
if not found then
add k v ps
else
newList
let tryFind k ps = List.tryPick (fun kvp -> if fst kvp = k then Some (snd kvp) else None) ps
module PropertyMap =
let inline add k v ps = Map.add k v ps
let inline remove k ps = Map.remove k ps
let inline upsert k v ps = Map.add k v ps
let inline tryFind k ps = Map.tryFind k ps
let add k v = function
| WriteObject ps -> WriteObject (PropertyList.add k v ps)
| ReadObject (ps, mps) ->
ReadObject (PropertyList.add k v ps, PropertyMap.add k v mps)
let remove k = function
| WriteObject ps -> WriteObject (PropertyList.remove k ps)
| ReadObject (ps, mps) -> ReadObject (PropertyList.remove k ps, PropertyMap.remove k mps)
let upsert k v = function
| WriteObject ps -> WriteObject (PropertyList.upsert k v ps)
| ReadObject (ps, mps) ->
ReadObject (PropertyList.upsert k v ps, PropertyMap.upsert k v mps)
let tryFind k = function
| WriteObject ps -> PropertyList.tryFind k ps
| ReadObject (_, mps) -> PropertyMap.tryFind k mps
let find k jsonObj =
match tryFind k jsonObj with
| Some v -> JsonResult.pass v
| None -> JsonResult.propertyNotFound k
let optimizeRead = function
| WriteObject ps -> ReadObject (ps, Map.ofList (List.rev ps))
| o -> o
let optimizeAppend = function
| ReadObject (ps, mps) -> WriteObject ps
| o -> o
let mapToList mps = Map.toList mps |> List.rev
let listToMap ps = List.rev ps |> Map.ofList
let dedupeWithMap kvps m =
if List.length kvps = Map.count m then
kvps
else
let hs = System.Collections.Generic.HashSet ()
List.foldBack (fun (k,_) s -> if hs.Add(k) then (k, Map.find k m) :: s else s) kvps []
let dedupeList kvps =
dedupeWithMap kvps (listToMap kvps)
let removeDuplicates = function
| WriteObject ps -> WriteObject (dedupeList ps)
| ReadObject (ps, mps) ->
if List.length ps <> Map.count mps then
ReadObject (dedupeWithMap ps mps, mps)
else
ReadObject (ps, mps)
let toPropertyListWithCustomKeyQuick (parse: Decoder<string,'a>) (decode: Decoder<Json,'b>) : Decoder<JsonObject,('a * 'b) list> = function
| WriteObject ps
| ReadObject (ps, _) ->
let rec loop agg lastK lastV ps =
match Decoder.withPropertyTag lastK parse lastK with
| JPass k ->
match Decoder.withPropertyTag lastK decode lastV with
| JPass v ->
let nextAgg = (k,v)::agg
match ps with
| [] -> JsonResult.pass nextAgg
| (nextK,nextV)::nextPs -> loop nextAgg nextK nextV nextPs
| JFail errs -> JsonResult.fail errs
| JFail errs -> JsonResult.fail errs
match ps with
| [] -> JsonResult.pass []
| (initK,initV)::initPs -> loop [] initK initV initPs
let toPropertyListWithCustomKey (parse: Decoder<string,'a>) (decode: Decoder<Json,'b>) : Decoder<JsonObject,('a * 'b) list> =
let idλ = (do ()); fun (x: JsonFailure list) -> x
function
| WriteObject ps
| ReadObject (ps, _) ->
let rec goodPath agg lastK lastV ps =
let kR = Decoder.withPropertyTag lastK parse lastK
let vR = Decoder.withPropertyTag lastK decode lastV
match kR, vR with
| JPass k, JPass v ->
let nextAgg = (k,v)::agg
match ps with
| [] -> JsonResult.pass nextAgg
| (nextK,nextV)::nextPs -> goodPath nextAgg nextK nextV nextPs
| JFail errs1, JFail errs2 ->
badPathTransfer [errs2;errs1] ps
| JFail errs, _
| _, JFail errs ->
badPathTransfer [errs] ps
and badPath (aggErrs: JsonFailure list) lastK lastV ps =
let kR = Decoder.withPropertyTag lastK parse lastK
let vR = Decoder.withPropertyTag lastK decode lastV
match kR, vR with
| JFail errs1, JFail errs2 ->
badPathTransfer (errs2::errs1::aggErrs) ps
| JFail errs, _
| _, JFail errs ->
badPathTransfer (errs::aggErrs) ps
| _ ->
badPathTransfer aggErrs ps
and badPathTransfer aggErrs ps =
match ps with
| [] -> JsonResult.fails aggErrs
| (nextK,nextV)::nextPs -> badPath aggErrs nextK nextV nextPs
match ps with
| [] -> JPass []
| (initK,initV)::initPs -> goodPath [] initK initV initPs
let toPropertyListWithQuick (decode: Decoder<Json,'b>) = function
| WriteObject ps
| ReadObject (ps, _) ->
let rec loop agg k lastV ps =
match Decoder.withPropertyTag k decode lastV with
| JPass v ->
let nextAgg = (k,v)::agg
match ps with
| [] -> JsonResult.pass nextAgg
| (nextK,nextV)::nextPs -> loop nextAgg nextK nextV nextPs
| JFail errs -> JsonResult.fail errs
match ps with
| [] -> JsonResult.pass []
| (initK,initV)::initPs -> loop [] initK initV initPs
let toPropertyListWith (decode: Decoder<Json,'b>) =
let idλ = (do ()); fun (x: JsonFailure list) -> x
function
| WriteObject ps
| ReadObject (ps, _) ->
let rec goodPath agg k lastV ps =
match Decoder.withPropertyTag k decode lastV with
| JPass v ->
let nextAgg = (k,v)::agg
match ps with
| [] -> JsonResult.pass nextAgg
| (nextK,nextV)::nextPs -> goodPath nextAgg nextK nextV nextPs
| JFail errs ->
badPathTransfer [errs] ps
and badPath (aggErrs: JsonFailure list) k lastV ps =
match Decoder.withPropertyTag k decode lastV with
| JFail errs ->
badPathTransfer (errs::aggErrs) ps
| _ ->
badPathTransfer aggErrs ps
and badPathTransfer aggErrs ps =
match ps with
| [] -> JsonResult.fails aggErrs
| (nextK,nextV)::nextPs -> badPath aggErrs nextK nextV nextPs
match ps with
| [] -> JsonResult.pass []
| (initK,initV)::initPs -> goodPath [] initK initV initPs
let toPropertyList = function
| WriteObject ps -> List.rev ps
| ReadObject (ps, _) -> List.rev ps
let ofPropertyListWithCustomKey (toString: 'a -> string) (encode: JsonEncoder<'b>) (ps: ('a * 'b) list): JsonObject =
let rec inner agg = function
| [] -> WriteObject agg
| (k,v) :: ps ->
inner ((toString k, encode v) :: agg) ps
inner [] ps
let ofPropertyListWith (encode: JsonEncoder<'a>) (ps: (string * 'a) list): JsonObject =
ofPropertyListWithCustomKey id encode ps
let ofPropertyList (ps: (string * Json) list): JsonObject =
List.rev ps
|> WriteObject
let toMapWithCustomKeyQuick (parse: Decoder<string,'k>) (decode: Decoder<Json,'v>) =
toPropertyListWithCustomKeyQuick parse decode
|> Decoder.map Map.ofList
let toMapWithCustomKey (parse: Decoder<string,'k>) (decode: Decoder<Json,'v>) =
toPropertyListWithCustomKey parse decode
|> Decoder.map Map.ofList
let toMapWithQuick (decode: Decoder<Json,'v>) =
toPropertyListWithQuick decode
|> Decoder.map Map.ofList
let toMapWith (decode: Decoder<Json,'v>) =
toPropertyListWith decode
|> Decoder.map Map.ofList
let toMap = function
| WriteObject ps -> List.rev ps |> Map.ofList
| ReadObject (_, mps) -> mps
let ofMap m = ReadObject (mapToList m, m)
let ofMapWith (encode: JsonEncoder<'a>) (m: Map<string, 'a>): JsonObject =
let newMap = Map.map (fun _ a -> encode a) m
ReadObject (mapToList newMap, newMap)
let ofMapWithCustomKey (toString: 'k -> string) (encode: JsonEncoder<'v>) (m: Map<'k, 'v>): JsonObject =
let newList =
mapToList m
|> List.map (fun (k,v) -> (toString k, encode v))
ReadObject (newList, Map.ofList newList)
let toJson jObj = Json.Object jObj
module Json =
let Null: Json = Json.Null
[<AutoOpen>]
module Parsing =
module Parser =
open FParsec
let ws = spaces // eats any whitespace
let inline str s = pstring s
let stringLiteral : Parser<string,unit> =
let escape = anyOf "\"\\/bfnrt"
|>> function
| 'b' -> "\b"
| 'f' -> "\u000C"
| 'n' -> "\n"
| 'r' -> "\r"
| 't' -> "\t"
| c -> string c // every other char is mapped to itself
let unicodeEscape =
str "u" >>. pipe4 hex hex hex hex (fun h3 h2 h1 h0 ->
let hex2int c = (int c &&& 15) + (int c >>> 6)*9 // hex char to int
(hex2int h3)*4096 + (hex2int h2)*256 + (hex2int h1)*16 + hex2int h0
|> char |> string
)
between (str "\"") (str "\"")
(stringsSepBy (manySatisfy (fun c -> c <> '"' && c <> '\\'))
(str "\\" >>. (escape <|> unicodeEscape)))
let jstring = stringLiteral |>> Json.String
let jsonNumOpts = NumberLiteralOptions.AllowFraction ||| NumberLiteralOptions.AllowExponent ||| NumberLiteralOptions.AllowMinusSign ||| NumberLiteralOptions.AllowPlusSign
let jnumber : Parser<Json,unit> =
fun stream ->
let reply = numberLiteralE jsonNumOpts (ErrorMessageList(ErrorMessage.Expected("JSON number"))) stream
if reply.Status = ReplyStatus.Ok then
Reply(Json.Number reply.Result.String)
else
Reply(reply.Status, reply.Error)
let jtrue = stringReturn "true" Json.True
let jfalse = stringReturn "false" Json.False
let jnull = stringReturn "null" Json.Null
// jvalue, jlist and jobject are three mutually recursive grammar productions.
// In order to break the cyclic dependency, we make jvalue a parser that
// forwards all calls to a parser in a reference cell.
let jvalue, jvalueRef = createParserForwardedToRef() // initially jvalueRef holds a reference to a dummy parser
let listBetweenStrings sOpen sClose pElement f =
between (str sOpen) (str sClose) (ws >>. sepBy (pElement .>> ws) (str "," .>> ws) |>> f)
let keyValue = tuple2 stringLiteral (ws >>. str ":" >>. ws >>. jvalue)
let jlist = listBetweenStrings "[" "]" jvalue Json.Array
let toJsonObject = fun lst -> let map = Map.ofList lst in ReadObject (lst,map) |> Json.Object
let jobject = listBetweenStrings "{" "}" keyValue toJsonObject
do jvalueRef := choice [jobject
jlist
jstring
jnumber
jtrue
jfalse
jnull]
let json = ws >>. jvalue .>> ws .>> eof
let parseJsonString str = run json str
let parseJsonStream stream =
runParserOnStream json () "" stream System.Text.Encoding.UTF8
let handleParserResult = function
| Success (json, _, _) -> JsonResult.pass json
| Failure (e, _, _) -> JsonResult.invalidJson e
module Json =
let parse s =
if System.String.IsNullOrWhiteSpace s then
JsonResult.noInput
else
Parser.parseJsonString s
|> Parser.handleParserResult
let parseStream (stream : #System.IO.Stream) =
Parser.parseJsonStream stream
|> Parser.handleParserResult
[<AutoOpen>]
module Formatting =
open System.Globalization
let escapeChars =
[| '"'; '\\'; '\n'; '\r'; '\t'; '\b'; '\f'
'\u0000'; '\u0001'; '\u0002'; '\u0003'
'\u0004'; '\u0005'; '\u0006'; '\u0007'
'\u000B'; '\u000E'; '\u000F'
'\u0010'; '\u0011'; '\u0012'; '\u0013'
'\u0014'; '\u0015'; '\u0016'; '\u0017'
'\u0018'; '\u0019'; '\u001A'; '\u001B'
'\u001C'; '\u001D'; '\u001E'; '\u001F' |]
let isEscapeChar = function
| '"' | '\\' -> true
| c when c >= '\u0000' && c <= '\u001F' -> true
| _ -> false
let isEscapeCharPred = System.Predicate<_> isEscapeChar
let escaped = function
| '"' -> @"\"""
| '\\' -> @"\\"
| '\n' -> @"\n"
| '\r' -> @"\r"
| '\t' -> @"\t"
| '\f' -> @"\f"
| '\b' -> @"\b"
| '\u0000' -> @"\u0000"
| '\u0001' -> @"\u0001"
| '\u0002' -> @"\u0002"
| '\u0003' -> @"\u0003"
| '\u0004' -> @"\u0004"
| '\u0005' -> @"\u0005"
| '\u0006' -> @"\u0006"
| '\u0007' -> @"\u0007"
| '\u000B' -> @"\u000B"
| '\u000E' -> @"\u000E"
| '\u000F' -> @"\u000F"
| '\u0010' -> @"\u0010"
| '\u0011' -> @"\u0011"
| '\u0012' -> @"\u0012"
| '\u0013' -> @"\u0013"
| '\u0014' -> @"\u0014"
| '\u0015' -> @"\u0015"
| '\u0016' -> @"\u0016"
| '\u0017' -> @"\u0017"
| '\u0018' -> @"\u0018"
| '\u0019' -> @"\u0019"
| '\u001A' -> @"\u001A"
| '\u001B' -> @"\u001B"
| '\u001C' -> @"\u001C"
| '\u001D' -> @"\u001D"
| '\u001E' -> @"\u001E"
| '\u001F' -> @"\u001F"
| c -> @"\u" + (int c).ToString("X4", CultureInfo.InvariantCulture)
type PropertyNameSpacing =
| NoSpaceBetweenNameAndValue
| SpaceBetweenNameAndValue
type ElementSpacing =
| NoSpaceBetweenElements
| SpaceBetweenElements
| NewLineBetweenElements of indentSpaces:int
type JsonFormattingOptions =
{ PropertyNameSpacing : PropertyNameSpacing
ElementSpacing : ElementSpacing }
static member Compact =
{ PropertyNameSpacing = NoSpaceBetweenNameAndValue
ElementSpacing = NoSpaceBetweenElements }
static member SingleLine =
{ PropertyNameSpacing = SpaceBetweenNameAndValue
ElementSpacing = SpaceBetweenElements }
static member Pretty =
{ PropertyNameSpacing = SpaceBetweenNameAndValue
ElementSpacing = NewLineBetweenElements 2 }
module StringBuilder =
open System.Text
let inline append (sb: StringBuilder) (s: string) =
sb.Append s |> ignore
let inline appendSubstr (sb: StringBuilder) (s: string) (start: int) (count: int) =
sb.Append (s, start, count) |> ignore
let inline appendChar (sb: StringBuilder) (c: char) =
sb.Append c |> ignore
let inline appendCharRep (sb: StringBuilder) (c: char) (repeats: int) =
sb.Append (c, repeats) |> ignore
let writeString (sb:System.Text.StringBuilder) (cs:string) =
let rec escapeState index =
append sb (escaped cs.[index])
let nextIndex = index + 1
if nextIndex < cs.Length then
if isEscapeChar cs.[nextIndex] |> not then
coreState nextIndex
else
escapeState nextIndex
and coreState index =
let nextEscapeIndex = cs.IndexOfAny(escapeChars, index)
if nextEscapeIndex = -1 then
appendSubstr sb cs index (cs.Length - index)
else
appendSubstr sb cs index (nextEscapeIndex - index)
escapeState nextEscapeIndex
coreState 0
let appendSpaceBetweenElements sb { ElementSpacing = es } level =
match es, level with
| NoSpaceBetweenElements, _ -> ()
| SpaceBetweenElements, _ -> appendChar sb ' '
| NewLineBetweenElements _, 0 -> appendChar sb '\n'
| NewLineBetweenElements s, l -> appendChar sb '\n'; appendCharRep sb ' ' (s * l |> int)
let addNameSeparator sb { PropertyNameSpacing = pns } =
match pns with
| NoSpaceBetweenNameAndValue -> appendChar sb ':'
| SpaceBetweenNameAndValue -> append sb ": "
let rec formatJson sb options level = function
| Json.Object (WriteObject props)
| Json.Object (ReadObject (props,_)) -> formatObject sb options level props
| Json.Array elems -> formatArray sb options level elems
| Json.String s -> formatString sb s
| Json.Number x -> formatNumber sb x
| Json.True -> append sb "true"
| Json.False -> append sb "false"
| Json.Null -> append sb "null"
and formatObject sb options level props =
let newLevel = level + 1
appendChar sb '{'
appendSpaceBetweenElements sb options newLevel
joinObject sb options newLevel props
appendSpaceBetweenElements sb options level
appendChar sb '}'
and joinObject sb options level values =
match values with
| [] -> ()
| [v] -> formatProperty sb options level v
| v :: vs ->
joinObject sb options level vs
appendChar sb ','
appendSpaceBetweenElements sb options level
formatProperty sb options level v
and formatProperty sb options level (k,v) =
formatString sb k
addNameSeparator sb options
formatJson sb options level v
and formatArray sb options level elems =
let newLevel = level + 1
appendChar sb '['
appendSpaceBetweenElements sb options newLevel
joinArray sb options newLevel elems
appendSpaceBetweenElements sb options level
appendChar sb ']'
and joinArray sb options level values =
match values with
| [] -> ()
| [v] -> formatJson sb options level v
| v :: vs ->
formatJson sb options level v
appendChar sb ','
appendSpaceBetweenElements sb options level
joinArray sb options level vs
and formatString sb str =
appendChar sb '"'
writeString sb str
appendChar sb '"'
and formatNumber sb n =
append sb n
[<RequireQualifiedAccess>]
module Json =
let formatWith options json =
let sb = System.Text.StringBuilder ()
StringBuilder.formatJson sb options 0 json
sb.ToString()
let format json =
formatWith JsonFormattingOptions.Compact json
[<AutoOpen>]
module Serialization =
open System.Globalization
module Json =
module Encode =
let buildWith (builder: ObjectBuilder<'a>) (a: 'a): Json =
builder a JsonObject.empty
|> JsonObject.toJson
let inline buildWithInline (builder: ObjectBuilder<'a>) (a: 'a): Json =
builder a JsonObject.empty
|> JsonObject.toJson
let required (encode : JsonEncoder<'a>) k a jObj =
JsonObject.add k (encode a) jObj
let optional encode k aO jObj =
match aO with
| Some a -> required encode k a jObj
| None -> jObj
let inline ifNotEqual x encode k a jObj =
if x = a then jObj
else required encode k a jObj
let conditional pred encode k a jObj =
if pred a then required encode k a jObj
else jObj
let requiredMixin (build: ObjectBuilder<'a>) a jObj =
build a jObj
let optionalMixin build aO jObj =
match aO with
| Some a -> buildWith a jObj
| None -> jObj
let ref<'a> (): JsonEncoder<'a> ref * JsonEncoder<'a> =
let innerRef = ref (Unchecked.defaultof<JsonEncoder<'a>>)
innerRef, (fun a -> (!innerRef) a)
let lazily (lazyEncode: Lazy<JsonEncoder<'a>>): JsonEncoder<'a> =
fun a -> lazyEncode.Force() a
let delay (u2aD: unit -> JsonEncoder<'a>): JsonEncoder<'a> =
let lazified = lazy (u2aD ())
lazily lazified
let delayWith (x2aD: 'x -> JsonEncoder<'a>) (x: 'x): JsonEncoder<'a> =
let lazified = lazy (x2aD x)
lazily lazified
let json json: Json = json
let jsonObject (jObj: JsonObject): Json =
JsonObject.toJson jObj
let jsonObjectWith (encode: ObjectBuilder<'a>) (a: 'a): Json =
buildWith encode a
let propertyList (ps: (string * Json) list): Json =
JsonObject.ofPropertyList ps
|> jsonObject
let propertyListWith (encode: JsonEncoder<'a>) (ps: (string * 'a) list): Json =
JsonObject.ofPropertyListWith encode ps
|> jsonObject
let list (els: Json list): Json =
Json.Array els
let listWith (encode: JsonEncoder<'a>) (els: 'a list): Json =
List.map encode els
|> list
let array (els: Json array): Json =
List.ofArray els
|> list
let arrayWith (encode: JsonEncoder<'a>) (els: 'a array): Json =
Array.map encode els
|> array
let option (jO: Json option): Json =
Option.defaultValue Null jO
let optionWith (encode: JsonEncoder<'a>) (aO: 'a option): Json =
Option.map encode aO
|> option
let result (jR : Result<Json, Json>) : Json =
match jR with
| Ok(a) -> a
| Error(b) -> b
let resultWith (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) (abR: Result<'a, 'b>): Json =
abR
|> Result.map encodeA
|> Result.mapError encodeB
|> result
// let set (els: Set<Json>): Json =
// Set.toList els
// |> list
let setWith (encode: JsonEncoder<'a>) (els: Set<'a>): Json =
Set.toList els
|> listWith encode
let map (m: Map<string, Json>): Json =
JsonObject.ofMap m
|> jsonObject
let mapWith (encode: JsonEncoder<'a>) (m: Map<string, 'a>): Json =
JsonObject.ofMapWith encode m
|> jsonObject
let mapWithCustomKey (toString: 'a -> string) (encode: JsonEncoder<'b>) (m: Map<'a, 'b>): Json =
JsonObject.ofMapWithCustomKey toString encode m
|> jsonObject
let tuple2 (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) ((a : 'a), (b : 'b)): Json =
list
[ encodeA a
encodeB b ]
let tuple3 (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) (encodeC: JsonEncoder<'c>) ((a : 'a), (b : 'b), (c: 'c)): Json =
list
[ encodeA a
encodeB b
encodeC c ]
let tuple4 (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) (encodeC: JsonEncoder<'c>) (encodeD: JsonEncoder<'d>) ((a : 'a), (b : 'b), (c: 'c), (d: 'd)): Json =
list
[ encodeA a
encodeB b
encodeC c
encodeD d ]
let tuple5 (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) (encodeC: JsonEncoder<'c>) (encodeD: JsonEncoder<'d>) (encodeE: JsonEncoder<'e>) ((a : 'a), (b : 'b), (c: 'c), (d: 'd), (e: 'e)): Json =
list
[ encodeA a
encodeB b
encodeC c
encodeD d
encodeE e ]
let tuple6 (encodeA: JsonEncoder<'a>) (encodeB: JsonEncoder<'b>) (encodeC: JsonEncoder<'c>) (encodeD: JsonEncoder<'d>) (encodeE: JsonEncoder<'e>) (encodeF: JsonEncoder<'f>) ((a : 'a), (b : 'b), (c: 'c), (d: 'd), (e: 'e), (f: 'f)): Json =
list
[ encodeA a
encodeB b
encodeC c
encodeD d
encodeE e
encodeF f ]