-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerator.fsx
More file actions
2481 lines (2152 loc) · 118 KB
/
Generator.fsx
File metadata and controls
2481 lines (2152 loc) · 118 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
open System.Text.Json
open System.IO
open System.Collections.Generic
let doc = JsonDocument.Parse (File.ReadAllText(Path.Combine(__SOURCE_DIRECTORY__, "dawn.json")))
let toOption ((exists : bool, value : 'a)) =
if exists then Some value
else None
let toOptionString ((exists : bool, value : JsonElement)) =
if exists && value.ValueKind = JsonValueKind.String then Some (value.GetString())
else None
module List =
let mapOption (mapping : 'a -> option<'b>) (l : list<'a>) =
let r = l |> List.map mapping
if r |> List.forall Option.isSome then
r |> List.map Option.get |> Some
else
None
type TypeRef = { TypeName : string; Annotation : option<string> }
module TypeRef =
let isFloat (t : TypeRef) =
match t.Annotation with
| None ->
t.TypeName = "float" || t.TypeName = "double"
| _ ->
false
let is64Bit (t : TypeRef) =
match t.Annotation with
| None ->
t.TypeName = "double" || t.TypeName = "int64_t" || t.TypeName = "uint64_t"
| _ ->
false
let isPointer (t : TypeRef) =
match t.Annotation with
| Some "*" | Some "const *" | Some "const*" -> true
| _ ->
match t.TypeName with
| "void *"
| "void const *" -> true
| _ -> false
type FieldDef =
{
Type : TypeRef
Name : string
Default : option<JsonElement>
Optional : bool
Length : option<string>
Tags : list<string>
}
module FieldDef =
let isUserData (a : FieldDef) =
(a.Type.TypeName = "void *" || (a.Type.TypeName = "void" && a.Type.Annotation = Some "*")) && a.Name.ToLower().Contains "userdata"
let tryParse (name : string) (e : JsonElement) =
match e.TryGetProperty("type") with
| (true, typ) when typ.ValueKind = JsonValueKind.String ->
let typ = typ.GetString()
let def = e.TryGetProperty("default") |> toOption
let annotation = e.TryGetProperty("annotation") |> toOptionString
let optional = e.TryGetProperty("optional") |> toOption |> Option.map (fun v -> v.GetBoolean()) |> Option.defaultValue false
let length =
match e.TryGetProperty("length") with
| (true, l) when l.ValueKind = JsonValueKind.String -> l.GetString() |> Some
| _ -> None
let tags =
match e.TryGetProperty "tags" with
| (true, t) -> List.init (t.GetArrayLength()) (fun i -> t[i].GetString())
| _ -> []
Some { Type = { TypeName = typ; Annotation = annotation }; Tags = tags; Name = name; Default = def; Optional = optional; Length = length }
| _ ->
None
[<RequireQualifiedAccess>]
type Direction =
| In
| Out
type StructDef =
{
Name : string
Extensible : option<Direction>
ChainRoots : list<string>
Chained : option<Direction>
Fields : list<FieldDef>
Tags : list<string>
}
type FunctionDef =
{
Name : string
Tags : list<string>
Return : TypeRef
Args : list<FieldDef>
}
module FunctionDef =
let tryParse (name : string) (obj : JsonElement) =
let args =
match obj.TryGetProperty("args") with
| (true, a) when a.ValueKind = JsonValueKind.Array ->
let len = a.GetArrayLength()
List.init len (fun i -> a.[i])
| _ ->
[]
let args =
args |> List.mapOption (fun a ->
match a.TryGetProperty "name" with
| (true, name) when name.ValueKind = JsonValueKind.String ->
FieldDef.tryParse (name.GetString()) a
| _ ->
None
)
let returns =
match obj.TryGetProperty("returns") with
| (true, r) ->
if r.ValueKind = JsonValueKind.String then
r.GetString()
elif r.ValueKind = JsonValueKind.Object then
match r.TryGetProperty "type" with
| (true, t) when t.ValueKind = JsonValueKind.String ->
t.GetString()
| _ ->
"void"
else
"void"
| _ ->
"void"
let tags =
match obj.TryGetProperty "tags" with
| (true, r) when r.ValueKind = JsonValueKind.Array ->
List.init (r.GetArrayLength()) (fun i -> r[i].GetString())
| _ ->
[]
match args with
| Some args ->
// TODO annotation??
Some { Name = name; Tags = tags; Return = { TypeName = returns; Annotation = None }; Args = args }
| None ->
None
let isBadWasmFunction (f : FunctionDef) =
f.Args.Length > 5 ||
f.Args |> List.exists (fun a -> TypeRef.is64Bit a.Type || TypeRef.isFloat a.Type)
type Enum =
{
Name : string
Values : list<string * int>
Flags : bool
}
type Alias =
{
Name : string
Type : TypeRef
}
type Native =
{
Name : string
WasmType : option<string>
}
type Object =
{
Name : string
Tags : list<string>
Methods : list<FunctionDef>
}
type Definition =
| Enum of Enum
| Delegate of FunctionDef
| Struct of StructDef
| Function of FunctionDef
| Alias of Alias
| Native of Native
| Object of Object
| CallbackInfo of StructDef
member x.Name =
match x with
| Enum { Name = n } -> n
| Delegate { Name = n } -> n
| Struct { Name = n } -> n
| Function { Name = n } -> n
| Alias { Name = n } -> n
| Native { Name = n } -> n
| Object { Name = n } -> n
| CallbackInfo { Name = n } -> n
member x.ReferencedTypes =
match x with
| Enum _ | Native _ ->
Seq.empty
| Delegate { Args = a; Return = r } | Function { Args = a; Return = r } ->
Seq.append (Seq.singleton r) (a |> Seq.map (fun a -> a.Type))
| Struct { Fields = f } | CallbackInfo { Fields = f } ->
f |> Seq.map (fun f -> f.Type)
| Alias { Type = t } -> Seq.singleton t
| Object { Methods = ms } ->
ms |> Seq.collect (fun m ->
m.Args |> Seq.map (fun a -> a.Type)
)
let allList = ResizeArray()
module StructDef =
let parse (name : string) (obj : JsonElement) =
let extensible =
match obj.TryGetProperty "extensible" with
| (true, e) when e.ValueKind = JsonValueKind.String ->
match e.GetString() with
| "in" -> Some Direction.In
| "out" -> Some Direction.Out
| e -> failwithf "bad direction: %A" e
| _ ->
None
let tags =
match obj.TryGetProperty("tags") with
| (true, t) when t.ValueKind = JsonValueKind.Array ->
List.init (t.GetArrayLength()) (fun i -> t[i].GetString())
| _ ->
[]
let fields =
match obj.TryGetProperty("members") with
| (true, mems) ->
let len = mems.GetArrayLength()
List.init len (fun i ->
let mem = mems[i]
let name = mem.GetProperty("name").GetString()
FieldDef.tryParse name mem
// let typName = mem.GetProperty("type").GetString()
// let name = mem.GetProperty("name").GetString()
// let def = mem.TryGetProperty("default") |> toOption
// let annotation = mem.TryGetProperty("annotation") |> toOptionString
// let optional = mem.TryGetProperty("optional") |> toOption |> Option.map (fun v -> v.GetBoolean()) |> Option.defaultValue false
// let length = mem.TryGetProperty("length") |> toOptionString
//
// let tags =
// match mem.TryGetProperty("tags") with
// | (true, t) when t.ValueKind = JsonValueKind.Array ->
// List.init (t.GetArrayLength()) (fun i -> t[i].GetString())
// | _ ->
// []
//
// // if tags |> List.exists (fun t -> t = "deprecated") then
// // None
// // else
// let typRef = { TypeName = typName; Annotation = annotation }
// Some { Type = typRef; Name = name; Default = def; Optional = optional; Length = length }
)
|> List.choose id
| _ ->
[]
let chainRoots =
match obj.TryGetProperty "chain roots" with
| (true, roots) when roots.ValueKind = JsonValueKind.Array ->
List.init (roots.GetArrayLength()) (fun i -> roots[i].GetString())
| _ ->
[]
let chained =
match obj.TryGetProperty "chained" with
| (true, c) when c.ValueKind = JsonValueKind.String ->
match c.GetString() with
| "in" -> Some Direction.In
| "out" -> Some Direction.Out
| e -> failwithf "bad direction: %A" e
| _ ->
None
{
Extensible = extensible
Chained = chained
Name = name
ChainRoots = chainRoots
Fields = fields
Tags = tags
}
for kv in doc.RootElement.EnumerateObject() do
let obj = kv.Value
if obj.ValueKind = JsonValueKind.Object then
match obj.TryGetProperty "category" with
| (true, cat) ->
match cat.GetString() with
| "callback info" ->
let name = kv.Name
let s = StructDef.parse name obj
let s =
{ s with
Extensible = Some Direction.In
Fields =
s.Fields @ [
{ Name = "userdata1"; Default = None; Optional = false; Length = None; Tags = []; Type = { TypeName = "void *"; Annotation = None}}
{ Name = "userdata2"; Default = None; Optional = false; Length = None; Tags = []; Type = { TypeName = "void *"; Annotation = None}}
]
}
allList.Add (CallbackInfo s)
| "object" ->
let tags =
match obj.TryGetProperty "tags" with
| (true, t) when t.ValueKind = JsonValueKind.Array ->
List.init (t.GetArrayLength()) (fun i -> t[i].GetString())
| _ ->
[]
match obj.TryGetProperty "methods" with
| (true, ms) when ms.ValueKind = JsonValueKind.Array ->
let meths =
List.init (ms.GetArrayLength()) (fun i ->
match ms.[i].TryGetProperty "name" with
| (true, n) when n.ValueKind = JsonValueKind.String ->
match FunctionDef.tryParse (n.GetString()) ms.[i] with
| Some f -> Some f
| None -> None
| _ ->
None
)
let releaseMeth =
{
FunctionDef.Name = "release"
Tags = []
Return = { TypeName = "void"; Annotation = None }
Args = []
}
let addRefMeth =
{
FunctionDef.Name = "add ref"
Tags = []
Return = { TypeName = "void"; Annotation = None }
Args = []
}
match meths |> List.mapOption id with
| Some meths ->
let meths = meths @ [releaseMeth; addRefMeth]
allList.Add (Object { Name = kv.Name; Tags = tags; Methods = meths })
| None ->
()
| _ ->
allList.Add (Object { Name = kv.Name; Tags = tags; Methods = [] })
() // TODO
| "native" ->
let w =
match obj.TryGetProperty "wasm type" with
| (true, w) when w.ValueKind = JsonValueKind.String ->
let w = w.GetString()
Some w
| _ ->
None
allList.Add(Native { Name = kv.Name; WasmType = w })
| "typedef" ->
match obj.TryGetProperty "type" with
| (true, t) when t.ValueKind = JsonValueKind.String ->
let annotation = obj.TryGetProperty("annotation") |> toOptionString
allList.Add(Alias { Name = kv.Name; Type = { TypeName = t.GetString(); Annotation = annotation } })
| _ ->
()
| "constant" ->
() // simple
| "enum" | "bitmask" ->
let values =
match obj.TryGetProperty "values" with
| (true, vs) when vs.ValueKind = JsonValueKind.Array ->
List.init (vs.GetArrayLength()) (fun i ->
let v = vs.[i]
let name = v.GetProperty("name").GetString()
let value = v.GetProperty("value").GetInt32()
let tags =
match v.TryGetProperty "tags" with
| (true, tags) when tags.ValueKind = JsonValueKind.Array ->
Array.init (tags.GetArrayLength()) (fun i -> tags.[i].GetString())
| _ ->
[||]
let value =
if tags |> Array.exists (fun t -> t = "dawn") then 0x50000 ||| value
else value
name, value
)
| _ ->
[]
let e = { Name = kv.Name; Values = values; Flags = cat.GetString() = "bitmask" }
allList.Add (Enum e)
| "function" ->
match FunctionDef.tryParse kv.Name obj with
| Some f ->
allList.Add (Function f)
| None ->
()
| "function pointer" ->
match FunctionDef.tryParse kv.Name obj with
| Some f ->
allList.Add (Delegate f)
| None ->
()
| "callback function" ->
match FunctionDef.tryParse kv.Name obj with
| Some f ->
let f =
{ f with
Args =
f.Args @ [
{ Name = "userdata1"; Tags = []; Type = { TypeName = "void *"; Annotation = None }; Default = None; Optional = false; Length = None }
{ Name = "userdata2"; Tags = []; Type = { TypeName = "void *"; Annotation = None }; Default = None; Optional = false; Length = None }
]
}
allList.Add (Delegate f)
| None ->
()
| "structure" ->
let name = kv.Name
let s = StructDef.parse name obj
allList.Add (Struct s)
| cat ->
failwithf "UNKNOWN CATEGORY: %A" cat
| _ ->
()
let nonExistentTypes = Set.empty // Set.ofList ["INTERNAL_HAVE_EMDAWNWEBGPU_HEADER"]
let all =
Seq.toArray allList
|> Array.choose (fun a ->
match a with
| Object o ->
let meths =
o.Methods |> List.filter (fun m ->
let deprecated = m.Tags |> List.exists (fun t -> t = "deprecated")
let bad =
Set.contains m.Return.TypeName nonExistentTypes ||
m.Args |> Seq.exists (fun a -> Set.contains a.Type.TypeName nonExistentTypes)
not deprecated && not bad
)
Some (Object { o with Methods = meths })
// else
// None
| Struct def ->
if def.Name = "INTERNAL_HAVE_EMDAWNWEBGPU_HEADER" then None
else Some a
| _ ->
Some a
)
let table = Dictionary()
for a in all do
table.[a.Name] <- a
let tryResolveType (t : TypeRef) =
match table.TryGetValue t.TypeName with
| (true, entry) ->
Some entry
| _ ->
None
let childTypes, parentTypes =
let mutable res = Map.empty
let mutable parents = Map.empty
for a in all do
match a with
| Object o ->
for meth in o.Methods do
if meth.Name.StartsWith "create " then
let parent = o.Name
let child = meth.Return.TypeName
match tryResolveType meth.Return with
| Some (Object _) ->
let mutable otherParent = None
let mutable isChild = true
match Map.tryFind child parents with
| Some (Some p) ->
if p <> parent then
parents <- Map.add child None parents
otherParent <- Some p
isChild <- false
| Some None ->
isChild <- false
| None ->
parents <- Map.add child (Some parent) parents
match otherParent with
| Some other ->
match Map.tryFind other res with
| Some l ->
res <- Map.add other (Map.remove child l) res
| None ->
()
| None ->
()
if isChild then
match Map.tryFind o.Name res with
| Some l ->
res <- Map.add o.Name (Map.add meth.Return.TypeName meth.Name l) res
| None ->
res <- Map.add o.Name (Map.ofList [meth.Return.TypeName, meth.Name]) res
| _ ->
()
| _ ->
()
let mutable pp = Map.empty
for KeyValue(c, p) in parents do
match p with
| Some p -> pp <- Map.add c p pp
| None -> ()
res, pp
let deviceChildren =
Set.ofList [
"queue"
"buffer"
"shared buffer memory"
"texture"
"bind group"
"command encoder"
//"compute pipeline"
"external texture"
"pipeline layout"
"query set"
"render bundle encoder"
//"render pipeline"
"sampler"
"shader module"
]
let rx = System.Text.RegularExpressions.Regex "^[0-9]+.*$"
// print native wrapper
let pascalCase (str : string) =
let res =
str.Split(" ")
|> Array.map (fun str -> str.Substring(0, 1).ToUpper() + str.Substring(1))
|> String.concat ""
if rx.IsMatch res then "D" + res
else res
let camelCase (str : string) =
let res =
str.Split(" ")
|> Array.mapi (fun i str -> if i > 0 then str.Substring(0, 1).ToUpper() + str.Substring(1) else str)
|> String.concat ""
if res = "type" then "typ"
elif res = "module" then "moodule"
elif rx.IsMatch res then "d" + res
else res
for (KeyValue(c, p)) in parentTypes do
printfn $"{pascalCase p} -> {pascalCase c}"
for (KeyValue(p, cs)) in childTypes do
printfn $"{pascalCase p}"
for (KeyValue(c, m)) in cs do
printfn $" .{pascalCase m} : {pascalCase c}"
//
// let deviceChild =
// let device =
// allList |> Seq.pick (fun d ->
// match d with
// | Object o when o.Name = "device" -> Some o
// | _ -> None
// )
//
// device.Methods
// |> Seq.choose (fun m ->
// if m.Name.StartsWith "create " then
// match tryResolveType m.Return with
// | Some (Object o) ->
// Some o.Name
// | _ ->
// None
// else
// None
// )
// |> Set.ofSeq
//
// for c in deviceChild do
// printfn "%0A" c
let isDawn (tags : list<string>) =
tags = [] || tags |> List.exists (fun t -> t = "dawn" || t = "native")
let isEmscripten (tags : list<string>) =
tags = [] || tags |> List.exists (fun t -> t = "emscripten")
module Native =
let rec nativeTypeName (t : TypeRef) =
let def = table.[t.TypeName]
let baseType =
match def with
| Object o -> "WGPU" + pascalCase o.Name
| Enum e -> "WGPU" + pascalCase e.Name
| Delegate d -> "WGPU" + pascalCase d.Name
| Alias a -> nativeTypeName a.Type
| Struct a -> "WGPU" + pascalCase a.Name
| Function _ -> failwith "not a type"
| CallbackInfo c -> "WGPU" + pascalCase c.Name
| Native n -> n.Name
match t.Annotation with
| None -> baseType
| Some a ->
match a with
| "*" -> baseType + "*"
| "const*" -> "const " + baseType + "*"
| "const*const*" -> "const " + baseType + "* const*"
| _ -> failwith "asdasdsad"
let print (fileName : string) (emscripten : bool) =
let b = System.Text.StringBuilder()
let printfn fmt = fmt |> Printf.kprintf (fun str -> b.AppendLine str |> ignore)
let functionFormat =
if emscripten then "EMSCRIPTEN_KEEPALIVE {0}"
else "DllExport({0})"
let checkTags =
if emscripten then isEmscripten
else isDawn
if emscripten then
printfn "#include <emscripten.h>"
printfn "#include <emscripten/html5.h>"
printfn "#include <SDL/SDL_image.h>"
printfn "typedef void* WGPUExternalTexture;"
else
printfn "#include \"dllexport.h\""
printfn "#include <string.h>"
printfn "#include <stdlib.h>"
printfn "#include <stdio.h>"
printfn "#include <stdint.h>"
if emscripten then
printfn "#include \"webgpu/webgpu.h\""
else
printfn "#include \"dawn/webgpu_cpp.h\""
printfn "#include \"dawn/webgpu.h\""
printfn "#include \"dawn/native/DawnNative.h\""
printfn "DllExport(int) gpuEnumerateAdapters(const WGPURequestAdapterOptions* options, int adaptersLen, WGPUAdapter* adapters, WGPUInstance* inst) {"
printfn " auto instance = std::make_unique<dawn::native::Instance>();"
printfn " auto i = instance->Get();"
printfn " *inst = i;"
printfn " wgpuInstanceAddRef(i);"
printfn " std::vector<dawn::native::Adapter> res = instance->EnumerateAdapters(options);"
printfn " if(adapters && adaptersLen >= res.size()) {"
printfn " for(int i = 0; i < res.size(); i++) {"
printfn " "
printfn " adapters[i] = res[i].Get();"
printfn " wgpuAdapterAddRef(adapters[i]);"
printfn " }"
printfn " }"
printfn " return res.size();"
printfn "}"
// printfn "DllExport(WGPUSurface) gpuInstanceCreateGLFWSurface(WGPUInstance self, const void* window) {"
// printfn " auto instance = wgpu::Instance(self);"
// printfn " auto surf = wgpu::glfw::CreateSurfaceForWindow(instance, (GLFWwindow*)window);"
// printfn " auto handle = surf.Get();"
// printfn " wgpuSurfaceAddRef(handle);"
// printfn " return handle;"
// printfn "}"
for a in all do
let functions =
match a with
| Enum _ | Delegate _ | Alias _ | Native _ | CallbackInfo _ | Struct _ ->
[]
| Function f ->
if checkTags f.Tags then [f]
else []
| Object o ->
if checkTags o.Tags then
o.Methods |> List.choose (fun m ->
if checkTags m.Tags then
let name = o.Name + " " + m.Name
let args = { Name = "self"; Tags = []; Type = { TypeName = o.Name; Annotation = None }; Default = None; Optional = false; Length = None } :: m.Args
Some { m with Name = name; Args = args }
else
None
)
else
[]
for m in functions do
let name = m.Name
let args = m.Args
if FunctionDef.isBadWasmFunction m then
printfn "typedef struct { "
for a in args do
printfn " %s %s;" (nativeTypeName a.Type) (pascalCase a.Name)
printfn "} WGPU%sArgs;" (pascalCase name)
let argdef = sprintf "const WGPU%sArgs* args" (pascalCase name)
let argref = args |> List.map (fun a -> sprintf "args->%s" (pascalCase a.Name)) |> String.concat ", "
printfn $"{System.String.Format(functionFormat, nativeTypeName m.Return)} gpu{pascalCase name}({argdef}) {{"
printfn $" return wgpu{pascalCase name}({argref});"
printfn $"}}"
else
let argdef = args |> List.map (fun a -> nativeTypeName a.Type + " " + camelCase a.Name) |> String.concat ", "
let argref = args |> List.map (fun a -> camelCase a.Name) |> String.concat ", "
printfn $"{System.String.Format(functionFormat, nativeTypeName m.Return)} gpu{pascalCase name}({argdef}) {{"
printfn $" return wgpu{pascalCase name}({argref});"
printfn $"}}"
()
()
File.WriteAllText(fileName, b.ToString())
module Enums =
let print() =
let b = System.Text.StringBuilder()
let printfn fmt = fmt |> Printf.kprintf (fun str -> b.AppendLine str |> ignore)
printfn "namespace rec WebGPU"
printfn "open System"
printfn "#nowarn \"9\""
for a in all do
match a with
| Enum e ->
if e.Flags then printfn "[<Flags>]"
printfn "type %s =" (pascalCase e.Name)
for (name, value) in e.Values do
let value =
if e.Flags then sprintf "%dL" value
else sprintf "%d" value
printfn " | %s = %s" (pascalCase name) value
| _ ->
()
File.WriteAllText(Path.Combine(__SOURCE_DIRECTORY__, "src", "WebGPU", "Enums.fs"), b.ToString())
module RawWrapper =
let rec externName (t : TypeRef) =
let def = table.[t.TypeName]
let baseType =
match def with
| Object o -> "nativeint"
| Enum e -> pascalCase e.Name
| Delegate d -> "nativeint" //pascalCase d.Name
| Alias a -> externName a.Type
| Struct a -> pascalCase a.Name
| Function _ -> failwith "not a type"
| CallbackInfo c -> pascalCase c.Name
| Native n ->
match n.Name with
| "int8_t" -> "int8"
| "uint8_t" -> "uint8"
| "int16_t" -> "int16"
| "uint16_t" -> "uint16"
| "int32_t" | "int" -> "int"
| "uint32_t" -> "uint32"
| "int64_t" -> "int64"
| "uint64_t" -> "uint64"
| "void" -> "void"
| "bool" -> "int"
| "char" -> "byte"
| "float" -> "float32"
| "double" -> "double"
| "size_t" -> "unativeint"
| "void *" | "void const *" -> "nativeint"
| _ -> failwithf "bad native type: %A" n.Name
match t.Annotation with
| None -> baseType
| Some a ->
match a with
| "*" -> baseType + "*"
| "const*" -> baseType + "*"
| "const*const*" -> baseType + "**"
| _ -> failwith "asdasdsad"
let rec fsharpName (t : TypeRef) =
let def = table.[t.TypeName]
let baseType =
match def with
| Object o -> "nativeint"
| Enum e -> pascalCase e.Name
| Delegate d -> "nativeint" //pascalCase d.Name
| Alias a -> fsharpName a.Type
| Struct a -> pascalCase a.Name
| Function _ -> failwith "not a type"
| CallbackInfo c -> pascalCase c.Name
| Native n ->
match n.Name with
| "int8_t" -> "int8"
| "uint8_t" -> "uint8"
| "int16_t" -> "int16"
| "uint16_t" -> "uint16"
| "int32_t" | "int" -> "int"
| "uint32_t" -> "uint32"
| "int64_t" -> "int64"
| "uint64_t" -> "uint64"
| "void" -> "unit"
| "bool" -> "int"
| "char" -> "byte"
| "float" -> "float32"
| "double" -> "double"
| "size_t" -> "unativeint"
| "void *" | "void const *" -> "nativeint"
| _ -> failwithf "bad native type: %A" n.Name
match t.Annotation with
| None -> baseType
| Some a ->
if baseType = "unit" then
"nativeint"
else
match a with
| "*" -> $"nativeptr<{baseType}>"
| "const*" -> $"nativeptr<{baseType}>"
| "const*const*" -> $"nativeptr<nativeptr<{baseType}>>"
| _ -> failwith "asdasdsad"
[<Struct>]
type TypeSize(ptrCount : int, size : int, custom : Map<string, int>) =
member x.PointerCount = ptrCount
member x.Size = size
member x.Custom : Map<string, int> = custom
static member Zero = TypeSize(0, 0, Map.empty)
static member (+) (l : TypeSize, r : TypeSize) =
let mutable current = l.Custom
for KeyValue(k, c) in r.Custom do
match Map.tryFind k current with
| Some cnt -> current <- Map.add k (cnt + c) current
| None -> current <- Map.add k c current
TypeSize(
l.PointerCount + r.PointerCount,
l.Size + r.Size,
current
)
static member Pointer = TypeSize(1, 0, Map.empty)
static member Fixed s = TypeSize(0, s, Map.empty)
static member CustomSize str = TypeSize(0, 0, Map.ofList [str, 1])
override x.ToString() =
let baseStr =
if ptrCount <= 0 then
if size <= 0 then
"0n"
else
sprintf "%dn" size
elif ptrCount = 1 then
if size <= 0 then "sizeof<nativeint>"
else sprintf "sizeof<nativeint> + %dn" size
else
if size <= 0 then sprintf "%d * sizeof<nativeint>" ptrCount
else sprintf "%d * sizeof<nativeint> + %dn" ptrCount size
let suffix =
custom |> Seq.map (fun (KeyValue(k, v)) ->
if v = 1 then k
else sprintf "%d * %s" v k
) |> String.concat " + "
if suffix.Length = 0 then baseStr
else baseStr + " + " + suffix
let print() =
let b = System.Text.StringBuilder()
let printfn fmt = fmt |> Printf.kprintf (fun str -> b.AppendLine str |> ignore)
printfn "namespace rec WebGPU.Raw"
printfn "open System.Collections.Generic"
printfn "open System"
printfn "open System.Runtime.InteropServices"
printfn "open Microsoft.FSharp.NativeInterop"
printfn "open WebGPU"
printfn "#nowarn \"9\""
for a in all do
match a with
| Enum e ->
()
//
// if e.Flags then printfn "[<Flags>]"
// printfn "type %s =" (pascalCase e.Name)
// for (name, value) in e.Values do
//
// printfn " | %s = %d" (pascalCase name) value
| Alias a ->
printfn "type %s = %s" (pascalCase a.Name) (fsharpName a.Type)
| Delegate d ->
let ret = fsharpName d.Return
match d.Args with
| [] ->
printfn "type %s = delegate of unit -> %s" (pascalCase d.Name) ret
| _ ->
let args = d.Args |> List.map (fun a -> sprintf "%s : %s" (camelCase a.Name) (fsharpName a.Type)) |> String.concat " * "
printfn "type %s = delegate of %s -> %s" (pascalCase d.Name) args ret
| Struct s | CallbackInfo s ->
if s.Fields.IsEmpty && Option.isNone s.Extensible && List.isEmpty s.ChainRoots then
printfn "[<StructLayout(LayoutKind.Explicit, Size = 4)>]"
printfn "type %s = struct end" (pascalCase s.Name)
else
let fields = s.Fields
let fields =
if Option.isSome s.Chained then { Name = "s type"; Tags = []; Type = { TypeName = "s type"; Annotation = None }; Default = None; Optional = false; Length = None } :: fields
else fields
let fields =
if Option.isSome s.Extensible || Option.isSome s.Chained then { Name = "next in chain"; Tags = []; Type = { TypeName = "void"; Annotation = Some "const*" }; Optional = true; Default = None; Length = None } :: fields
else fields
let args =
fields |> List.map (fun f ->
let typ = fsharpName f.Type
let name = camelCase f.Name
$"{name} : {typ}"