-
Notifications
You must be signed in to change notification settings - Fork 2
/
Peeble.fsx
1541 lines (1343 loc) · 60.2 KB
/
Peeble.fsx
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
#load "c:/Development/crazy/.paket/load/netStandard2.0/Transpiler/FSharp.Compiler.Service.fsx"
#I @"C:\development\Fable\src\Fable.Transforms"
#load @"Global\Fable.Core.fs" @"Global\Prelude.fs" @"Global\Compiler.fs" @"AST\AST.Common.fs" @"AST\AST.Fable.fs" @"MonadicTrampoline.fs" @"Transforms.Util.fs" @"OverloadSuffix.fs" @"FSharp2Fable.Util.fs" @"ReplacementsInject.fs" @"Replacements.fs" @"Inject.fs" @"FSharp2Fable.fs" @"FableTransforms.fs"
open System
open Fable
open FSharp.Compiler.SourceCodeServices
open System.Collections.Generic
open System.Collections.Concurrent
open System.IO
type Project(projectOptions: FSharpProjectOptions,
implFiles: IDictionary<string, FSharpImplementationFileContents>,
errors: FSharpErrorInfo array) =
let projectFile = Path.normalizePath projectOptions.ProjectFileName
let inlineExprs = ConcurrentDictionary<string, InlineExpr>()
//let rootModules =
// implFiles |> Seq.map (fun kv ->
// kv.Key, FSharp2Fable.Compiler.getRootModuleFullName kv.Value) |> dict
member __.ImplementationFiles = implFiles
member __.RootModules = dict [] //rootModules
member __.InlineExprs = inlineExprs
member __.Errors = errors
member __.ProjectOptions = projectOptions
member __.ProjectFile = projectFile
member __.GetOrAddInlineExpr(fullName, generate) =
inlineExprs.GetOrAdd(fullName, fun _ -> generate())
type Log =
{ Message: string
Tag: string
Severity: Severity
Range: SourceLocation option
FileName: string option }
type Compiler(currentFile, project: Project, options, fableLibraryDir: string) =
let mutable id = 0
let logs = ResizeArray<Log>()
let fableLibraryDir = fableLibraryDir.TrimEnd('/')
member __.GetLogs() =
logs |> Seq.toList
member __.GetFormattedLogs() =
let severityToString = function
| Severity.Warning -> "warning"
| Severity.Error -> "error"
| Severity.Info -> "info"
logs
|> Seq.groupBy (fun log -> severityToString log.Severity)
|> Seq.map (fun (severity, logs) ->
logs |> Seq.map (fun log ->
match log.FileName with
| Some file ->
match log.Range with
| Some r -> sprintf "%s(%i,%i): (%i,%i) %s %s: %s" file r.start.line r.start.column r.``end``.line r.``end``.column severity log.Tag log.Message
| None -> sprintf "%s(1,1): %s %s: %s" file severity log.Tag log.Message
| None -> log.Message)
|> Seq.toArray
|> Tuple.make2 severity)
|> Map
member __.Options = options
member __.CurrentFile = currentFile
interface ICompiler with
member __.Options = options
member __.LibraryDir = fableLibraryDir
member __.CurrentFile = currentFile
member x.GetRootModule(fileName) =
let fileName = Path.normalizePathAndEnsureFsExtension fileName
match project.RootModules.TryGetValue(fileName) with
| true, rootModule -> rootModule
| false, _ ->
let msg = sprintf "Cannot find root module for %s. If this belongs to a package, make sure it includes the source files." fileName
(x :> ICompiler).AddLog(msg, Severity.Warning)
"" // failwith msg
member __.GetOrAddInlineExpr(fullName, generate) =
project.InlineExprs.GetOrAdd(fullName, fun _ -> generate())
member __.AddLog(msg, severity, ?range, ?fileName:string, ?tag: string) =
{ Message = msg
Tag = defaultArg tag "FABLE"
Severity = severity
Range = range
FileName = fileName }
|> logs.Add
// TODO: If name includes `$$2` at the end, remove it
member __.GetUniqueVar(name) =
id <- id + 1
Naming.getUniqueName (defaultArg name "var") id
type PhpConst =
| PhpConstNumber of float
| PhpConstString of string
| PhpConstBool of bool
| PhpConstNull
| PhpConstUnit
type PhpArrayIndex =
| PhpArrayNoIndex
| PhpArrayInt of int
| PhpArrayString of string
type PhpField =
{ Name: string
Type: string }
type Capture =
| ByValue of string
| ByRef of string
type Prop =
| Field of PhpField
| StrField of string
and PhpExpr =
| PhpVar of string * typ: PhpType option
| PhpGlobal of string
| PhpConst of PhpConst
| PhpUnaryOp of string * PhpExpr
| PhpBinaryOp of string *PhpExpr * PhpExpr
| PhpProp of PhpExpr * Prop * typ: PhpType option
| PhpArrayAccess of PhpExpr * PhpExpr
| PhpNew of ty:PhpType * args:PhpExpr list
| PhpArray of args: (PhpArrayIndex * PhpExpr) list
| PhpCall of f: PhpExpr * args: PhpExpr list
| PhpMethod of this: PhpExpr * func:string * args: PhpExpr list
| PhpTernary of gard: PhpExpr * thenExpr: PhpExpr * elseExpr: PhpExpr
| PhpIsA of expr: PhpExpr * PhpType
| PhpAnonymousFunc of args: string list * uses: Capture list * body: PhpStatement list
| PhpMacro of macro: string * args: PhpExpr list
and PhpStatement =
| Return of PhpExpr
| Expr of PhpExpr
| Switch of PhpExpr * (PhpCase * PhpStatement list) list
| Break
| Assign of target:PhpExpr * value:PhpExpr
| If of guard: PhpExpr * thenCase: PhpStatement list * elseCase: PhpStatement list
| Throw of string
| Do of PhpExpr
and PhpCase =
| IntCase of int
| StringCase of string
| DefaultCase
and PhpFun =
{ Name: string
Args: string list
Matchings: PhpStatement list
Body: PhpStatement list
Static: bool
}
and PhpType =
{ Name: string
Fields: PhpField list;
Methods: PhpFun list
Abstract: bool
BaseType: PhpType option
Interfaces: PhpType list
}
type PhpDecl =
| PhpFun of PhpFun
| PhpDeclValue of name:string * PhpExpr
| PhpType of PhpType
type PhpFile =
{ Decls: (int * PhpDecl) list }
module Output =
type Writer =
{ Writer: TextWriter
Indent: int
Precedence: int }
let indent ctx =
{ ctx with Indent = ctx.Indent + 1}
module Writer =
let create w =
{ Writer = w; Indent = 0; Precedence = Int32.MaxValue }
let writeIndent ctx =
for _ in 1 .. ctx.Indent do
ctx.Writer.Write(" ")
let write ctx txt =
ctx.Writer.Write(txt: string)
let writeln ctx txt =
ctx.Writer.WriteLine(txt: string)
let writei ctx txt =
writeIndent ctx
write ctx txt
let writeiln ctx txt =
writeIndent ctx
writeln ctx txt
let writeVarList ctx vars =
let mutable first = true
for var in vars do
if first then
first <- false
else
write ctx ", "
write ctx "$"
write ctx var
let writeUseList ctx vars =
let mutable first = true
for var in vars do
if first then
first <- false
else
write ctx ", "
match var with
| ByValue v ->
write ctx "$"
write ctx v
| ByRef v ->
write ctx "&$"
write ctx v
module Precedence =
let binary =
function
| "*" | "/" | "%" -> 3
| "+" | "-" | "." -> 4
| "<<" | ">>" -> 5
| "<" | "<=" | ">=" | ">" -> 7
| "==" | "!=" | "==="
| "!==" | "<>" | "<=>" -> 7
| "&" -> 8
| "^" -> 9
| "|" -> 10
| "&&" -> 11
| "||" -> 12
| "??" -> 13
| op -> failwithf "Unknown binary operator %s" op
let unary =
function
| "!" -> 2
| "-" -> 4
| "&" -> 8
| op -> failwithf "Unknown unary operator %s" op
let _new = 0
let instanceOf = 1
let ternary = 14
let assign = 15
let clear ctx = { ctx with Precedence = Int32.MaxValue}
let withPrecedence ctx prec f =
let useParens = prec > ctx.Precedence || (prec = 14 && ctx.Precedence = 14)
let subCtx = { ctx with Precedence = prec }
if useParens then
write subCtx "("
f subCtx
if useParens then
write subCtx ")"
let rec writeExpr ctx expr =
match expr with
| PhpBinaryOp(op, left, right) ->
withPrecedence ctx (Precedence.binary op)
(fun subCtx ->
writeExpr subCtx left
write subCtx " "
write subCtx op
write subCtx " "
writeExpr subCtx right)
| PhpUnaryOp(op, expr) ->
withPrecedence ctx (Precedence.unary op)
(fun subCtx ->
write subCtx op
writeExpr subCtx expr )
| PhpConst cst ->
match cst with
| PhpConstNumber n -> write ctx (string n)
| PhpConstString s ->
write ctx "'"
write ctx (s.Replace("'",@"\'"))
write ctx "'"
| PhpConstBool true -> write ctx "true"
| PhpConstBool false -> write ctx "false"
| PhpConstNull -> write ctx "NULL"
| PhpConstUnit -> write ctx "NULL"
| PhpVar (v,_) ->
write ctx "$"
write ctx v
| PhpGlobal v ->
write ctx "$GLOBALS['"
write ctx v
write ctx "']"
| PhpProp(l,r, _) ->
writeExpr ctx l
write ctx "->"
match r with
| Field r -> write ctx r.Name
| StrField r -> write ctx r
| PhpNew(t,args) ->
withPrecedence ctx (Precedence._new)
(fun subCtx ->
write subCtx "new "
write subCtx t.Name
write subCtx "("
writeArgs subCtx args
write subCtx ")")
| PhpArray(args) ->
write ctx "[ "
let mutable first = true
for key,value in args do
if first then
first <- false
else
write ctx ", "
writeArrayIndex ctx key
writeExpr ctx value
write ctx "]"
| PhpArrayAccess(array, index) ->
writeExpr ctx array
write ctx "["
writeExpr ctx index
write ctx "]"
| PhpCall(f,args) ->
let anonymous = match f with PhpAnonymousFunc _ -> true | _ -> false
if anonymous then
write ctx "("
match f with
| PhpConst (PhpConstString f) ->
write ctx f
| _ -> writeExpr ctx f
if anonymous then
write ctx ")"
write ctx "("
writeArgs ctx args
write ctx ")"
| PhpMethod(this,f,args) ->
writeExpr ctx this
write ctx "->"
write ctx f
write ctx "("
writeArgs ctx args
write ctx ")"
| PhpTernary (guard, thenExpr, elseExpr) ->
withPrecedence ctx (Precedence.ternary)
(fun ctx ->
writeExpr ctx guard
write ctx " ? "
writeExpr ctx thenExpr
write ctx " : "
writeExpr ctx elseExpr)
| PhpIsA (expr, t) ->
withPrecedence ctx (Precedence.instanceOf)
(fun ctx ->
writeExpr ctx expr
write ctx " instanceof "
write ctx t.Name)
| PhpAnonymousFunc(args, uses, body) ->
write ctx "function ("
writeVarList ctx args
write ctx ")"
match uses with
| [] -> ()
| _ ->
write ctx " use ("
writeUseList ctx uses
write ctx ")"
write ctx " { "
let multiline = body.Length > 1
let bodyCtx =
if multiline then
writeln ctx ""
indent ctx
else
ctx
for st in body do
writeStatement bodyCtx st
if multiline then
writei ctx "}"
else
write ctx " }"
| PhpMacro(macro, args) ->
let regex = System.Text.RegularExpressions.Regex("\$(?<n>\d)(?<s>\.\.\.)?")
let matches = regex.Matches(macro)
let mutable pos = 0
for m in matches do
let n = int m.Groups.["n"].Value
write ctx (macro.Substring(pos,m.Index-pos))
if m.Groups.["s"].Success then
match args.[n] with
| PhpArray items ->
let mutable first = true
for _,value in items do
if first then
first <- false
else
write ctx ", "
writeExpr ctx value
| _ -> failwith "Splice param should be a array"
else
writeExpr ctx args.[n]
pos <- m.Index + m.Length
write ctx (macro.Substring(pos))
and writeArgs ctx args =
let mutable first = true
for arg in args do
if first then
first <- false
else
write ctx ", "
writeExpr ctx arg
and writeArrayIndex ctx index =
match index with
| PhpArrayString s ->
write ctx "'"
write ctx s
write ctx "' => "
| PhpArrayInt n ->
write ctx (string n)
write ctx " => "
| PhpArrayNoIndex ->
()
and writeStatement ctx st =
match st with
| PhpStatement.Return expr ->
writei ctx "return "
writeExpr (Precedence.clear ctx) expr
writeln ctx ";"
| Expr expr ->
writei ctx ""
writeExpr (Precedence.clear ctx) expr
writeln ctx ";"
| Assign(name, expr) ->
writei ctx ""
writeExpr (Precedence.clear ctx) name
write ctx " = "
writeExpr (Precedence.clear ctx) expr
writeln ctx ";"
| Switch(expr, cases) ->
writei ctx "switch ("
writeExpr (Precedence.clear ctx) expr
writeln ctx ")"
writeiln ctx "{"
let casesCtx = indent ctx
let caseCtx = indent casesCtx
for case,sts in cases do
match case with
| IntCase i ->
writei casesCtx "case "
write casesCtx (string i)
| StringCase s ->
writei casesCtx "case '"
write casesCtx s
write casesCtx "'"
| DefaultCase ->
writei casesCtx "default"
writeln casesCtx ":"
for st in sts do
writeStatement caseCtx st
writeiln ctx "}"
| Break ->
writeiln ctx "break;"
| If(guard, thenCase, elseCase) ->
writei ctx "if ("
writeExpr (Precedence.clear ctx) guard
writeln ctx ") {"
let body = indent ctx
for st in thenCase do
writeStatement body st
writei ctx "}"
if List.isEmpty elseCase then
writeiln ctx ""
else
writeiln ctx " else {"
for st in elseCase do
writeStatement body st
writeiln ctx "}"
| Throw s ->
writei ctx "throw new Exception('"
write ctx s
writeln ctx "');"
| PhpStatement.Do (PhpConst PhpConstUnit)-> ()
| PhpStatement.Do (expr) ->
writei ctx ""
writeExpr (Precedence.clear ctx) expr
writeln ctx ";"
let writeFunc ctx (f: PhpFun) =
writei ctx ""
if f.Static then
write ctx "static "
write ctx "function "
write ctx f.Name
write ctx "("
let mutable first = true
for arg in f.Args do
if first then
first <- false
else
write ctx ", "
write ctx "$"
write ctx arg
writeln ctx ") {"
let bodyCtx = indent ctx
for s in f.Matchings do
writeStatement bodyCtx s
for s in f.Body do
writeStatement bodyCtx s
writeiln ctx "}"
let writeField ctx (m: PhpField) =
writei ctx "public $"
write ctx m.Name
writeln ctx ";"
let writeCtor ctx (t: PhpType) =
writei ctx "function __construct("
let mutable first = true
for p in t.Fields do
if first then
first <- false
else
write ctx ", "
//write ctx p.Type
write ctx "$"
write ctx p.Name
writeln ctx ") {"
let bodyctx = indent ctx
for p in t.Fields do
writei bodyctx "$this->"
write bodyctx p.Name
write bodyctx " = $"
write bodyctx p.Name
writeln bodyctx ";"
writeiln ctx "}"
let writeType ctx (t: PhpType) =
writei ctx ""
if t.Abstract then
write ctx "abstract "
write ctx "class "
write ctx t.Name
match t.BaseType with
| Some t ->
write ctx " extends "
write ctx t.Name
| None -> ()
if t.Interfaces <> [] then
write ctx " implements "
let mutable first = true
for itf in t.Interfaces do
if first then
first <- false
else
write ctx ", "
write ctx itf.Name
writeln ctx " {"
let mbctx = indent ctx
for m in t.Fields do
writeField mbctx m
if not t.Abstract then
writeCtor mbctx t
for m in t.Methods do
writeFunc mbctx m
writeiln ctx "}"
let writeAssign ctx n expr =
writei ctx "$GLOBALS['"
write ctx n
write ctx "'] = "
writeExpr ctx expr
writeln ctx ";"
let writeDecl ctx d =
match d with
| PhpType t -> writeType ctx t
| PhpFun t -> writeFunc ctx t
| PhpDeclValue(n,expr) -> writeAssign ctx n expr
let writeFile ctx (file: PhpFile) =
writeln ctx "<?php"
for i,d in file.Decls do
writeln ctx ( "#" + string i)
writeDecl ctx d
writeln ctx ""
open Fable.AST
module PhpList =
let list = { Name = "FSharpList"; Fields = []; Methods = []; Abstract = true; BaseType = None; Interfaces = [] }
let value = { Name = "value"; Type = "" }
let next = { Name = "next"; Type = "FSharpList" }
let cons = { Name = "Cons"; Fields = [ value; next ]; Methods = []; Abstract = false; BaseType = Some list; Interfaces = [] }
let nil = { Name = "Nil"; Fields = []; Methods = []; Abstract = false; BaseType = Some list; Interfaces = [] }
module PhpResult =
let result = { Name = "Result"; Fields = []; Methods = []; Abstract = true; BaseType = None; Interfaces = []}
let okValue = { Name = "ResultValue"; Type = ""}
let ok = { Name = "Ok"; Fields = [okValue]; Methods = []; Abstract = true; BaseType = Some result; Interfaces = [] }
let errorValue = { Name = "ErrorValue"; Type = ""}
let error = { Name = "ResultError"; Fields = [errorValue] ; Methods = []; Abstract = true; BaseType = Some result; Interfaces = [] }
module PhpUnion =
let union = { Name = "Union"; Fields = []; Methods = []; Abstract = true; BaseType = None; Interfaces = []}
let fSharpUnion = { Name = "FSharpUnion"; Fields = []; Methods = []; Abstract = true; BaseType = None; Interfaces = []}
module Core =
let icomparable = { Name = "iComparable"; Fields = []; Methods = []; Abstract = true; BaseType = None; Interfaces = [] }
type PhpCompiler =
{ mutable Types: Map<string,PhpType>
mutable DecisionTargets: (Fable.Ident list * Fable.Expr) list
mutable LocalVars: string Set
mutable CapturedVars: Capture Set
mutable MutableVars: string Set
mutable Id: int
}
static member empty =
{ Types = Map.ofList [ "List" , PhpList.list
"Cons" , PhpList.cons
"Nil", PhpList.nil
"Result", PhpResult.result
"Ok", PhpResult.ok
"ResultError", PhpResult.error
]
DecisionTargets = []
LocalVars = Set.empty
CapturedVars = Set.empty
MutableVars = Set.empty
Id = 0
}
member this.AddType(phpType: PhpType) =
this.Types <- Map.add phpType.Name phpType this.Types
phpType
member this.AddLocalVar(var, isMutable) =
if isMutable then
this.MutableVars <- Set.add var this.MutableVars
if this.CapturedVars.Contains(Capture.ByRef var) then
()
elif this.CapturedVars.Contains(Capture.ByValue var) then
this.CapturedVars <- this.CapturedVars |> Set.remove (Capture.ByValue var) |> Set.add(ByRef var)
else
this.LocalVars <- Set.add var this.LocalVars
member this.UseVar(var) =
if not (Set.contains var this.LocalVars) && not (Set.contains (ByRef var) this.CapturedVars) then
if Set.contains var this.MutableVars then
this.CapturedVars <- Set.add (ByRef var) this.CapturedVars
else
this.CapturedVars <- Set.add (ByValue var) this.CapturedVars
member this.UseVarByRef(var) =
this.MutableVars <- Set.add var this.MutableVars
if not (Set.contains var this.LocalVars) && not (Set.contains (ByValue var) this.CapturedVars) then
this.CapturedVars <- Set.add (ByRef var) this.CapturedVars
member this.UseVar(var) =
match var with
| ByValue name -> this.UseVar name
| ByRef name -> this.UseVarByRef name
member this.MakeUniqueVar(name) =
this.Id <- this.Id + 1
"_" + name + "__" + string this.Id
member this.NewScope() =
{ this with
LocalVars = Set.empty
CapturedVars = Set.empty }
let convertType (t: FSharpType) =
if (t.IsAbbreviation) then
t.Format(FSharpDisplayContext.Empty.WithShortTypeNames(true))
else
match t with
| Symbol.TypeWithDefinition entity ->
match entity.CompiledName with
| "FSharpSet`1" -> "Set"
| name -> name
| _ ->
failwithf "%A" t
let fixName (name: string) =
name.Replace('$','_')
let caseName (case: FSharpUnionCase) =
let entity = case.ReturnType.TypeDefinition
if entity.UnionCases.Count = 1 then
case.Name
elif entity.CompiledName = "FSharpResult`2" then
if case.Name = "Ok" then
case.Name
else
"ResultError"
else
entity.CompiledName + "_" + case.Name
let convertUnion (ctx: PhpCompiler) (info: Fable.UnionConstructorInfo) =
if info.Entity.UnionCases.Count = 1 then
let case = info.Entity.UnionCases.[0]
[ let t =
{ Name = case.Name
Fields = [ for e in case.UnionCaseFields do
{ Name = e.Name
Type = convertType e.FieldType } ]
Methods = [
{ PhpFun.Name = "get_FSharpCase"
PhpFun.Args = []
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ PhpStatement.Return(PhpConst(PhpConstString(case.Name)))] }
{ PhpFun.Name = "CompareTo"
PhpFun.Args = ["other"]
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ for e in case.UnionCaseFields do
let cmp = PhpVar(ctx.MakeUniqueVar "cmp",None)
match e.FieldType.TypeDefinition.CompiledName with
| "int" ->
Assign(cmp,
PhpTernary( PhpBinaryOp(">",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ),
PhpConst(PhpConstNumber 1.),
PhpTernary(
PhpBinaryOp("<",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None)),
PhpConst(PhpConstNumber -1.),
PhpConst(PhpConstNumber 0.)
) ) )
| _ ->
Assign(cmp,
PhpMethod(PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
"CompareTo",
[PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ])
)
If(PhpBinaryOp("!=", cmp, PhpConst(PhpConstNumber 0.) ),
[PhpStatement.Return cmp],
[]
)
PhpStatement.Return (PhpConst (PhpConstNumber 0.))
]
}
]
Abstract = false
BaseType = None
Interfaces = [ PhpUnion.fSharpUnion; Core.icomparable ]
}
ctx.AddType(t) |> PhpType ]
else
[ let baseType =
{ Name = info.Entity.CompiledName
Fields = []
Methods = []
Abstract = true
BaseType = None
Interfaces = [PhpUnion.union; PhpUnion.fSharpUnion ]}
ctx.AddType(baseType) |> PhpType
for i, case in Seq.indexed info.Entity.UnionCases do
let t =
{ Name = caseName case
Fields = [ for e in case.UnionCaseFields do
{ Name = e.Name
Type = convertType e.FieldType } ]
Methods = [ { PhpFun.Name = "get_Case";
PhpFun.Args = []
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ PhpStatement.Return(PhpConst(PhpConstString(caseName case)))]
}
{ PhpFun.Name = "get_FSharpCase";
PhpFun.Args = []
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ PhpStatement.Return(PhpConst(PhpConstString(case.Name)))]
}
{ PhpFun.Name = "get_Tag"
PhpFun.Args = []
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ PhpStatement.Return(PhpConst(PhpConstNumber (float i)))]
}
{ PhpFun.Name = "CompareTo"
PhpFun.Args = ["other"]
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ let cmp = PhpVar(ctx.MakeUniqueVar "cmp",None)
Assign(cmp,
PhpTernary( PhpBinaryOp(">",
PhpMethod(PhpVar("this",None), "get_Tag", []),
PhpMethod(PhpVar("other", None), "get_Tag", []) ),
PhpConst(PhpConstNumber 1.),
PhpTernary(
PhpBinaryOp("<",
PhpMethod(PhpVar("this",None), "get_Tag", []),
PhpMethod(PhpVar("other", None), "get_Tag" , [])),
PhpConst(PhpConstNumber -1.),
PhpConst(PhpConstNumber 0.))))
if not case.HasFields then
PhpStatement.Return(cmp)
else
If(PhpBinaryOp("!=", cmp, PhpConst(PhpConstNumber 0.) ),
[PhpStatement.Return cmp],
[]
)
for e in case.UnionCaseFields do
let cmp = PhpVar(ctx.MakeUniqueVar "cmp",None)
match e.FieldType.TypeDefinition.CompiledName with
| "int" ->
Assign(cmp,
PhpTernary( PhpBinaryOp(">",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ),
PhpConst(PhpConstNumber 1.),
PhpTernary(
PhpBinaryOp("<",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None)),
PhpConst(PhpConstNumber -1.),
PhpConst(PhpConstNumber 0.)
) ) )
| _ ->
Assign(cmp,
PhpMethod(PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
"CompareTo",
[PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ])
)
If(PhpBinaryOp("!=", cmp, PhpConst(PhpConstNumber 0.) ),
[PhpStatement.Return cmp],
[]
)
PhpStatement.Return (PhpConst (PhpConstNumber 0.))
]
}
]
Abstract = false
BaseType = Some baseType
Interfaces = [ Core.icomparable ] }
ctx.AddType(t) |> PhpType ]
let convertRecord (ctx: PhpCompiler) (info: Fable.CompilerGeneratedConstructorInfo) =
[ let t =
{ Name = info.Entity.CompiledName
Fields = [ for e in info.Entity.FSharpFields do
{ Name = e.Name
Type = convertType e.FieldType } ]
Methods = [
{ PhpFun.Name = "CompareTo"
PhpFun.Args = ["other"]
PhpFun.Matchings = []
PhpFun.Static = false
PhpFun.Body =
[ for e in info.Entity.FSharpFields do
let cmp = PhpVar(ctx.MakeUniqueVar "cmp",None)
match e.FieldType.TypeDefinition.CompiledName with
| "int"
| "string" ->
Assign(cmp,
PhpTernary( PhpBinaryOp(">",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ),
PhpConst(PhpConstNumber 1.),
PhpTernary(
PhpBinaryOp("<",
PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None)),
PhpConst(PhpConstNumber -1.),
PhpConst(PhpConstNumber 0.)
) ) )
| _ ->
Assign(cmp,
PhpMethod(PhpProp(PhpVar("this",None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None),
"CompareTo",
[PhpProp(PhpVar("other", None), Prop.Field { Name = e.Name; Type = convertType e.FieldType }, None) ])
)
If(PhpBinaryOp("!=", cmp, PhpConst(PhpConstNumber 0.) ),
[PhpStatement.Return cmp],
[]
)
PhpStatement.Return (PhpConst (PhpConstNumber 0.))
] }
]
Abstract = false
BaseType = None
Interfaces = [ Core.icomparable ]}
ctx.AddType(t) |> PhpType ]
type ReturnStrategy =
| Return
| Let of string
| Do
| Target of string
let convertTest ctx test phpExpr =
match test with
| Fable.TestKind.UnionCaseTest(case,_) ->
let t = Map.find (caseName case) ctx.Types
PhpIsA(phpExpr, t)
| Fable.TestKind.ListTest(isCons) ->
PhpIsA(phpExpr, if isCons then PhpList.cons else PhpList.nil)
| Fable.OptionTest(isSome) ->
let isNull = PhpCall(PhpConst (PhpConstString "is_null"), [phpExpr])
if isSome then
PhpUnaryOp("!",isNull)
else
isNull
let rec getExprType =
function
| PhpVar(_, t) -> t
| PhpProp(_,_, t) -> t
| _ -> None
let rec convertExpr (ctx: PhpCompiler) (expr: Fable.Expr) =
match expr with
| Fable.Value(value,_) ->
convertValue ctx value
| Fable.Operation(Fable.BinaryOperation(op,left,right),t,_) ->
let opstr =
match op with
| BinaryOperator.BinaryMultiply -> "*"
| BinaryOperator.BinaryPlus ->
match t with
| Fable.Type.String -> "."
| _ -> "+"
| BinaryOperator.BinaryMinus -> "-"
| BinaryOperator.BinaryLess -> "<"
| BinaryOperator.BinaryGreater -> ">"
| BinaryOperator.BinaryLessOrEqual -> "<="
| BinaryOperator.BinaryGreaterOrEqual -> ">="
| BinaryOperator.BinaryAndBitwise -> "&"
| BinaryOperator.BinaryOrBitwise -> "|"
| BinaryOperator.BinaryEqual -> "=="