-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathTransform.fs
2259 lines (2021 loc) · 80 KB
/
Transform.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
module rec Glutinum.Converter.Transform
open Fable.Core
open Glutinum.Converter.FSharpAST
open Glutinum.Converter.GlueAST
open System
type Reporter() =
let warnings = ResizeArray<string>()
let errors = ResizeArray<string>()
member val Warnings = warnings
member val Errors = errors
member val HasRegEpx = false with get, set
// Not really proud of this implementation, but I was not able to make it in a
// pure functional way, using a Tree structure or something similar
// It seems like for now this implementation does the job which is the most important
// And this is probably more readable than what a pure functional implementation would be
type TransformContext
(reporter: Reporter, currentScopeName: string, ?parent: TransformContext)
=
let types = ResizeArray<FSharpType>()
let modules = ResizeArray<TransformContext>()
member val FullName =
match parent with
| None -> ""
| Some parent ->
(parent.FullName + "." + currentScopeName).TrimStart '.'
member val CurrentScopeName = currentScopeName
// We need to expose the types for the children to be able to access
// push to them.
// This variable should not be accessed directly, but through the ExposeType method
// that's why we decorate it with the _ prefix
member val _types = types
// We expose an access to the reporter so we can propagate its instance
// when needed
// You should not use this directly, but instead use the AddWarning and AddError methods
member val _Reporter = reporter
member _.ExposeRegExp() =
// TODO: Rework how we memorize if need to expose RegExp alias
// Perhaps, before the printer phase we should traverse the whole AST to find information
// like aliases that we need to expose
// We could propagate the IsStandardLibrary flag to the F# AST to check such information
// Example: If we find an F# TypeReference with the name "RegExp" and the IsStandardLibrary flag is true
// then we need to expose the RegExp alias
reporter.HasRegEpx <- true
member _.ExposeType(typ: FSharpType) =
match parent with
| None -> types.Add(typ)
// The default case is to expose the type to the parent
// For example, when we are at Locale.Hello.Config
// we want to expose the type to Locale.Hello
// because this will generate
// module Locale =
// module Hello =
// type Config = ...
// and not
// module Locale =
// module Hello =
// module Config = ...
// type Config = ...
| Some parent -> parent._types.Add(typ)
member this.PushScope(scopeName: string) =
let childContext = TransformContext(reporter, scopeName, parent = this)
modules.Add childContext
childContext
member _.ToList() =
match parent with
| None ->
[
yield! types |> Seq.toList
for subModules in modules do
yield! subModules.ToList()
]
| Some _ ->
let types =
[
yield! Seq.toList types
for subModules in modules do
yield! subModules.ToList()
]
// Erase empty modules
if types.IsEmpty then
[]
else
({
Name = currentScopeName
Types = types
IsRecursive = false
}
: FSharpModule)
|> FSharpType.Module
|> List.singleton
member _.AddWarning(warning: string) = reporter.Warnings.Add warning
member _.AddError(error: string) = reporter.Errors.Add error
let private mapTypeNameToFableCoreAwareName
(context: TransformContext)
(typeReference: GlueTypeReference)
=
if typeReference.IsStandardLibrary then
match typeReference.Name with
| "Date" -> "JS.Date"
| "Promise" -> "JS.Promise"
| "Uint8Array" -> "JS.Uint8Array"
| "ReadonlyArray" -> "ResizeArray"
| "Array" -> "ResizeArray"
| "Boolean" -> "bool"
| "RegExp" ->
context.ExposeRegExp()
"RegExp"
| name -> name
else
typeReference.Name
let private unwrapOptionIfAlreadyOptional
(context: TransformContext)
(typ: GlueType)
(isOptional: bool)
=
// If the property is optional, we want to unwrap the option type
// This is to prevent generating a `string option option`
let typ' = transformType context typ
if isOptional then
match typ' with
| FSharpType.Option underlyingType -> underlyingType
| _ -> typ'
else
typ'
let private sanitizeNameAndPushScope
(name: string)
(context: TransformContext)
=
let name = Naming.sanitizeName name
let context = context.PushScope name
(name, context)
type TransformCommentResult =
{
ObsoleteAttributes: FSharpAttribute list
XmlDoc: FSharpXmlDoc list
}
let private transformComment
(comment: GlueAST.GlueComment list)
: TransformCommentResult
=
let rec categorize
(acc:
{|
Deprecated: (string option) list
Throws: string list
Remarks: string list
Others: GlueAST.GlueComment list
|})
(comments: GlueAST.GlueComment list)
=
match comments with
| [] -> acc
| comment :: rest ->
match comment with
| GlueComment.Deprecated content ->
categorize
{| acc with
Deprecated = acc.Deprecated @ [ content ]
|}
rest
| GlueComment.Throws content ->
categorize
{| acc with
Throws = acc.Throws @ [ content ]
|}
rest
| GlueComment.Remarks content ->
categorize
{| acc with
Remarks = acc.Remarks @ [ content ]
|}
rest
| _ ->
categorize
{| acc with
Others = acc.Others @ [ comment ]
|}
rest
let categories =
categorize
{|
Deprecated = []
Throws = []
Remarks = []
Others = []
|}
comment
let obsoleteAttributes =
categories.Deprecated |> List.map FSharpAttribute.Obsolete
let remarks =
if not categories.Remarks.IsEmpty || not categories.Throws.IsEmpty then
[
yield! categories.Remarks
// F# XML Doc does not support @throws so we convert it to remarks to keep the information
if not categories.Throws.IsEmpty then
if not categories.Remarks.IsEmpty then
""
"Throws:"
"-------"
for throws in categories.Throws do
""
throws
]
|> String.concat "\n"
|> FSharpXmlDoc.Remarks
|> Some
else
None
let others =
categories.Others
|> List.map (fun comment ->
match comment with
| GlueComment.Deprecated _
| GlueComment.Throws _
| GlueComment.Remarks _ -> failwith "Should not happen"
| GlueComment.Summary summary -> FSharpXmlDoc.Summary summary
| GlueComment.Returns returns -> FSharpXmlDoc.Returns returns
| GlueComment.Param param ->
let content =
param.Content
|> Option.map (fun content ->
content.TrimStart().TrimStart('-').TrimStart()
)
|> Option.defaultValue ""
({ Name = param.Name; Content = content }: FSharpCommentParam)
|> FSharpXmlDoc.Param
| GlueComment.DefaultValue defaultValue ->
FSharpXmlDoc.DefaultValue defaultValue
| GlueComment.Example example -> FSharpXmlDoc.Example example
| GlueComment.TypeParam typeParam ->
({
TypeName = typeParam.TypeName
Content = typeParam.Content |> Option.defaultValue ""
}
: FSharpCommentTypeParam)
|> FSharpXmlDoc.TypeParam
)
// Sort the XML Doc to have a consistent order
let others =
[
yield! others
if remarks.IsSome then
remarks.Value
]
|> List.sortBy (fun xmlDoc ->
match xmlDoc with
| FSharpXmlDoc.Summary _ -> 0
| FSharpXmlDoc.DefaultValue _ -> 1
| FSharpXmlDoc.Remarks _ -> 2
| FSharpXmlDoc.Example _ -> 3
| FSharpXmlDoc.Param _ -> 4
| FSharpXmlDoc.TypeParam _ -> 5
| FSharpXmlDoc.Returns _ -> 999 // Always put returns at the end
)
{
ObsoleteAttributes = obsoleteAttributes
XmlDoc = others
}
let private transformLiteral (glueLiteral: GlueLiteral) : FSharpLiteral =
match glueLiteral with
| GlueLiteral.String value -> FSharpLiteral.String value
| GlueLiteral.Int value -> FSharpLiteral.Int value
| GlueLiteral.Float value -> FSharpLiteral.Float value
| GlueLiteral.Bool value -> FSharpLiteral.Bool value
| GlueLiteral.Null -> FSharpLiteral.Null
let private transformPrimitive
(gluePrimitive: GluePrimitive)
: FSharpPrimitive
=
match gluePrimitive with
| GluePrimitive.String -> FSharpPrimitive.String
| GluePrimitive.Int -> FSharpPrimitive.Int
| GluePrimitive.Float -> FSharpPrimitive.Float
| GluePrimitive.Bool -> FSharpPrimitive.Bool
| GluePrimitive.Unit -> FSharpPrimitive.Unit
| GluePrimitive.Number -> FSharpPrimitive.Number
| GluePrimitive.Any -> FSharpPrimitive.Null
| GluePrimitive.Null -> FSharpPrimitive.Null
| GluePrimitive.Undefined -> FSharpPrimitive.Null
| GluePrimitive.Object -> FSharpPrimitive.Null
| GluePrimitive.Symbol -> FSharpPrimitive.Null
let private transformTupleType
(context: TransformContext)
(glueTypes: GlueType list)
: FSharpType
=
glueTypes |> List.map (transformType context) |> FSharpType.Tuple
let rec private transformType
(context: TransformContext)
(glueType: GlueType)
: FSharpType
=
match glueType with
| GlueType.Unknown -> FSharpType.Object
| GlueType.Primitive primitiveInfo ->
transformPrimitive primitiveInfo |> FSharpType.Primitive
| GlueType.TemplateLiteral -> FSharpType.Primitive FSharpPrimitive.String
| GlueType.OptionalType glueType ->
transformType context glueType |> FSharpType.Option
| GlueType.ThisType typeName -> FSharpType.ThisType typeName
| GlueType.TupleType glueTypes -> transformTupleType context glueTypes
| GlueType.Union(GlueTypeUnion cases) ->
let optionalTypes, others =
cases
|> List.partition (fun glueType ->
match glueType with
| GlueType.Primitive primitiveInfo ->
match primitiveInfo with
| GluePrimitive.Null
| GluePrimitive.Undefined -> true
| _ -> false
| _ -> false
)
let isOptional = not optionalTypes.IsEmpty
if isOptional && others.Length = 1 then
FSharpType.Option(transformType context others.Head)
// Don't wrap in a U1 if there is only one case
else if others.Length = 1 then
transformType context others.Head
else
match
tryOptimizeUnionType context context.CurrentScopeName others
with
| Some typ ->
typ |> context.ExposeType
// Get fullname
// Store type in the exposed types memory
({
Name = context.FullName
FullName = context.FullName
TypeArguments = []
Type = FSharpType.Discard
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| None ->
let name, context =
sanitizeNameAndPushScope $"U{others.Length}" context
let cases =
others
|> List.mapi (fun index caseType ->
let context = context.PushScope $"Case%i{index + 1}"
transformType context caseType |> FSharpUnionCase.Typed
)
{
Attributes = []
Name = name
Cases = cases
IsOptional = isOptional
}
|> FSharpType.Union
| GlueType.TypeReference typeReference ->
({
Name = mapTypeNameToFableCoreAwareName context typeReference
FullName = typeReference.FullName
TypeArguments =
typeReference.TypeArguments |> List.map (transformType context)
Type = //transformType context typeReference.TypeRef
// TODO: This code looks suspicious
// Why would a typeReference always be a string? I think I added that here to make
// the compiler happy because we don't have a concrete type for the TypeReference
// this is because of the recursive types which creates infinite loops in the reader
FSharpType.Primitive FSharpPrimitive.String
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| GlueType.Array glueType ->
transformType context glueType |> FSharpType.ResizeArray
| GlueType.ClassDeclaration classDeclaration ->
({
Name = classDeclaration.Name
FullName = classDeclaration.Name
TypeArguments = []
Type = FSharpType.Discard // TODO: Retrieve the type
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| GlueType.TypeParameter name -> FSharpType.TypeParameter name
| GlueType.FunctionType functionTypeInfo ->
({
Parameters =
functionTypeInfo.Parameters
// TypeScript allows to annotate the `this` parameter but it is not actually part
// of the function signature that the user will call.
|> List.filter (fun parameter -> parameter.Name <> "this")
|> List.map (transformParameter context)
ReturnType = transformType context functionTypeInfo.Type
}
: FSharpFunctionType)
|> FSharpType.Function
| GlueType.Interface interfaceInfo ->
FSharpType.Interface(transformInterface context interfaceInfo)
| GlueType.TypeLiteral typeLiteralInfo ->
let hasNoIndexSignature =
typeLiteralInfo.Members
|> List.forall (
function
| GlueMember.IndexSignature _ -> false
| GlueMember.MethodSignature _
| GlueMember.Property _
| GlueMember.GetAccessor _
| GlueMember.SetAccessor _
| GlueMember.CallSignature _
| GlueMember.Method _
| GlueMember.ConstructSignature _ -> true
)
if hasNoIndexSignature then
let typeLiteralParameters =
typeLiteralInfo.Members
|> TransformMembers.toFSharpParameters context
// If the underlying type is an option, we want to make the field optional
// remove the option type
|> List.map (fun parameter ->
match parameter.Type with
| FSharpType.Option underlyingType ->
{ parameter with
Type = underlyingType
IsOptional = true
}
| _ -> parameter
)
// Sort to have the optional fields at the end
|> List.sortBy _.IsOptional
let explicitFields =
typeLiteralParameters
|> List.map (fun parameter ->
{
Name = parameter.Name
Type =
// If the argument is optional, we want to wrap it in an option
if parameter.IsOptional then
FSharpType.Option parameter.Type
else
parameter.Type
}
: FSharpExplicitField
)
({
Attributes =
[ FSharpAttribute.Global; FSharpAttribute.AllowNullLiteral ]
Name = context.CurrentScopeName
PrimaryConstructor =
{
Parameters = typeLiteralParameters
Attributes =
[
FSharpAttribute.ParamObject
FSharpAttribute.EmitSelf
]
Accessibility = FSharpAccessibility.Public
}
SecondaryConstructors = []
ExplicitFields = explicitFields
TypeParameters = []
}
: FSharpClass)
|> FSharpType.Class
|> context.ExposeType
else
{
Attributes =
[
FSharpAttribute.AllowNullLiteral
FSharpAttribute.Interface
]
Name = context.CurrentScopeName
OriginalName = "" // This is a Fake type so we don't have an original name
TypeParameters = []
Members =
TransformMembers.toFSharpMember
context
typeLiteralInfo.Members
Inheritance = []
}
|> FSharpType.Interface
|> context.ExposeType
// Get fullname
// Store type in the exposed types memory
({
Name = context.FullName
FullName = context.FullName
TypeArguments = []
Type = FSharpType.Discard
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| GlueType.ExportDefault glueType -> transformType context glueType
| GlueType.Variable info -> transformType context info.Type
| GlueType.KeyOf innerGlueType ->
match
TypeAliasDeclaration.tryTransformKeyOf
context.CurrentScopeName
innerGlueType
with
| Some typ ->
context.ExposeType typ
({
Name = context.FullName
FullName = context.FullName
TypeArguments = []
Type = FSharpType.Discard
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| None -> FSharpType.Object
| GlueType.NamedTupleType namedTupleType ->
transformType context namedTupleType.Type
| GlueType.Discard -> FSharpType.Object
| GlueType.Literal glueLiteral ->
match glueLiteral with
| GlueLiteral.String _ -> FSharpType.Primitive FSharpPrimitive.String
| GlueLiteral.Int _ -> FSharpType.Primitive FSharpPrimitive.Int
| GlueLiteral.Float _ -> FSharpType.Primitive FSharpPrimitive.Float
| GlueLiteral.Bool _ -> FSharpType.Primitive FSharpPrimitive.Bool
| GlueLiteral.Null -> FSharpType.Primitive FSharpPrimitive.Null
| GlueType.FunctionDeclaration functionDeclaration ->
({
Parameters =
functionDeclaration.Parameters
|> List.map (transformParameter context)
ReturnType = transformType context functionDeclaration.Type
}
: FSharpFunctionType)
|> FSharpType.Function
| GlueType.IntersectionType members ->
if members.IsEmpty then
FSharpType.Object
else
{
Attributes =
[
FSharpAttribute.AllowNullLiteral
FSharpAttribute.Interface
]
Name = context.CurrentScopeName
OriginalName = context.CurrentScopeName
TypeParameters = []
Members = TransformMembers.toFSharpMember context members
Inheritance = []
}
|> FSharpType.Interface
|> context.ExposeType
({
Name = context.FullName
TypeParameters = []
})
|> FSharpType.Mapped
| GlueType.UtilityType utilityType ->
match utilityType with
| GlueUtilityType.Partial interfaceInfo ->
transformInterface context interfaceInfo
|> Interface.makePartial context.CurrentScopeName
|> FSharpType.Interface
|> context.ExposeType
// Get fullname
// Store type in the exposed types memory
({
Name = context.FullName
FullName = context.FullName
TypeArguments = []
Type = FSharpType.Discard
}
: FSharpTypeReference)
|> FSharpType.TypeReference
| GlueUtilityType.Record recordInfo ->
transformRecord context context.CurrentScopeName [] recordInfo
|> context.ExposeType
({
Name = context.FullName
TypeParameters = []
})
|> FSharpType.Mapped
| GlueType.TypeAliasDeclaration typeAliasDeclaration ->
({
Name = typeAliasDeclaration.Name
TypeParameters = []
})
|> FSharpType.Mapped
| GlueType.Literal _
| GlueType.ModuleDeclaration _
| GlueType.IndexedAccessType _
| GlueType.Enum _
| GlueType.TypeAliasDeclaration _ ->
context.AddError $"Could not transform type: %A{glueType}"
FSharpType.Discard
/// <summary></summary>
/// <param name="exports"></param>
/// <returns></returns>
let private transformExports
(context: TransformContext)
(isTopLevel: bool)
(exports: GlueType list)
: FSharpType
=
let context = context.PushScope "Exports"
let members =
exports
|> List.collect (
function
| GlueType.Variable info ->
let name, context = sanitizeNameAndPushScope info.Name context
let xmlDocInfo = transformComment info.Documentation
{
Attributes =
[
FSharpAttribute.Import(
info.Name,
Naming.MODULE_PLACEHOLDER
)
yield! xmlDocInfo.ObsoleteAttributes
]
Name = name
OriginalName = info.Name
Parameters = []
TypeParameters = []
Type = transformType context info.Type
IsOptional = false
IsStatic = true
Accessor = None
Accessibility = FSharpAccessibility.Public
XmlDoc = xmlDocInfo.XmlDoc
Body = FSharpMemberInfoBody.NativeOnly
}
|> FSharpMember.Property
|> List.singleton
| GlueType.FunctionDeclaration info ->
let name, context = sanitizeNameAndPushScope info.Name context
let xmlDocInfo = transformComment info.Documentation
{
Attributes =
[
if isTopLevel then
FSharpAttribute.Import(
info.Name,
Naming.MODULE_PLACEHOLDER
)
else
FSharpAttribute.EmitMacroInvoke info.Name
yield! xmlDocInfo.ObsoleteAttributes
]
Name = name
OriginalName = info.Name
Parameters =
info.Parameters |> List.map (transformParameter context)
TypeParameters =
transformTypeParameters context info.TypeParameters
Type = transformType context info.Type
IsOptional = false
IsStatic = isTopLevel
Accessor = None
Accessibility = FSharpAccessibility.Public
XmlDoc = xmlDocInfo.XmlDoc
Body = FSharpMemberInfoBody.NativeOnly
}
|> FSharpMember.Method
|> List.singleton
| GlueType.ClassDeclaration info
| GlueType.ExportDefault(GlueType.ClassDeclaration info) ->
// TODO: Handle constructor overloads
let name, context = sanitizeNameAndPushScope info.Name context
// If the class has no constructor explicitly defined, we need to generate one
let constructors =
if info.Constructors.IsEmpty then
[ { Documentation = []; Parameters = [] } ]
else
info.Constructors
constructors
|> List.map (fun constructorInfo ->
let xmlDocInfo =
transformComment constructorInfo.Documentation
{
Attributes =
[
if isTopLevel then
FSharpAttribute.Import(
info.Name,
Naming.MODULE_PLACEHOLDER
)
FSharpAttribute.EmitConstructor
else
FSharpAttribute.EmitMacroConstructor
info.Name
yield! xmlDocInfo.ObsoleteAttributes
]
Name = name
OriginalName = info.Name
Parameters =
constructorInfo.Parameters
|> List.map (transformParameter context)
TypeParameters =
transformTypeParameters context info.TypeParameters
Type =
({
Name = Naming.sanitizeName info.Name
TypeParameters =
transformTypeParameters
context
info.TypeParameters
})
|> FSharpType.Mapped
IsOptional = false
IsStatic = isTopLevel
Accessor = None
Accessibility = FSharpAccessibility.Public
XmlDoc = xmlDocInfo.XmlDoc
Body = FSharpMemberInfoBody.NativeOnly
}
|> FSharpMember.Method
)
| GlueType.ModuleDeclaration moduleDeclaration ->
let sanitizedName = Naming.sanitizeName moduleDeclaration.Name
{
Attributes =
[
FSharpAttribute.ImportAll Naming.MODULE_PLACEHOLDER
FSharpAttribute.Text(
$$"""Emit("$0.{{Naming.removeSurroundingQuotes moduleDeclaration.Name}}")"""
)
]
// "_" suffix is added to avoid name collision if
// there are some functions with the same name as
// the name of the module
// TODO: Only add the "_" suffix if there is a name collision
Name = sanitizedName + "_"
OriginalName = $"{moduleDeclaration.Name}.Exports"
Parameters = []
TypeParameters = []
Type =
({
Name = $"{sanitizedName}.Exports"
TypeParameters = []
})
|> FSharpType.Mapped
IsOptional = false
IsStatic = isTopLevel
Accessor = FSharpAccessor.ReadOnly |> Some
Accessibility = FSharpAccessibility.Public
XmlDoc = []
Body = FSharpMemberInfoBody.NativeOnly
}
|> FSharpMember.Property
|> List.singleton
| GlueType.ExportDefault glueType ->
let name, context =
sanitizeNameAndPushScope glueType.Name context
{
Attributes =
[
FSharpAttribute.ImportDefault
Naming.MODULE_PLACEHOLDER
]
Name = name
OriginalName = glueType.Name
Parameters = []
TypeParameters = []
Type = transformType context glueType
IsOptional = false
IsStatic = true
Accessor = None
Accessibility = FSharpAccessibility.Public
XmlDoc = []
Body = FSharpMemberInfoBody.NativeOnly
}
|> FSharpMember.Property
|> List.singleton
| glueType ->
failwithf "Could not generate exportMembers for: %A" glueType
)
{
Attributes = [ FSharpAttribute.AbstractClass; FSharpAttribute.Erase ]
Name = "Exports"
OriginalName = "Exports"
Members = members
TypeParameters = []
Inheritance = []
}
|> FSharpType.Interface
let private transformParameter
(context: TransformContext)
(parameter: GlueParameter)
: FSharpParameter
=
let context = context.PushScope(parameter.Name)
let typ =
let computedType =
unwrapOptionIfAlreadyOptional
context
parameter.Type
parameter.IsOptional
// In TypeScript, if an argument is marked as spread, users is forced to
// use an array. We want to remove the default transformation for that
// array and use the underlying type instead
// By default, an array is transformed to ResizeArray in F#
if parameter.IsSpread then
match computedType with
| FSharpType.ResizeArray underlyingType -> underlyingType
| _ -> computedType
else
computedType
{
Attributes =
[
if parameter.IsSpread then
FSharpAttribute.ParamArray
]
Name = Naming.sanitizeName parameter.Name
IsOptional = parameter.IsOptional
Type = typ
}
let private transformAccessor (accessor: GlueAccessor) : FSharpAccessor =
match accessor with
| GlueAccessor.ReadOnly -> FSharpAccessor.ReadOnly
| GlueAccessor.WriteOnly -> FSharpAccessor.WriteOnly
| GlueAccessor.ReadWrite -> FSharpAccessor.ReadWrite
module private TransformMembers =
let toFSharpMember
(context: TransformContext)
(members: GlueMember list)
: FSharpMember list
=
members
// We want to transform GetAccessor / SetAccessor
// into a single Property if they are related to the same property
|> List.choose (
function
| GlueMember.GetAccessor getAccessorInfo as self ->
let associatedSetAccessor =
members
|> List.tryFind (
function
| GlueMember.SetAccessor setPropertyInfo ->
getAccessorInfo.Name = setPropertyInfo.Name
| _ -> false
)
match associatedSetAccessor with
// If we found an associated SetAccessor, we want to transform into a Property
// and it is now a read-write property
| Some _ ->
{
Name = getAccessorInfo.Name
Documentation = getAccessorInfo.Documentation
Type = getAccessorInfo.Type
IsOptional = false
IsStatic = getAccessorInfo.IsStatic
Accessor = GlueAccessor.ReadWrite
IsPrivate = getAccessorInfo.IsPrivate
}
|> GlueMember.Property
|> Some
// Otherwise, we keep the GetAccessor as is
| None -> Some self
| GlueMember.SetAccessor setAccessorInfo as self ->
let associatedGetAccessor =
members
|> List.tryFind (
function
| GlueMember.GetAccessor getPropertyInfo ->
setAccessorInfo.Name = getPropertyInfo.Name
| _ -> false
)
// If we found an associated GetAccessor, we want to remove the SetAccessor
// the property has been transformed into a Property during the GetAccessor check
match associatedGetAccessor with
| Some _ -> None
// Otherwise, we keep the SetAccessor as is
| None -> Some self
| GlueMember.CallSignature _ as self -> Some self
| GlueMember.Method _ as self -> Some self
| GlueMember.Property _ as self -> Some self
| GlueMember.IndexSignature _ as self -> Some self
| GlueMember.MethodSignature _ as self -> Some self
| GlueMember.ConstructSignature _ as self -> Some self
)
|> List.choose (
function
| GlueMember.Method methodInfo ->
let name, context =
sanitizeNameAndPushScope methodInfo.Name context
if methodInfo.IsStatic then
{
Attributes = []
Name = name
OriginalName = methodInfo.Name
Parameters =
methodInfo.Parameters
|> List.map (transformParameter context)
Type = transformType context methodInfo.Type
TypeParameters = []
IsOptional = methodInfo.IsOptional