forked from microsoft/TypeScript-DOM-lib-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TS.fsx
1497 lines (1263 loc) · 64 KB
/
TS.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
#r "packages/FSharp.Data/lib/net40/FSharp.Data.dll"
#r "System.Xml.Linq.dll"
open System
open System.Collections.Generic
open System.IO
open System.Text
open System.Text.RegularExpressions
open System.Web
open Microsoft.FSharp.Reflection
open FSharp.Data
module GlobalVars =
let inputFolder = Path.Combine(__SOURCE_DIRECTORY__, "inputfiles")
let outputFolder = Path.Combine(__SOURCE_DIRECTORY__, "generated")
// Create output folder
if not (Directory.Exists(outputFolder)) then
Directory.CreateDirectory(outputFolder) |> ignore
let makeTextWriter fileName = File.CreateText(Path.Combine(outputFolder, fileName)) :> TextWriter
let tsWebOutput = makeTextWriter "dom.generated.d.ts"
let tsWorkerOutput = makeTextWriter "webworker.generated.d.ts"
let defaultEventType = "Event"
module Helpers =
/// Quick checker for option type values
let OptionCheckValue value = function
| Some v when v = value -> true
| _ -> false
let unionToString (x: 'a) =
match FSharpValue.GetUnionFields(x, typeof<'a>) with
| case, _ -> case.Name
module Option =
let runIfSome f x =
match x with
| Some x' -> f x'
| _ -> ()
let toBool f x =
match x with
| Some x' -> f x'
| _ -> false
type String with
member this.TrimStartString str =
if this.StartsWith(str) then this.Substring(str.Length)
else this
module Types =
open Helpers
type Flavor = Worker | Web | All with
override x.ToString() = unionToString x
type Browser = XmlProvider<"sample.xml", Global=true>
// Printer for print to string
type StringPrinter() =
let output = StringBuilder()
let stack = StringBuilder()
let mutable curTabCount = 0
member this.GetCurIndent() = String.replicate curTabCount " "
member this.Print content = Printf.kprintf (output.Append >> ignore) content
member this.PrintToStack content = Printf.kprintf (stack.Append >> ignore) content
member this.ClearStack () = stack.Clear() |> ignore
member this.PrintStackContent () = this.Print "%s" (stack.ToString())
member this.Printl content =
Printf.kprintf (fun s -> output.Append("\r\n" + this.GetCurIndent() + s) |> ignore) content
member this.PrintlToStack content =
Printf.kprintf (fun s -> stack.Append("\r\n" + this.GetCurIndent() + s) |> ignore) content
member this.StackIsEmpty () = stack.Length = 0
member this.IncreaseIndent() = curTabCount <- curTabCount + 1
member this.SetIndent indentNum = curTabCount <- indentNum
member this.DecreaseIndent() = curTabCount <- Math.Max(curTabCount - 1, 0)
member this.ResetIndent() = curTabCount <- 0
member this.PrintWithAddedIndent content =
Printf.kprintf (fun s -> output.Append("\r\n" + this.GetCurIndent() + " " + s) |> ignore) content
member this.GetResult() = output.ToString()
member this.Clear() = output.Clear() |> ignore
member this.Reset() =
this.Clear()
this.ResetIndent()
type Event = { Name : string; Type : string }
/// Method parameter
type Param = {
Type : string
Name : string
Optional : bool
Variadic : bool
Nullable : bool }
/// Function overload
type Overload = { ParamCombinations : Param list; ReturnTypes : string list; Nullable : Boolean } with
member this.IsEmpty = this.ParamCombinations.IsEmpty && (this.ReturnTypes = [ "void" ] || this.ReturnTypes = [ "" ])
type Function =
| Method of Browser.Method
| Ctor of Browser.Constructor
| CallBackFun of Browser.CallbackFunction
// Note:
// Eventhandler's name and the eventName are not just off by "on".
// For example, handlers named "onabort" may handle "SVGAbort" event in the XML file
type EventHandler = { Name : string; EventName : string; EventType : string }
/// Decide which members of a function to emit
type EmitScope =
| StaticOnly
| InstanceOnly
| All
type ExtendConflict = { BaseType: string; ExtendType: string list; MemberNames: string list }
module InputJson =
open Helpers
open Types
type InputJsonType = JsonProvider<"inputfiles/sample.json">
let overriddenItems =
File.ReadAllText(GlobalVars.inputFolder + @"/overridingTypes.json") |> InputJsonType.Parse
let removedItems =
File.ReadAllText(GlobalVars.inputFolder + @"/removedTypes.json") |> InputJsonType.Parse
let addedItems =
File.ReadAllText(GlobalVars.inputFolder + @"/addedTypes.json") |> InputJsonType.Parse
// This is the kind of items in the external json files that are used as a
// correction for the spec.
type ItemKind =
| Property
| Method
| Constant
| Constructor
| Interface
| Callback
| Indexer
| SignatureOverload
| TypeDef
| Extends
override x.ToString() =
match x with
| Property _ -> "property"
| Method _ -> "method"
| Constant _ -> "constant"
| Constructor _ -> "constructor"
| Interface _ -> "interface"
| Callback _ -> "callback"
| Indexer _ -> "indexer"
| SignatureOverload _ -> "signatureoverload"
| TypeDef _ -> "typedef"
| Extends _ -> "extends"
let getItemByName (allItems: InputJsonType.Root []) (itemName: string) (kind: ItemKind) otherFilter =
let filter (item: InputJsonType.Root) =
OptionCheckValue itemName item.Name &&
item.Kind.ToLower() = kind.ToString() &&
otherFilter item
allItems |> Array.tryFind filter
let matchInterface iName (item: InputJsonType.Root) =
item.Interface.IsNone || item.Interface.Value = iName
let getOverriddenItemByName itemName (kind: ItemKind) iName =
getItemByName overriddenItems itemName kind (matchInterface iName)
let getRemovedItemByName itemName (kind: ItemKind) iName =
getItemByName removedItems itemName kind (matchInterface iName)
let getAddedItemByName itemName (kind: ItemKind) iName =
getItemByName addedItems itemName kind (matchInterface iName)
let getItems (allItems: InputJsonType.Root []) (kind: ItemKind) (flavor: Flavor) =
allItems
|> Array.filter (fun t ->
t.Kind.ToLower() = kind.ToString() &&
(t.Flavor.IsNone || t.Flavor.Value = flavor.ToString() || flavor = Flavor.All))
let getOverriddenItems = getItems overriddenItems
let getAddedItems = getItems addedItems
let getRemovedItems = getItems removedItems
let getAddedItemsByInterfaceName kind flavor iName =
getAddedItems kind flavor |> Array.filter (matchInterface iName)
let getOverriddenItemsByInterfaceName kind flavor iName =
getOverriddenItems kind flavor |> Array.filter (matchInterface iName)
let getRemovedItemsByInterfaceName kind flavor iName =
getRemovedItems kind flavor |> Array.filter (matchInterface iName)
module CommentJson =
type CommentJsonType = JsonProvider<"inputfiles/comments.json", InferTypesFromValues=false>
let comments = File.ReadAllText(Path.Combine(GlobalVars.inputFolder, "comments.json")) |> CommentJsonType.Parse
type InterfaceCommentItem = { Property: Map<string, string>; Method: Map<string, string>; Constructor: string option }
let commentMap =
comments.Interfaces
|> Array.map (fun i ->
let propertyMap = i.Members.Property |> Array.map (fun p -> (p.Name, p.Comment)) |> Map.ofArray
let methodMap = i.Members.Method |> Array.map (fun m -> (m.Name, m.Comment)) |> Map.ofArray
(i.Name, { Property = propertyMap; Method = methodMap; Constructor = i.Members.Constructor }))
|> Map.ofArray
let GetCommentForProperty iName pName =
match commentMap.TryFind iName with
| Some i -> i.Property.TryFind pName
| _ -> None
let GetCommentForMethod iName mName =
match commentMap.TryFind iName with
| Some i -> i.Method.TryFind mName
| _ -> None
let GetCommentForConstructor iName =
match commentMap.TryFind iName with
| Some i -> i.Constructor
| _ -> None
module Data =
open Helpers
open Types
// Used to decide if a member should be emitted given its static property and
// the intended scope level.
let inline matchScope scope (x: ^a when ^a: (member Static: Option<'b>)) =
if scope = EmitScope.All then true
else
let isStatic = (^a: (member Static: Option<'b>)x)
if isStatic.IsSome then scope = EmitScope.StaticOnly
else scope = EmitScope.InstanceOnly
let matchInterface iName (x: InputJson.InputJsonType.Root) =
x.Interface.IsNone || x.Interface.Value = iName
/// Parameter cannot be named "default" in JavaScript/Typescript so we need to rename it.
let AdjustParamName name =
match name with
| "default" -> "_default"
| "delete" -> "_delete"
| "continue" -> "_continue"
| _ -> name
/// Parse the xml input file
let browser =
(new StreamReader(Path.Combine(GlobalVars.inputFolder, "browser.webidl.xml"))).ReadToEnd() |> Browser.Parse
let worker =
(new StreamReader(Path.Combine(GlobalVars.inputFolder, "webworkers.specidl.xml"))).ReadToEnd() |> Browser.Parse
/// Check if the given element should be disabled or not
/// reason is that ^a can be an interface, property or method, but they
/// all share a 'tag' property
let inline ShouldKeep flavor (i: ^a when ^a: (member Tags: string option)) =
let filterByTag =
match (^a: (member Tags: string option) i) with
| Some tags ->
match flavor with
| Flavor.All -> true
| Flavor.Web -> tags <> "MSAppOnly" && tags <> "WinPhoneOnly"
| Flavor.Worker -> tags <> "IEOnly"
| _ -> true
filterByTag
// Global interfacename to interface object map
let allWebNonCallbackInterfaces =
Array.concat [| browser.Interfaces; browser.MixinInterfaces.Interfaces |]
let allWebInterfaces =
Array.concat [| browser.Interfaces; browser.CallbackInterfaces.Interfaces; browser.MixinInterfaces.Interfaces |]
let allWorkerAdditionalInterfaces =
Array.concat [| worker.Interfaces; worker.MixinInterfaces.Interfaces |]
let allInterfaces =
Array.concat [| allWebInterfaces; allWorkerAdditionalInterfaces |]
let inline toNameMap< ^a when ^a: (member Name: string) > (data: array< ^a > ) =
data
|> Array.map (fun x -> ((^a: (member Name: string) x), x))
|> Map.ofArray
let allInterfacesMap =
allInterfaces |> toNameMap
let allDictionariesMap =
Array.concat [| browser.Dictionaries; worker.Dictionaries |]
|> toNameMap
let allEnumsMap =
Array.concat [| browser.Enums; worker.Enums |]
|> toNameMap
let allCallbackFuncs =
Array.concat [| browser.CallbackFunctions; worker.CallbackFunctions |]
|> toNameMap
let GetInterfaceByName = allInterfacesMap.TryFind
type KnownWorkerInterfaceType = JsonProvider<"inputfiles/knownWorkerInterfaces.json", InferTypesFromValues=false>
let knownWorkerInterfaces =
File.ReadAllText(Path.Combine(GlobalVars.inputFolder, "knownWorkerInterfaces.json"))
|> KnownWorkerInterfaceType.Parse
|> set
let GetAllInterfacesByFlavor flavor =
match flavor with
| Flavor.Web -> allWebInterfaces |> Array.filter (ShouldKeep Web)
| Flavor.All -> allWebInterfaces |> Array.filter (ShouldKeep Flavor.All)
| Flavor.Worker ->
let isFromBrowserXml = allWebInterfaces |> Array.filter (fun i -> knownWorkerInterfaces.Contains i.Name)
Array.append isFromBrowserXml allWorkerAdditionalInterfaces
let GetNonCallbackInterfacesByFlavor flavor =
match flavor with
| Flavor.Web -> allWebNonCallbackInterfaces |> Array.filter (ShouldKeep Flavor.Web)
| Flavor.All -> allWebNonCallbackInterfaces |> Array.filter (ShouldKeep Flavor.All)
| Flavor.Worker ->
let isFromBrowserXml = allWebNonCallbackInterfaces |> Array.filter (fun i -> knownWorkerInterfaces.Contains i.Name)
Array.append isFromBrowserXml allWorkerAdditionalInterfaces
let GetPublicInterfacesByFlavor flavor =
match flavor with
| Flavor.Web | Flavor.All -> browser.Interfaces |> Array.filter (ShouldKeep flavor)
| Flavor.Worker ->
let isFromBrowserXml = browser.Interfaces |> Array.filter (fun i -> knownWorkerInterfaces.Contains i.Name)
Array.append isFromBrowserXml worker.Interfaces
let GetCallbackFuncsByFlavor flavor =
browser.CallbackFunctions
|> Array.filter (fun cb -> (flavor <> Flavor.Worker || knownWorkerInterfaces.Contains cb.Name) && ShouldKeep flavor cb)
/// Event name to event type map
let eNameToEType =
[ for i in allWebNonCallbackInterfaces do
if i.Events.IsSome then yield! i.Events.Value.Events ]
|> List.map (fun (e : Browser.Event) ->
let eType =
match e.Name with
| "abort" -> "UIEvent"
| "complete" -> "Event"
| "click" -> "MouseEvent"
| "error" -> "ErrorEvent"
| "load" -> "Event"
| "loadstart" -> "Event"
| "progress" -> "ProgressEvent"
| "readystatechange" -> "ProgressEvent"
| "resize" -> "UIEvent"
| "timeout" -> "ProgressEvent"
| _ -> e.Type
(e.Name, eType))
|> Map.ofList
let eNameToETypeWithoutCase =
eNameToEType
|> Map.toList
|> List.map (fun (k, v) -> (k.ToLower(), v))
|> Map.ofList
let getEventTypeInInterface eName (i: Browser.Interface) =
match i.Name, eName with
| "IDBDatabase", "abort"
| "IDBTransaction", "abort"
| "MSBaseReader", "abort"
| "XMLHttpRequestEventTarget", "abort"
-> "Event"
| "XMLHttpRequest", "readystatechange"
-> "Event"
| "XMLHttpRequest", _
-> "ProgressEvent"
| _ ->
let ownEventType =
if i.Events.IsSome then
match i.Events.Value.Events |> Array.tryFind (fun e -> e.Name = eName) with
| Some e -> e.Type
| _ -> ""
else
""
if ownEventType = "" then
match eNameToEType.TryFind eName with
| Some eType' -> eType'
| _ -> "Event"
else
ownEventType
/// Tag name to element name map
let tagNameToEleName =
let preferedElementMap =
function
| "script" -> "HTMLScriptElement"
| "a" -> "HTMLAnchorElement"
| "title" -> "HTMLTitleElement"
| "style" -> "HTMLStyleElement"
| _ -> ""
let resolveElementConflict tagName (iNames : seq<string>) =
match preferedElementMap tagName with
| name when Seq.contains name iNames -> name
| _ -> raise (Exception("Element conflict occured! Typename: " + tagName))
[ for i in GetNonCallbackInterfacesByFlavor Flavor.All do
yield! [ for e in i.Elements do
yield (e.Name, i.Name) ] ]
|> Seq.groupBy fst
|> Seq.map (fun (key, group) -> (key, Seq.map snd group))
|> Seq.map (fun (key, group) ->
key,
match Seq.length group with
| 1 -> Seq.head group
| _ -> resolveElementConflict key group)
|> Map.ofSeq
/// Interface name to all its implemented / inherited interfaces name list map
/// e.g. If i1 depends on i2, i2 should be in dependencyMap.[i1.Name]
let iNameToIDependList =
let rec getExtendList(iName : string) =
match GetInterfaceByName iName with
| Some i ->
match i.Extends with
| "Object" -> []
| super -> super :: (getExtendList super)
| _ -> []
let getImplementList(iName : string) =
match GetInterfaceByName iName with
| Some i -> List.ofArray i.Implements
| _ -> []
Array.concat [| allWebNonCallbackInterfaces; worker.Interfaces; worker.MixinInterfaces.Interfaces |]
|> Array.map (fun i -> (i.Name, List.concat [ (getExtendList i.Name); (getImplementList i.Name) ]))
|> Map.ofArray
/// Distinct event type list, used in the "createEvent" function
let distinctETypeList =
let usedEvents =
[ for i in GetNonCallbackInterfacesByFlavor Flavor.All do
match i.Events with
| Some es -> yield! es.Events
| _ -> () ]
|> List.map (fun e -> e.Type)
|> List.distinct
let unUsedEvents =
GetNonCallbackInterfacesByFlavor Flavor.All
|> Array.choose (fun i ->
if i.Extends = "Event" && i.Name.EndsWith("Event") && not (List.contains i.Name usedEvents) then Some(i.Name) else None)
|> Array.distinct
|> List.ofArray
List.concat [ usedEvents; unUsedEvents ] |> List.sort
/// Determine if interface1 depends on interface2
let IsDependsOn i1Name i2Name =
match (iNameToIDependList.ContainsKey i2Name) && (iNameToIDependList.ContainsKey i1Name) with
| true -> Seq.contains i2Name iNameToIDependList.[i1Name]
| false -> i2Name = "Object"
/// Interface name to its related eventhandler name list map
/// Note:
/// In the xml file, each event handler has
/// 1. eventhanlder name: "onready", "onabort" etc.
/// 2. the event name that it handles: "ready", "SVGAbort" etc.
/// And they don't NOT just differ by an "on" prefix!
let iNameToEhList =
let getEventTypeFromHandler (p : Browser.Property) (i : Browser.Interface) =
let eType =
// Check the "event-handler" attribute of the event handler property,
// which is the corresponding event name
match p.EventHandler with
| Some eName ->
// The list is partly obtained from the table at
// http://www.w3.org/TR/DOM-Level-3-Events/#dom-events-conformance #4.1
match eNameToEType.TryFind eName with
| Some v -> v
| _ -> GlobalVars.defaultEventType
| _ -> GlobalVars.defaultEventType
match eType with
| "Event" -> "Event"
| name when (IsDependsOn name "Event") -> eType
| _ -> GlobalVars.defaultEventType
// Get all the event handlers from an interface and also from its inherited / implemented interfaces
let rec getEventHandler(i : Browser.Interface) =
let ownEventHandler =
match i.Properties with
| Some ps ->
ps.Properties
|> Array.choose (fun p' ->
if p'.Type = "EventHandler" && p'.EventHandler.IsSome then
Some({ Name = p'.Name; EventName = p'.EventHandler.Value; EventType = getEventTypeFromHandler p' i })
else None)
|> List.ofArray
| None -> []
if ownEventHandler.Length > 0 then ownEventHandler else []
allInterfaces
|> Array.map (fun i -> (i.Name, getEventHandler i))
|> Map.ofArray
let iNameToEhParents =
let hasHandler (i : Browser.Interface) =
iNameToEhList.ContainsKey i.Name && not iNameToEhList.[i.Name].IsEmpty
// Get all the event handlers from an interface and also from its inherited / implemented interfaces
let rec getParentsWithEventHandler (i : Browser.Interface) =
let getParentEventHandler (i: Browser.Interface) =
if hasHandler i then [i] else getParentsWithEventHandler i
let extendedParentWithEventHandler =
match GetInterfaceByName i.Extends with
| Some extended -> getParentEventHandler extended
| None -> []
let implementedParentsWithEventHandler =
i.Implements
|> Array.choose GetInterfaceByName
|> List.ofArray
|> List.collect getParentEventHandler
List.concat [ extendedParentWithEventHandler; implementedParentsWithEventHandler ]
allInterfaces
|> Array.map (fun i -> (i.Name, getParentsWithEventHandler i))
|> Map.ofArray
/// Event handler name to event type map
let ehNameToEType =
let t =
[ for KeyValue(_, ehList) in iNameToEhList do
yield! (List.map (fun eh -> (eh.Name, eh.EventType)) ehList) ]
|> List.distinct
t |> Map.ofList
let GetGlobalPollutor flavor =
match flavor with
| Flavor.Web | Flavor.All -> browser.Interfaces |> Array.tryFind (fun i -> i.PrimaryGlobal.IsSome)
| Flavor.Worker -> worker.Interfaces |> Array.tryFind (fun i -> i.Global.IsSome)
let GetGlobalPollutorName flavor =
match GetGlobalPollutor flavor with
| Some gp -> gp.Name
| _ -> "Window"
/// Return a sequence of returntype * HashSet<paramCombination> tuple
let GetOverloads (f : Function) (decomposeMultipleTypes : bool) =
let getParams (f : Function) =
match f with
| Method m ->
[ for p in m.Params do
yield { Type = p.Type
Name = p.Name
Optional = p.Optional.IsSome
Variadic = p.Variadic.IsSome
Nullable = p.Nullable.IsSome } ]
| Ctor c ->
[ for p in c.Params do
yield { Type = p.Type
Name = p.Name
Optional = p.Optional.IsSome
Variadic = p.Variadic.IsSome
Nullable = p.Nullable.IsSome } ]
| CallBackFun cb ->
[ for p in cb.Params do
yield { Type = p.Type
Name = p.Name
Optional = p.Optional.IsSome
Variadic = p.Variadic.IsSome
Nullable = p.Nullable.IsSome } ]
let getReturnType (f : Function) =
match f with
| Method m -> m.Type
| Ctor _ -> ""
| CallBackFun cb -> cb.Type
let isNullable =
match f with
| Method m -> m.Nullable.IsSome
| Ctor _ -> false
| CallBackFun cb -> true
// Some params have the type of "(DOMString or DOMString [] or Number)"
// we need to transform it into [“DOMString", "DOMString []", "Number"]
let decomposeTypes (t : string) = t.Trim([| '('; ')' |]).Split([| " or " |], StringSplitOptions.None)
let decomposeParam (p : Param) =
[ for t in (decomposeTypes p.Type) do
yield { Type = t
Name = p.Name
Optional = p.Optional
Variadic = p.Variadic
Nullable = p.Nullable } ]
let pCombList =
let pCombs = List<_>()
let rec enumParams (acc : Param list) (rest : Param list) =
match rest with
| p :: ps when p.Type.Contains("or") ->
let pOptions = decomposeParam p
for pOption in pOptions do
enumParams (pOption :: acc) ps
| p :: ps -> enumParams (p :: acc) ps
| [] ->
// Iteration is completed and time to print every param now
pCombs.Add(List.rev acc) |> ignore
enumParams [] (getParams f)
List.ofSeq pCombs
let rTypes =
getReturnType f
|> decomposeTypes
|> List.ofArray
if decomposeMultipleTypes then
[ for pComb in pCombList do
yield { ParamCombinations = pComb
ReturnTypes = rTypes
Nullable = isNullable } ]
else
[ { ParamCombinations = getParams f
ReturnTypes = rTypes
Nullable = isNullable } ]
/// Define the subset of events that dedicated workers will use
let workerEventsMap =
[
("close", "CloseEvent");
("error", "ErrorEvent");
("upgradeneeded", "IDBVersionChangeEvent");
("message", "MessageEvent");
("loadend", "ProgressEvent");
("progress", "ProgressEvent");
]
|> Map.ofList
let typeDefSet =
browser.Typedefs |> Array.map (fun td -> td.NewType) |> Set.ofArray
let extendConflicts = [
{ BaseType = "AudioContext"; ExtendType = ["OfflineContext"]; MemberNames = ["suspend"] };
{ BaseType = "HTMLCollection"; ExtendType = ["HTMLFormControlsCollection"]; MemberNames = ["namedItem"] };
]
let extendConflictsBaseTypes =
extendConflicts |> List.map (fun ec -> (ec.BaseType, ec)) |> Map.ofList
module Emit =
open Data
open Types
open Helpers
open InputJson
// Global print target
let Pt = StringPrinter()
// When emit webworker types the dom types are ignored
let mutable ignoreDOMTypes = false
// Extended types used but not defined in the spec
let extendedTypes =
["ArrayBuffer";"ArrayBufferView";"Int8Array";"Uint8Array";"Int16Array";"Uint16Array";"Int32Array";"Uint32Array";"Float32Array";"Float64Array"]
/// Get typescript type using object dom type, object name, and it's associated interface name
let rec DomTypeToTsType (objDomType: string) =
match objDomType.Trim('?') with
| "AbortMode" -> "String"
| "any" -> "any"
| "bool" | "boolean" | "Boolean" -> "boolean"
| "CanvasPixelArray" -> "number[]"
| "Date" -> "Date"
| "DOMHighResTimeStamp" -> "number"
| "DOMString" -> "string"
| "DOMTimeStamp" -> "number"
| "EndOfStreamError" -> "number"
| "EventListener" -> "EventListenerOrEventListenerObject"
| "double" | "float" -> "number"
| "Function" -> "Function"
| "long" | "long long" | "signed long" | "signed long long" | "unsigned long" | "unsigned long long" -> "number"
| "octet" | "byte" -> "number"
| "object" -> "any"
| "Promise" -> "Promise"
| "ReadyState" -> "string"
| "sequence" -> "Array"
| "short" | "signed short" | "unsigned short" -> "number"
| "UnrestrictedDouble" -> "number"
| "void" -> "void"
| extendedType when List.contains extendedType extendedTypes -> extendedType
| _ ->
if ignoreDOMTypes && Seq.contains objDomType ["Element"; "Window"; "Document"] then "any"
else
// Name of an interface / enum / dict. Just return itself
if allInterfacesMap.ContainsKey objDomType ||
allCallbackFuncs.ContainsKey objDomType ||
allDictionariesMap.ContainsKey objDomType then
objDomType
// Name of a type alias. Just return itself
elif typeDefSet.Contains objDomType then objDomType
// Enum types are all treated as string
elif allEnumsMap.ContainsKey objDomType then "string"
// Union types
elif objDomType.Contains(" or ") then
let allTypes = objDomType.Trim('(', ')').Split([|" or "|], StringSplitOptions.None)
|> Array.map (fun t -> DomTypeToTsType (t.Trim('?', ' ')))
if Seq.contains "any" allTypes then "any" else String.concat " | " allTypes
else
// Check if is array type, which looks like "sequence<DOMString>"
let unescaped = System.Web.HttpUtility.HtmlDecode(objDomType)
let genericMatch = Regex.Match(unescaped, @"^(\w+)<(\w+)>$")
if genericMatch.Success then
let tName = DomTypeToTsType (genericMatch.Groups.[1].Value)
let paramName = DomTypeToTsType (genericMatch.Groups.[2].Value)
match tName with
| _ ->
if tName = "Array" then paramName + "[]"
else tName + "<" + paramName + ">"
elif objDomType.EndsWith("[]") then
let elementType = objDomType.Replace("[]", "").Trim() |> DomTypeToTsType
elementType + "[]"
else "any"
let makeNullable (originalType: string) =
match originalType with
| "any" -> "any"
| "void" -> "void"
| t when t.Contains "| null" -> t
| functionType when functionType.Contains "=>" -> "(" + functionType + ") | null"
| _ -> originalType + " | null"
let DomTypeToNullableTsType (objDomType: string) (nullable: bool) =
let resolvedType = DomTypeToTsType objDomType
if nullable then makeNullable resolvedType else resolvedType
let EmitConstants (i: Browser.Interface) =
let emitConstantFromJson (c: InputJsonType.Root) = Pt.Printl "readonly %s: %s;" c.Name.Value c.Type.Value
let emitConstant (c: Browser.Constant) =
if Option.isNone (getRemovedItemByName c.Name ItemKind.Constant i.Name) then
match getOverriddenItemByName c.Name ItemKind.Constant i.Name with
| Some c' -> emitConstantFromJson c'
| None -> Pt.Printl "readonly %s: %s;" c.Name (DomTypeToTsType c.Type)
let addedConstants = getAddedItems ItemKind.Constant Flavor.All
Array.iter emitConstantFromJson addedConstants
if i.Constants.IsSome then
Array.iter emitConstant i.Constants.Value.Constants
let matchSingleParamMethodSignature (m: Browser.Method) expectedMName expectedMType expectedParamType =
OptionCheckValue expectedMName m.Name &&
(DomTypeToNullableTsType m.Type m.Nullable.IsSome) = expectedMType &&
m.Params.Length = 1 &&
(DomTypeToTsType m.Params.[0].Type) = expectedParamType
/// Emit overloads for the createElement method
let EmitCreateElementOverloads (m: Browser.Method) =
if matchSingleParamMethodSignature m "createElement" "Element" "string" then
Pt.Printl "createElement<K extends keyof HTMLElementTagNameMap>(tagName: K): HTMLElementTagNameMap[K];"
Pt.Printl "createElement(tagName: string): HTMLElement;"
/// Emit overloads for the getElementsByTagName method
let EmitGetElementsByTagNameOverloads (m: Browser.Method) =
if matchSingleParamMethodSignature m "getElementsByTagName" "NodeList" "string" then
Pt.Printl "getElementsByTagName<K extends keyof ElementListTagNameMap>(%s: K): ElementListTagNameMap[K];" m.Params.[0].Name
Pt.Printl "getElementsByTagName(%s: string): NodeListOf<Element>;" m.Params.[0].Name
/// Emit overloads for the querySelector method
let EmitQuerySelectorOverloads (m: Browser.Method) =
if matchSingleParamMethodSignature m "querySelector" "Element" "string" then
Pt.Printl "querySelector<K extends keyof ElementTagNameMap>(selectors: K): ElementTagNameMap[K] | null;"
Pt.Printl "querySelector(selectors: string): Element | null;"
/// Emit overloads for the querySelectorAll method
let EmitQuerySelectorAllOverloads (m: Browser.Method) =
if matchSingleParamMethodSignature m "querySelectorAll" "NodeList" "string" then
Pt.Printl "querySelectorAll<K extends keyof ElementListTagNameMap>(selectors: K): ElementListTagNameMap[K];"
Pt.Printl "querySelectorAll(selectors: string): NodeListOf<Element>;"
let EmitHTMLElementTagNameMap () =
Pt.Printl "interface HTMLElementTagNameMap {"
Pt.IncreaseIndent()
for e in tagNameToEleName do
if iNameToIDependList.ContainsKey e.Value && Seq.contains "HTMLElement" iNameToIDependList.[e.Value] then
Pt.Printl "\"%s\": %s;" (e.Key.ToLower()) e.Value
Pt.DecreaseIndent()
Pt.Printl "}"
Pt.Printl ""
let EmitElementTagNameMap () =
Pt.Printl "interface ElementTagNameMap {"
Pt.IncreaseIndent()
for e in tagNameToEleName do
Pt.Printl "\"%s\": %s;" (e.Key.ToLower()) e.Value
Pt.DecreaseIndent()
Pt.Printl "}"
Pt.Printl ""
let EmitElementListTagNameMap () =
Pt.Printl "interface ElementListTagNameMap {"
Pt.IncreaseIndent()
for e in tagNameToEleName do
Pt.Printl "\"%s\": NodeListOf<%s>;" (e.Key.ToLower()) e.Value
Pt.DecreaseIndent()
Pt.Printl "}"
Pt.Printl ""
/// Emit overloads for the createEvent method
let EmitCreateEventOverloads (m: Browser.Method) =
if matchSingleParamMethodSignature m "createEvent" "Event" "string" then
// Emit plurals. For example, "Events", "MutationEvents"
let hasPlurals = ["Event"; "MutationEvent"; "MouseEvent"; "SVGZoomEvent"; "UIEvent"]
for x in distinctETypeList do
Pt.Printl "createEvent(eventInterface:\"%s\"): %s;" x x
if List.contains x hasPlurals then
Pt.Printl "createEvent(eventInterface:\"%ss\"): %s;" x x
Pt.Printl "createEvent(eventInterface: string): Event;"
/// Generate the parameters string for function signatures
let ParamsToString (ps: Param list) =
let paramToString (p: Param) =
let isOptional = not p.Variadic && p.Optional
let pType = if isOptional then DomTypeToTsType p.Type else DomTypeToNullableTsType p.Type p.Nullable
(if p.Variadic then "..." else "") +
(AdjustParamName p.Name) +
(if isOptional then "?: " else ": ") +
pType +
(if p.Variadic then "[]" else "")
String.Join(", ", (List.map paramToString ps))
let EmitCallBackInterface (i:Browser.Interface) =
Pt.Printl "interface %s {" i.Name
Pt.PrintWithAddedIndent "(evt: Event): void;"
Pt.Printl "}"
Pt.Printl ""
let EmitCallBackFunctions flavor =
let emitCallbackFunctionsFromJson (cb: InputJson.InputJsonType.Root) =
Pt.Printl "interface %s {" cb.Name.Value
cb.Signatures |> Array.iter (Pt.PrintWithAddedIndent "%s;")
Pt.Printl "}"
let emitCallBackFunction (cb: Browser.CallbackFunction) =
if Option.isNone (getRemovedItemByName cb.Name ItemKind.Callback "")then
match getOverriddenItemByName cb.Name ItemKind.Callback "" with
| Some cb' -> emitCallbackFunctionsFromJson cb'
| _ ->
Pt.Printl "interface %s {" cb.Name
let overloads = GetOverloads (CallBackFun cb) false
for { ParamCombinations = pCombList } in overloads do
let paramsString = ParamsToString pCombList
Pt.PrintWithAddedIndent "(%s): %s;" paramsString (DomTypeToTsType cb.Type)
Pt.Printl "}"
getAddedItems ItemKind.Callback flavor
|> Array.iter emitCallbackFunctionsFromJson
GetCallbackFuncsByFlavor flavor |> Array.iter emitCallBackFunction
let EmitEnums () =
let emitEnum (e: Browser.Enum) = Pt.Printl "declare var %s: string;" e.Name
browser.Enums |> Array.iter emitEnum
let EmitEventHandlerThis flavor (prefix: string) (i: Browser.Interface) =
if prefix = "" then "this: " + i.Name + ", "
else match GetGlobalPollutor flavor with
| Some pollutor -> "this: " + pollutor.Name + ", "
| _ -> ""
let EmitProperties flavor prefix (emitScope: EmitScope) (i: Browser.Interface) (conflictedMembers: Set<string>) =
let emitPropertyFromJson (p: InputJsonType.Root) =
let readOnlyModifier =
match p.Readonly with
| Some(true) -> "readonly "
| _ -> ""
Pt.Printl "%s%s%s: %s;" prefix readOnlyModifier p.Name.Value p.Type.Value
let emitCommentForProperty (printLine: Printf.StringFormat<_, unit> -> _) pName =
match CommentJson.GetCommentForProperty i.Name pName with
| Some comment -> printLine "%s" comment
| _ -> ()
let emitProperty (p: Browser.Property) =
let printLine content =
if conflictedMembers.Contains p.Name then Pt.PrintlToStack content else Pt.Printl content
emitCommentForProperty printLine p.Name
// Treat window.name specially because of https://github.com/Microsoft/TypeScript/issues/9850
if p.Name = "name" && i.Name = "Window" && emitScope = EmitScope.All then
printLine "declare const name: never;"
elif Option.isNone (getRemovedItemByName p.Name ItemKind.Property i.Name) then
match getOverriddenItemByName p.Name ItemKind.Property i.Name with
| Some p' -> emitPropertyFromJson p'
| None ->
let pType =
match p.Type with
| "EventHandler" ->
// Sometimes event handlers with the same name may actually handle different
// events in different interfaces. For example, "onerror" handles "ErrorEvent"
// normally, but in "SVGSVGElement" it handles "SVGError" event instead.
let eType =
if p.EventHandler.IsSome then
getEventTypeInInterface p.EventHandler.Value i
else
"Event"
String.Format("({0}ev: {1}) => any", EmitEventHandlerThis flavor prefix i, eType)
| _ -> DomTypeToTsType p.Type
let pTypeAndNull = if p.Nullable.IsSome then makeNullable pType else pType
let readOnlyModifier = if p.ReadOnly.IsSome && prefix = "" then "readonly " else ""
printLine "%s%s%s: %s;" prefix readOnlyModifier p.Name pTypeAndNull
// Note: the schema file shows the property doesn't have "static" attribute,
// therefore all properties are emited for the instance type.
if emitScope <> StaticOnly then
match i.Properties with
| Some ps ->
ps.Properties
|> Array.filter (ShouldKeep flavor)
|> Array.iter emitProperty
| None -> ()
for addedItem in getAddedItems ItemKind.Property flavor do
if (matchInterface i.Name addedItem) && (prefix <> "declare var " || addedItem.ExposeGlobally.IsNone || addedItem.ExposeGlobally.Value) then
emitCommentForProperty Pt.Printl addedItem.Name.Value
emitPropertyFromJson addedItem
let EmitMethods flavor prefix (emitScope: EmitScope) (i: Browser.Interface) (conflictedMembers: Set<string>) =
// Note: two cases:
// 1. emit the members inside a interface -> no need to add prefix
// 2. emit the members outside to expose them (for "Window") -> need to add "declare"
let emitMethodFromJson (m: InputJsonType.Root) =
m.Signatures |> Array.iter (Pt.Printl "%s%s;" prefix)
let emitCommentForMethod (printLine: Printf.StringFormat<_, unit> -> _) (mName: string option) =
if mName.IsSome then
match CommentJson.GetCommentForMethod i.Name mName.Value with
| Some comment -> printLine "%s" comment
| _ -> ()
// If prefix is not empty, then this is the global declare function addEventListener, we want to override this
// Otherwise, this is EventTarget.addEventListener, we want to keep that.
let mFilter (m:Browser.Method) =
matchScope emitScope m &&
not (prefix <> "" && OptionCheckValue "addEventListener" m.Name)
let emitMethod flavor prefix (i:Browser.Interface) (m:Browser.Method) =
let printLine content =
if m.Name.IsSome && conflictedMembers.Contains m.Name.Value then Pt.PrintlToStack content else Pt.Printl content
// print comment
emitCommentForMethod printLine m.Name
// Find if there are overriding signatures in the external json file
// - overriddenType: meaning there is a better definition of this type in the json file
// - removedType: meaning the type is marked as removed in the json file
// if there is any conflicts between the two, the "removedType" has a higher priority over
// the "overridenType".
let removedType = Option.bind (fun name -> InputJson.getRemovedItemByName name InputJson.ItemKind.Method i.Name) m.Name
let overridenType = Option.bind (fun mName -> InputJson.getOverriddenItemByName mName InputJson.ItemKind.Method i.Name) m.Name
if removedType.IsNone then
match overridenType with
| Some t ->
match flavor with
| Flavor.All | Flavor.Web -> t.WebOnlySignatures |> Array.iter (printLine "%s%s;" prefix)
| _ -> ()
t.Signatures |> Array.iter (printLine "%s%s;" prefix)
| None ->
match i.Name, m.Name with
| _, Some "createElement" -> EmitCreateElementOverloads m
| _, Some "createEvent" -> EmitCreateEventOverloads m
| _, Some "getElementsByTagName" -> EmitGetElementsByTagNameOverloads m
| _, Some "querySelector" -> EmitQuerySelectorOverloads m
| _, Some "querySelectorAll" -> EmitQuerySelectorAllOverloads m
| _ ->
if m.Name.IsSome then