-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathBasicGenerativeProvisionTests.fs
More file actions
556 lines (483 loc) · 31.9 KB
/
BasicGenerativeProvisionTests.fs
File metadata and controls
556 lines (483 loc) · 31.9 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
module TPSDK.BasicGenerativeTests
open System
open System.IO
open System.Reflection
open System.Reflection.Emit
open ProviderImplementation.ProvidedTypes
open ProviderImplementation.ProvidedTypesTesting
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Core.CompilerServices
open UncheckedQuotations
open Xunit
#nowarn "760" // IDisposable needs new
[<TypeProvider>]
type GenerativePropertyProviderWithStaticParams (config : TypeProviderConfig) as this =
inherit TypeProviderForNamespaces (config)
let ns = "StaticProperty.Provided"
let asm = Assembly.GetExecutingAssembly()
let createType (typeName, _) =
let myAssem = ProvidedAssembly()
let myType = ProvidedTypeDefinition(myAssem, ns, typeName, Some typeof<obj>, isErased=false, hideObjectMethods=true)
myType.AddXmlDoc("Here is some doc")
let embedString = "test"
// Special TPSDK support for embedding Decimal values
let embedM = 5M
// Special TPSDK support for embedding System.DateTime values
let embedDT = System.DateTime.Now
// Special TPSDK support for embedding System.DateTimeOffset values
let embedDTO = System.DateTimeOffset.Now
// Special TPSDK support for embedding System.Type values
let embedType = typeof<int>
let testCode _args =
<@@ // NewArray
let arr = [| 1;2;3;4 |]
// Coerce
let arr2 = (box arr :?> int[])
let s = "hello world"
// Literal field
let s2 = System.DayOfWeek.Friday
// NewObj on default ctor - this is not yet supported in generative
// let s3 = System.DateTime()
// NewObj on value type
let s4 = System.DateTime(100L)
// NewObj on reference type
let s5 = System.Object()
// NewObj on generic reference type
let s6 = System.Collections.Generic.List<int>()
// NewObj on generic reference type
let s7 = System.Collections.Generic.Dictionary<int,int>()
let s8 = [1] |> List.map (fun x -> x + 1) |> List.map (fun x -> x + 2)
let s9 = match [1] with a :: b -> a | [] -> 5
let s9 = match Choice1Of2 4 with Choice1Of2 a -> a | Choice2Of2 () -> 5
let s10 = match Choice1Of3 4 with Choice1Of3 a -> a | Choice2Of3 () | Choice3Of3 () -> 5
let s11 = { contents = 4 }
let s12 x = s11.contents <- x
let s13 x = s11.Value <- x
let rec s14 x = if x = 0 then 1 else s14 (x-1) + s14 (x-1)
let rec s14 x = if x = 0 then 1 else s15 x + s15 x
and s15 x = s14 (x-1)
let mutable j = 3
for i in [ 1 .. 10 ] do
j <- j + 1
//Arithmetic - note, operations such as + are emitted as a call to the method in the F# library, even over integers
let z1 = 1 + 1 - 1 * 1 / 1
let z2 = 1u + 1u - 1u * 1u / 1u
let z3 = 1L + 1L - 1L * 1L / 1L
//Arithmetic (decimals)
let z4 = 1M + 1M - 1M * 1M / 1M
//Lambda
let f1 = (fun (x:int) -> x + 1)
let f2 = (fun (x:int) (y:int) -> x + y + 1)
let f3 = (fun (x:int) (y:int) (z:int) -> x + y + z + 1)
// Application
let z5 = f1 3 + f2 3 4 + f3 4 5 6
// Const, Tuple
let q1 = (embedM, embedString)
let q2 = (embedM, embedString, embedDT, embedType, embedDTO, (1,2,3))
// WhileLoop
while false do ()
// FastIntegerForLoop
for i in 0 .. 100 do
ignore ()
// // ForLoop - the TryFinally is not yet supported
// for i in 0L .. 100L do
// ignore ()
//IfThenElse one branch
if s = "" then
failwith "test"
//IfThenElse
if s = "" then
[]
else
Set.toList (Set.ofList [ "Hello world" ]) @@>
let adderCode (args: Expr list) = <@@ ignore (%%(args.[1]): System.EventHandler) @@>
let removerCode (args: Expr list) = <@@ ignore (%%(args.[1]) : System.EventHandler) @@>
let setterCode (args: Expr list) = <@@ ignore (%%(args.[1]) : string list) @@>
let ctorCode (args: Expr list) = <@@ ignore 1 @@>
let cctorCode (_args: Expr list) = <@@ ignore 2 @@>
let ctorCode2 (args: Expr list) =
match args.[0] with
| Var v -> if v.Name <> "this" then failwithf "args.[0].Name = %s" v.Name
| q -> failwithf "expected Var but got %A" q
match args.[1] with
| Var v -> if v.Name <> "arg" then failwithf "args.[1].Name = %s" v.Name
| q -> failwithf "expected Var but got %A" q
<@@ ignore (%%(args.[1]) : string list) @@>
let myProp = ProvidedProperty("MyStaticProperty", typeof<string list>, isStatic = true, getterCode = testCode)
let myProp2 = ProvidedProperty("MyInstaceProperty", typeof<string list>, isStatic = false, getterCode = testCode, setterCode = setterCode)
let myMeth1 = ProvidedMethod("MyStaticMethod", [], typeof<string list>, isStatic = true, invokeCode = testCode)
let myMeth2 = ProvidedMethod("MyInstanceMethod", [], typeof<string list>, isStatic = false, invokeCode = testCode)
let myEvent1 = ProvidedEvent("MyEvent", typeof<System.EventHandler>, isStatic = false, adderCode = adderCode, removerCode = removerCode)
let myCctor1 = ProvidedConstructor([], invokeCode = cctorCode, IsTypeInitializer=true)
let myCtor1 = ProvidedConstructor([], invokeCode = ctorCode)
let myCtor2 = ProvidedConstructor([ProvidedParameter("arg", typeof<string list>)], invokeCode = ctorCode2)
myType.AddMembers [ (myProp :> MemberInfo); (myProp2 :> MemberInfo); (myMeth1 :> MemberInfo); (myMeth2 :> MemberInfo); (myEvent1 :> MemberInfo); (myCctor1 :> MemberInfo); (myCtor1 :> MemberInfo); (myCtor2 :> MemberInfo)]
myAssem.AddTypes [myType]
myType
do
let myType = ProvidedTypeDefinition(asm, ns, "MyType", Some typeof<obj>)
let parameters = [ ProvidedStaticParameter("Count", typeof<int>)
ProvidedStaticParameter("Count2", typeof<int>, 3) ]
myType.DefineStaticParameters(parameters, (fun typeName args -> createType(typeName, (args.[0] :?> int) + (args.[1] :?> int))))
this.AddNamespace(ns, [myType])
let testCases() =
let fsCoreVersion = typeof<list<int>>.Assembly.GetName().Version.ToString()
[ (sprintf "FSharp.Core %s .NET Standard 2.0" fsCoreVersion, fsCoreVersion, (fun _ -> true), Targets.DotNetStandard20FSharpRefs) ]
[<Fact>]
let ``GenerativePropertyProviderWithStaticParams generates for correctly``() : unit =
for (text, desc, supports, refs) in testCases() do
if supports() then
printfn ""
printfn "----- GenerativePropertyProviderWithStaticParams hosted execution: %s ------- " desc
let staticArgs = [| box 3; box 4 |]
let runtimeAssemblyRefs = refs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativePropertyProviderWithStaticParams cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + (if isNull s then "" else s.ToString()) + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
match t.Assembly with
| :? ProvidedAssembly -> ()
| _ -> failwithf "expected a ProvidedAssembly"
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(t.Assembly)
Assert.NotEqual(0, assemContents.Length)
// re-read the assembly with the more complete reader to allow us to look at generated references
let assem = tp.TargetContext.ReadRelatedAssembly(assemContents)
printfn "typeName = %s" typeName
let typeName2 = providedType.Namespace + "." + typeName
printfn "typeName2 = %s" typeName2
let t2 = assem.GetType(typeName2)
Assert.NotNull(t2)
let allCtors = t2.GetConstructors(BindingFlags.NonPublic ||| BindingFlags.Public ||| BindingFlags.Static ||| BindingFlags.Instance)
Assert.Equal(3, allCtors.Length)
let ctors = allCtors |> Array.filter (fun c -> not c.IsStatic)
Assert.Equal(2, ctors.Length)
for ctor in ctors do
printfn "ctor.Name = %s" ctor.Name
Assert.Equal(".ctor", ctor.Name)
let cctors = allCtors |> Array.filter (fun c -> c.IsStatic)
Assert.Equal(1, cctors.Length)
printfn "cctors.[0].Name = %s" cctors.[0].Name
Assert.Equal(".cctor", cctors.[0].Name)
let res = [| for r in assem.GetReferencedAssemblies() -> r.ToString() |] |> String.concat ","
printfn "----- %s ------- " text
printfn "compilation references for FSharp.Core target %s = %A" text runtimeAssemblyRefs
printfn "assembly references for FSharp.Core target %s = %s" text res
Assert.Contains("FSharp.Core, Version="+desc, res)
[<Fact>]
let ``GenerativePropertyProviderWithStaticParams attributes are read correctly``() : unit =
for (text, desc, supports, refs) in testCases() do
if supports() then
let staticArgs = [| box 3; box 4 |]
let runtimeAssemblyRefs = refs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativePropertyProviderWithStaticParams cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + (if isNull s then "" else s.ToString()) + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
//check that attributes read using the typed overload to GetCustomAttributes<t> can be read from the provided method
let firstMethod = t.GetMembers() |> Array.find (fun m -> m :? ProvidedMethod )
let attrib = firstMethod.GetCustomAttributes<CompiledNameAttribute>()
Assert.NotNull attrib
[<Fact>]
let ``GenerativePropertyProviderWithStaticParams reflection on MethodSymbol and ConstructorSymbols do not throw``() : unit =
for (text, desc, supports, refs) in testCases() do
if supports() then
let staticArgs = [| box 3; box 4 |]
let runtimeAssemblyRefs = refs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativePropertyProviderWithStaticParams cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + (if isNull s then "" else s.ToString()) + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
let genericContainer = ProvidedTypeBuilder.MakeGenericType(typedefof<Option<_>>, [t])
let methods = genericContainer.GetMethods(BindingFlags.NonPublic ||| BindingFlags.Public ||| BindingFlags.Static ||| BindingFlags.Instance)
let methodCustomAttributes =
methods |> Array.choose (fun methodSymbol -> methodSymbol.GetCustomAttributes(true) |> Array.tryHead )
Assert.NotEmpty methodCustomAttributes
let ctors = genericContainer.GetConstructors(BindingFlags.NonPublic ||| BindingFlags.Public ||| BindingFlags.Static ||| BindingFlags.Instance)
let ctorCustomAttributes = ctors |> Array.choose (fun ctorSymbol -> ctorSymbol.GetCustomAttributes(true) |> Array.tryHead )
Assert.NotEmpty ctorCustomAttributes
[<TypeProvider>]
type GenerativeProviderWithRecursiveReferencesToGeneratedTypes (config : TypeProviderConfig) as this =
inherit TypeProviderForNamespaces (config)
let ns = "RecursiveReferencesToGeneratedTypes.Provided"
let asm = Assembly.GetExecutingAssembly()
let createType (typeName, _) =
let myAssem = ProvidedAssembly()
let myBaseType = ProvidedTypeDefinition(myAssem, ns, typeName+"BaseType", Some typeof<obj>, isErased=false, isSealed=false)
let myCtorOnBaseType = ProvidedConstructor([ProvidedParameter("implicitCtorFieldName",typeof<int>)], invokeCode = (fun _args -> <@@ () @@>), IsImplicitConstructor=true)
// Note: myType refers to another generated type as its base class.
let myType = ProvidedTypeDefinition(myAssem, ns, typeName, Some (myBaseType :> Type), isErased=false)
// Note: this method refers to another generated type as its return type
let myMeth1 = ProvidedMethod("MyInstanceMethodOnBaseType", [], myBaseType, isStatic = false, invokeCode = (fun _args -> Expr.NewObject(myCtorOnBaseType, [Expr.Value(1)])))
// Note: this method refers to another generated type as its return type
let myMeth2 = ProvidedMethod("MyInstanceMethod", [], myBaseType, isStatic = false, invokeCode = (fun _args -> Expr.NewObject(myCtorOnBaseType, [Expr.Value(1)])))
// Note: this method refers to another generated type as its return type
let myProp1 =
match <@@ Seq.map id [] @@> with
| Patterns.Call(_, m, _) ->
let method = ProvidedTypeBuilder.MakeGenericMethod(m.GetGenericMethodDefinition(), [myBaseType])
let resultType = ProvidedTypeBuilder.MakeGenericType(typedefof<seq<_>>, [myBaseType])
let lambda = Expr.Lambda(Var("_", typeof<int>), Expr.NewObject(myCtorOnBaseType, [Expr.Value(1)]))
ProvidedProperty("MyProp", resultType, getterCode = function _ -> Expr.CallUnchecked(method, [lambda ; <@@ Seq.empty @@>]))
| x -> failwithf "unexpected pattern %A" x
myBaseType.AddMembers [ (myCtorOnBaseType :> MemberInfo); (myMeth1 :> MemberInfo) ; (myProp1 :> MemberInfo) ]
myType.AddMembers [ (myMeth2 :> MemberInfo) ]
// Test a generative type with a base type from mscorlib
let myType2 = ProvidedTypeDefinition(asm, ns, typeName+"MyTypeWithBaseType", Some (typeof<System.Collections.BitArray>), isErased=false)
// Test a generative type implementing an interface from msvorlib
let myType3 = ProvidedTypeDefinition(asm, ns, typeName+"MyTypeWithInterfaceType", Some (typeof<obj>), isErased=false)
myType3.AddInterfaceImplementation typeof<System.IDisposable>
let disposeMethImpl = ProvidedMethod("Dispose", [], typeof<Void>, isStatic = false, invokeCode = (fun _args -> Expr.Value((), typeof<Void>)))
myType3.AddMember disposeMethImpl
myType3.DefineMethodOverride(disposeMethImpl, typeof<IDisposable>.GetMethod("Dispose"))
myAssem.AddTypes [myBaseType; myType; myType2; myType3]
myType
do
let myStaticParameterizedType = ProvidedTypeDefinition(asm, ns, "MyType", Some typeof<obj>)
let parameters = [ ProvidedStaticParameter("Count", typeof<int>)
ProvidedStaticParameter("Count2", typeof<int>, 3) ]
myStaticParameterizedType.DefineStaticParameters(parameters, (fun typeName args -> createType(typeName, (args.[0] :?> int) + (args.[1] :?> int))))
this.AddNamespace(ns, [myStaticParameterizedType])
[<Fact>]
let ``GenerativeProviderWithRecursiveReferencesToGeneratedTypes generates correctly``() : unit =
for (text, desc, supports, refs) in testCases() do
if supports() then
printfn ""
printfn "----- GenerativeProviderWithRecursiveReferencesToGeneratedTypes generates correctly: %s ------- " text
let staticArgs = [| box 3; box 4 |]
let runtimeAssemblyRefs = refs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativeProviderWithRecursiveReferencesToGeneratedTypes cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + (if isNull s then "" else s.ToString()) + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
match t.Assembly with
| :? ProvidedAssembly -> ()
| _ -> failwithf "expected a ProvidedAssembly"
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(t.Assembly)
Assert.NotEqual(0, assemContents.Length)
// re-read the assembly with the more complete reader to allow us to look at generated references
let assem = tp.TargetContext.ReadRelatedAssembly(assemContents)
let res = [| for r in assem.GetReferencedAssemblies() -> r.ToString() |] |> String.concat ","
printfn "----- %s ------- " text
printfn "compilation references for FSharp.Core target %s = %A" text runtimeAssemblyRefs
printfn "assembly references for FSharp.Core target %s = %s" text res
Assert.Contains("FSharp.Core, Version="+desc, res)
let ``GenerativeProviderWithRecursiveReferencesToGeneratedTypes generates for hosted execution correctly``() : unit =
for (text, desc, supports, refs) in testCases() do
if supports() then
printfn "----- GenerativeProviderWithRecursiveReferencesToGeneratedTypes hosted execution: %s ------- " desc
let staticArgs = [| box 3; box 4 |]
let runtimeAssemblyRefs = refs()
//printfn "----- refs = %A ------- " runtimeAssemblyRefs
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs, isHostedExecution=true)
let tp = GenerativeProviderWithRecursiveReferencesToGeneratedTypes cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + (if isNull s then "" else s.ToString()) + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
match t.Assembly with
| :? ProvidedAssembly -> failwithf "did not expect a ProvidedAssembly - when used in hosted execution a type provider should return a Reflection.Load assembly"
| _ -> ()
// OK, now check we can do a little bit of reflection emit against the types coming from this assembly
let tmpFile = Path.GetTempFileName()
let assemblyFileName = Path.ChangeExtension(tmpFile, "dll")
File.Delete(tmpFile)
let simpleName = Path.GetFileNameWithoutExtension(assemblyFileName)
let asmName = AssemblyName(simpleName)
let currentDom = AppDomain.CurrentDomain
let asmB = AssemblyBuilder.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run)
let modB = asmB.DefineDynamicModule(simpleName)
let typB = modB.DefineType("A", TypeAttributes.Sealed ||| TypeAttributes.Class)
let methB = typB.DefineMethod("M", MethodAttributes.Static)
methB.SetParameters( [| |])
methB.SetReturnType(t)
// TESTING TODO: Register binary
// TESTING TODO: field defs
// Provider for testing custom attribute encoding fixes:
// Fix 1: encoding obj[] in an object-typed constructor parameter slot (previously threw "TODO: can't yet emit arrays in attrs")
// Fix 2: applying transValue to constructor args and named properties so System.Type values are correctly encoded
[<TypeProvider>]
type GenerativeProviderWithCustomAttrEncoding (config : TypeProviderConfig) as this =
inherit TypeProviderForNamespaces (config)
let ns = "CustomAttrEncoding.Provided"
let tempAssembly = ProvidedAssembly()
let container = ProvidedTypeDefinition(tempAssembly, ns, "Container", Some typeof<obj>, isErased = false)
do
// Fix 1: property with DefaultValueAttribute(object) where value is a string[] (array in object slot)
let defaultValueCtorObj = typeof<System.ComponentModel.DefaultValueAttribute>.GetConstructor([|typeof<obj>|])
let propWithArrayAttr = ProvidedProperty("PropWithArrayAttr", typeof<string>, isStatic = false,
getterCode = fun _ -> <@@ "hello" @@>)
propWithArrayAttr.AddCustomAttribute {
new CustomAttributeData() with
member _.Constructor = defaultValueCtorObj
member _.ConstructorArguments = upcast [| CustomAttributeTypedArgument(typeof<obj>, box [| "a"; "b"; "c" |]) |]
member _.NamedArguments = upcast [||] }
// Fix 2: property with DefaultValueAttribute(object) where value is a System.Type
let propWithTypeAttr = ProvidedProperty("PropWithTypeAttr", typeof<string>, isStatic = false,
getterCode = fun _ -> <@@ "world" @@>)
propWithTypeAttr.AddCustomAttribute {
new CustomAttributeData() with
member _.Constructor = defaultValueCtorObj
member _.ConstructorArguments = upcast [| CustomAttributeTypedArgument(typeof<obj>, box typeof<System.Int32>) |]
member _.NamedArguments = upcast [||] }
container.AddMembers [ (propWithArrayAttr :> MemberInfo); (propWithTypeAttr :> MemberInfo) ]
container.AddMember (ProvidedConstructor([], invokeCode = fun _ -> <@@ () @@>))
tempAssembly.AddTypes [container]
this.AddNamespace(ns, [container])
// Provider for testing custom attribute named arguments (NamedArguments path in the assembly compiler).
// Uses DebuggerDisplayAttribute(string) with the settable "Name" named property.
[<TypeProvider>]
type GenerativeProviderWithNamedArgAttrs (config : TypeProviderConfig) as this =
inherit TypeProviderForNamespaces (config)
let ns = "NamedArgAttrs.Provided"
let tempAssembly = ProvidedAssembly()
let container = ProvidedTypeDefinition(tempAssembly, ns, "Container", Some typeof<obj>, isErased = false)
do
// DebuggerDisplayAttribute has ctor(string) and a settable string property "Name".
// We use this to exercise the NamedArguments encoding path in defineCustomAttrs.
let debuggerDisplayCtor = typeof<System.Diagnostics.DebuggerDisplayAttribute>.GetConstructor([| typeof<string> |])
let debuggerDisplayNameProp = typeof<System.Diagnostics.DebuggerDisplayAttribute>.GetProperty("Name")
let propWithNamedArg = ProvidedProperty("PropWithNamedArg", typeof<int>, isStatic = false,
getterCode = fun _ -> <@@ 42 @@>)
propWithNamedArg.AddCustomAttribute {
new CustomAttributeData() with
member _.Constructor = debuggerDisplayCtor
member _.ConstructorArguments = upcast [| CustomAttributeTypedArgument(typeof<string>, box "{Value}") |]
member _.NamedArguments =
upcast [| CustomAttributeNamedArgument(debuggerDisplayNameProp, CustomAttributeTypedArgument(typeof<string>, box "MyProp")) |] }
container.AddMember propWithNamedArg
container.AddMember (ProvidedConstructor([], invokeCode = fun _ -> <@@ () @@>))
tempAssembly.AddTypes [container]
this.AddNamespace(ns, [container])
[<Fact>]
let ``Generative custom attribute with array argument in object slot encodes correctly``() =
// Regression test for Fix 1: encoding obj[] in an object-typed constructor parameter slot
// Before fix: GetGeneratedAssemblyContents would throw failwith "TODO: can't yet emit arrays in attrs"
let runtimeAssemblyRefs = Targets.DotNetStandard20FSharpRefs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativeProviderWithCustomAttrEncoding cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
// Must not throw (before fix, this threw on the array arg)
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(providedType.Assembly)
Assert.NotEqual(0, assemContents.Length)
let assem = Assembly.Load assemContents
let containerType = assem.GetType("CustomAttrEncoding.Provided.Container")
Assert.NotNull(containerType)
let prop = containerType.GetProperty("PropWithArrayAttr")
Assert.NotNull(prop)
let attrData = prop.GetCustomAttributesData()
let defaultValueAttr = attrData |> Seq.tryFind (fun a -> a.Constructor.DeclaringType.Name = "DefaultValueAttribute")
Assert.True(defaultValueAttr.IsSome, "DefaultValueAttribute should be present on PropWithArrayAttr")
[<Fact>]
let ``Generative custom attribute with Type argument in object slot encodes correctly``() =
// Regression test for Fix 2: applying transValue so System.Type args are correctly encoded
let runtimeAssemblyRefs = Targets.DotNetStandard20FSharpRefs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativeProviderWithCustomAttrEncoding cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
// Must not throw
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(providedType.Assembly)
Assert.NotEqual(0, assemContents.Length)
let assem = Assembly.Load assemContents
let containerType = assem.GetType("CustomAttrEncoding.Provided.Container")
Assert.NotNull(containerType)
let prop = containerType.GetProperty("PropWithTypeAttr")
Assert.NotNull(prop)
let attrData = prop.GetCustomAttributesData()
let defaultValueAttr = attrData |> Seq.tryFind (fun a -> a.Constructor.DeclaringType.Name = "DefaultValueAttribute")
Assert.True(defaultValueAttr.IsSome, "DefaultValueAttribute should be present on PropWithTypeAttr")
[<Fact>]
let ``Generative custom attribute with named property argument encodes and round-trips correctly``() =
// Tests the NamedArguments encoding path in defineCustomAttrs (lines 15696–15697 of ProvidedTypes.fs).
// Before this path was exercised: named property arguments could silently be dropped.
let runtimeAssemblyRefs = Targets.DotNetStandard20FSharpRefs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig (__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let tp = GenerativeProviderWithNamedArgAttrs cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(providedType.Assembly)
Assert.NotEqual(0, assemContents.Length)
let assem = Assembly.Load assemContents
let containerType = assem.GetType("NamedArgAttrs.Provided.Container")
Assert.NotNull(containerType)
let prop = containerType.GetProperty("PropWithNamedArg")
Assert.NotNull(prop)
let attrData = prop.GetCustomAttributesData()
let debugAttr = attrData |> Seq.tryFind (fun a -> a.Constructor.DeclaringType.Name = "DebuggerDisplayAttribute")
Assert.True(debugAttr.IsSome, "DebuggerDisplayAttribute should be present on PropWithNamedArg")
let attr = debugAttr.Value
// Verify the constructor argument "{Value}" round-tripped
Assert.Equal(1, attr.ConstructorArguments.Count)
Assert.Equal("{Value}", attr.ConstructorArguments.[0].Value :?> string)
// Verify the named argument "Name" = "MyProp" round-tripped
let namedArgs = attr.NamedArguments |> Seq.toList
Assert.Equal(1, namedArgs.Length)
Assert.Equal("Name", namedArgs.[0].MemberName)
Assert.Equal("MyProp", namedArgs.[0].TypedValue.Value :?> string)
[<Fact>]
let ``TargetTypeDefinition member-wrapper caches are thread-safe under parallel access``() =
// Regression test for https://github.com/fsprojects/FSharp.TypeProviders.SDK/issues/481
// PR #471 introduced lazy caches in TargetTypeDefinition. When multiple threads call
// GetConstructors/GetMethods/etc. concurrently on the same generated type the underlying
// shared caches must not corrupt. Run 8 parallel threads each interrogating every member
// kind on the same TargetTypeDefinition; if any internal collection races, the dictionaries
// will throw InvalidOperationException.
let runtimeAssemblyRefs = Targets.DotNetStandard20FSharpRefs()
let runtimeAssembly = runtimeAssemblyRefs.[0]
let cfg = Testing.MakeSimulatedTypeProviderConfig(__SOURCE_DIRECTORY__, runtimeAssembly, runtimeAssemblyRefs)
let staticArgs = [| box 5; box 6 |]
let tp = GenerativePropertyProviderWithStaticParams cfg :> TypeProviderForNamespaces
let providedNamespace = tp.Namespaces.[0]
let providedTypes = providedNamespace.GetTypes()
let providedType = providedTypes.[0]
let typeName = providedType.Name + (staticArgs |> Seq.map (fun s -> ",\"" + s.ToString() + "\"") |> Seq.reduce (+))
let t = (tp :> ITypeProvider).ApplyStaticArguments(providedType, [| typeName |], staticArgs)
let assemContents = (tp :> ITypeProvider).GetGeneratedAssemblyContents(t.Assembly)
let assem = tp.TargetContext.ReadRelatedAssembly(assemContents)
let typeName2 = providedType.Namespace + "." + typeName
let targetType = assem.GetType(typeName2)
Assert.NotNull(targetType)
let bf = BindingFlags.Public ||| BindingFlags.NonPublic ||| BindingFlags.Instance ||| BindingFlags.Static
let errors = System.Collections.Concurrent.ConcurrentBag<exn>()
let threads =
[| for _ in 1..8 ->
System.Threading.Thread(fun () ->
try
for _ in 1..50 do
targetType.GetConstructors(bf) |> ignore
targetType.GetMethods(bf) |> ignore
targetType.GetFields(bf) |> ignore
targetType.GetProperties(bf) |> ignore
targetType.GetEvents(bf) |> ignore
targetType.GetNestedTypes(bf) |> ignore
with ex ->
errors.Add(ex)) |]
for th in threads do th.Start()
for th in threads do th.Join()
Assert.True(errors.IsEmpty, sprintf "Thread-safety violations: %A" (errors |> Seq.toList))