Repository navigation
Expand file tree
/
Copy pathLuaObjectGeneratorTests.cs
More file actions
638 lines (594 loc) · 22.8 KB
/
Copy pathLuaObjectGeneratorTests.cs
File metadata and controls
638 lines (594 loc) · 22.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
using System.Collections.Immutable;
using Lua.SourceGenerator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace Lua.SourceGenerator.Tests;
public class LuaObjectGeneratorTests
{
[TestCase("class BoundObject")]
[TestCase("class BoundObject<T>")]
[TestCase("record BoundObject")]
[TestCase("record BoundObject<T>")]
public void BoundMethods_GenerateWithoutDiagnostics(string declaration)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject(BindInstanceMethods = true)]
internal partial {{declaration}}
{
[LuaMember]
public int Read(int value = 1) => value;
[LuaMember, LuaMetamethod(LuaObjectMetamethod.Len)]
public int Length() => 2;
[LuaMember]
public static int StaticRead() => 3;
}
"""
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[TestCase("public static int Read(System.ReadOnlySpan<LuaValue> values) => values.Length;")]
[TestCase("public int Read(System.ReadOnlySpan<LuaValue> values) => values.Length;")]
[TestCase(
"public static int Read(int first, System.ReadOnlySpan<LuaValue> values) => first + values.Length;"
)]
[TestCase(
"public int Read(int first, System.ReadOnlySpan<LuaValue> values) => first + values.Length;"
)]
[TestCase(
"public int Read(System.ReadOnlySpan<LuaValue> values, System.Threading.CancellationToken ct) => values.Length;"
)]
[TestCase("public static int Read(System.ReadOnlyMemory<LuaValue> values) => values.Length;")]
[TestCase("public int Read(System.ReadOnlyMemory<LuaValue> values) => values.Length;")]
[TestCase(
"public static int Read(int first, System.ReadOnlyMemory<LuaValue> values, System.Threading.CancellationToken ct) => first + values.Length;"
)]
[TestCase(
"public int Read(int first, System.ReadOnlyMemory<LuaValue> values, System.Threading.CancellationToken ct) => first + values.Length;"
)]
[TestCase(
"public int Read(int first = 1, System.ReadOnlySpan<LuaValue> values = default) => first + values.Length;"
)]
[TestCase(
"public int Read(out int extra, ref int first, System.ReadOnlyMemory<LuaValue> values) { extra = first++; return values.Length; }"
)]
[TestCase(
"public System.Threading.Tasks.Task<int> Read(System.ReadOnlyMemory<LuaValue> values) => System.Threading.Tasks.Task.FromResult(values.Length);"
)]
[TestCase(
"public System.Threading.Tasks.ValueTask<int> Read(System.ReadOnlyMemory<LuaValue> values) => new System.Threading.Tasks.ValueTask<int>(values.Length);"
)]
[TestCase(
"public System.Threading.Tasks.Task<int> Read(System.ReadOnlySpan<LuaValue> values) => System.Threading.Tasks.Task.FromResult(values.Length);"
)]
[TestCase("public void Read(System.Threading.CancellationToken ct) { }")]
public void VariadicParameters_GenerateWithoutDiagnostics(string method)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject]
internal partial class VariadicObject
{
[LuaMember] {{method}}
}
internal static class Consumer
{
public static LuaValue Convert() => new VariadicObject();
}
"""
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[TestCase(
"System.ReadOnlySpan<LuaValue> values, int last",
"System.ReadOnlySpan<Lua.LuaValue>"
)]
[TestCase(
"System.ReadOnlyMemory<LuaValue> values, int last",
"System.ReadOnlyMemory<Lua.LuaValue>"
)]
[TestCase("System.ReadOnlySpan<int> values", "System.ReadOnlySpan<int>")]
[TestCase("System.ReadOnlyMemory<int> values", "System.ReadOnlyMemory<int>")]
[TestCase("System.Span<LuaValue> values", "System.Span<Lua.LuaValue>")]
[TestCase("System.Memory<LuaValue> values", "System.Memory<Lua.LuaValue>")]
[TestCase("ref System.ReadOnlySpan<LuaValue> values", "System.ReadOnlySpan<Lua.LuaValue>")]
[TestCase("out System.ReadOnlyMemory<LuaValue> values", "System.ReadOnlyMemory<Lua.LuaValue>")]
[TestCase("in System.ReadOnlyMemory<LuaValue> values", "System.ReadOnlyMemory<Lua.LuaValue>")]
[TestCase("System.ReadOnlyMemory<LuaValue>? values", "System.ReadOnlyMemory<Lua.LuaValue>")]
[TestCase("params LuaValue[] values", "Lua.LuaValue[]")]
public void VariadicParameters_RejectUnsupportedShapes(string parameters, string typeName)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject]
internal partial class UnsupportedObject
{
[LuaMember] public void Read({{parameters}}) => throw new System.NotSupportedException();
}
[LuaObject]
internal partial class HealthyObject
{
[LuaMember] public int Value => 1;
}
internal static class Consumer
{
public static LuaValue Convert() => new HealthyObject();
}
"""
);
AssertUnsupportedMemberDiagnostic(
result.Diagnostics,
result.UserSource,
"LUACS006",
"values",
typeName
);
}
[TestCase("System.ReadOnlySpan<LuaValue>")]
[TestCase("System.ReadOnlyMemory<LuaValue>")]
public void VariadicParameters_StillValidateAllowNull(string type)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject]
internal partial class UnsupportedObject
{
[LuaMember] public void Read([System.Diagnostics.CodeAnalysis.AllowNull] {{type}} values) { }
}
[LuaObject]
internal partial class HealthyObject { }
"""
);
AssertUnsupportedMemberDiagnostic(
result.Diagnostics,
result.UserSource,
"LUACS008",
"values",
"values"
);
}
[TestCase("LuaValue[]", "System.Array.Empty<LuaValue>()", "Lua.LuaValue[]")]
[TestCase("LuaValue[,]", "new LuaValue[0, 0]", "Lua.LuaValue[*,*]")]
[TestCase("int[]", "System.Array.Empty<int>()", "int[]")]
[TestCase("string[]?", "null", "string[]?")]
[TestCase(
"Task<LuaValue[]>",
"Task.FromResult(System.Array.Empty<LuaValue>())",
"Lua.LuaValue[]"
)]
[TestCase(
"ValueTask<LuaValue[]>",
"new ValueTask<LuaValue[]>(System.Array.Empty<LuaValue>())",
"Lua.LuaValue[]"
)]
[TestCase("int*", "null", "int*")]
[TestCase("delegate*<int>", "null", "delegate*<int>")]
public void UnsupportedReturnType_DoesNotStopOtherLuaObjects(
string returnType,
string returnExpression,
string diagnosticType
)
{
var usingTasks = returnType.Contains("Task") ? "using System.Threading.Tasks;" : "";
var result = CompileGeneratedSource(
$$"""
#nullable enable
using Lua;
{{usingTasks}}
[LuaObject]
internal unsafe partial class UnsupportedObject
{
[LuaMember] public {{returnType}} Read() => {{returnExpression}};
}
[LuaObject]
internal partial class HealthyObject
{
[LuaMember] public int Value => 1;
}
internal static class Consumer
{
public static LuaValue Convert() => new HealthyObject();
}
"""
);
AssertUnsupportedMemberDiagnostic(
result.Diagnostics,
result.UserSource,
"LUACS005",
"Read",
diagnosticType
);
Assert.That(
result.GeneratedTrees.Select(x => Path.GetFileName(x.FilePath)),
Is.EquivalentTo(new[] { "HealthyObject.LuaObject.g.cs" })
);
}
[TestCase("LuaValue[] values", "Lua.LuaValue[]")]
[TestCase("ref LuaValue[] values", "Lua.LuaValue[]")]
[TestCase("out LuaValue[] values", "Lua.LuaValue[]")]
public void UnsupportedParameterType_HasALocatedDiagnostic(
string parameter,
string diagnosticType
)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject]
internal partial class UnsupportedObject
{
[LuaMember] public void Read({{parameter}}) => throw new System.NotSupportedException();
}
[LuaObject]
internal partial class HealthyObject
{
[LuaMember] public int Value => 1;
}
internal static class Consumer
{
public static LuaValue Convert() => new HealthyObject();
}
"""
);
AssertUnsupportedMemberDiagnostic(
result.Diagnostics,
result.UserSource,
"LUACS006",
"values",
diagnosticType
);
}
static void AssertUnsupportedMemberDiagnostic(
ImmutableArray<Diagnostic> diagnostics,
SyntaxTree userSource,
string diagnosticId,
string memberName,
string typeName
)
{
Assert.That(diagnostics, Has.Length.EqualTo(1), string.Join("\n", diagnostics));
var diagnostic = diagnostics[0];
Assert.That(diagnostic.Id, Is.EqualTo(diagnosticId));
Assert.That(diagnostic.Severity, Is.EqualTo(DiagnosticSeverity.Error));
Assert.That(diagnostic.GetMessage(), Does.Contain($"'{typeName}'"));
Assert.That(diagnostic.Location.SourceTree, Is.SameAs(userSource));
Assert.That(
userSource.GetText().ToString(diagnostic.Location.SourceSpan),
Is.EqualTo(memberName)
);
}
[TestCase("public int Read(ref int value, out int extra) { extra = ++value; return value; }")]
[TestCase("public static void Read(out int extra, ref int value) { extra = ++value; }")]
[TestCase("public Task<int> Read() => Task.FromResult(1);")]
[TestCase("public ValueTask<int> Read() => new ValueTask<int>(1);")]
[TestCase("public Task Read() => Task.CompletedTask;")]
[TestCase("public ValueTask Read() => default;")]
public void SupportedMethods_StillGenerateWithoutDiagnostics(string method)
{
var usingTasks = method.Contains("Task") ? "using System.Threading.Tasks;" : "";
var result = CompileGeneratedSource(
$$"""
using Lua;
{{usingTasks}}
[LuaObject]
internal partial class HealthyObject
{
[LuaMember] {{method}}
}
internal static class Consumer
{
public static LuaValue Convert() => new HealthyObject();
}
"""
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[TestCase(
"[LuaMetamethod(LuaObjectMetamethod.Call)] public static BaseObject New() => new();",
"[LuaMetamethod(LuaObjectMetamethod.Call)] public new static DerivedObject New() => new();"
)]
[TestCase(
"[LuaMember] public virtual int Value { get; set; }",
"[LuaMember] public override int Value { get; set; }"
)]
[TestCase("[LuaMember] public int Value;", "[LuaMember] public new int Value;")]
[TestCase(
"[LuaMember] public virtual int Read() => 1;",
"[LuaMember] public override int Read() => 2;"
)]
[TestCase(
"[LuaMember(\"read\")] public int BaseRead() => 1;",
"[LuaMember(\"read\")] public int DerivedRead() => 2;"
)]
[TestCase(
"[LuaMember(\"value\")] public int BaseValue { get; set; }",
"[LuaMember(\"value\")] public int DerivedValue;"
)]
[TestCase(
"[LuaMember(\"value\")] public int BaseValue { get; set; }",
"[LuaMember(\"value\")] public int DerivedRead() => 2;"
)]
[TestCase(
"[LuaMember(\"value\")] public int BaseRead() => 1;",
"[LuaMember(\"value\")] public int DerivedValue { get; set; }"
)]
[TestCase(
"[LuaMetamethod(LuaObjectMetamethod.Len)] public int BaseLength() => 1;",
"[LuaMetamethod(LuaObjectMetamethod.Len)] public int DerivedLength() => 2;"
)]
[TestCase("[LuaMember] public virtual int Read() => 1;", "public override int Read() => 2;")]
public void DerivedBindings_ReplaceInheritedBindings(string baseMember, string derivedMember)
{
var result = CompileGeneratedSource(
$$"""
using Lua;
[LuaObject]
internal partial class BaseObject { {{baseMember}} }
[LuaObject]
internal partial class DerivedObject : BaseObject { {{derivedMember}} }
[LuaObject]
internal partial class LeafObject : DerivedObject { }
"""
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[Test]
public void DuplicateMetamethods_InTheSameTypeRemainErrors()
{
var result = CompileGeneratedSource(
"""
using Lua;
[LuaObject]
internal partial class BaseObject
{
[LuaMetamethod(LuaObjectMetamethod.Len)] public int Length() => 1;
}
[LuaObject]
internal partial class DerivedObject : BaseObject
{
[LuaMetamethod(LuaObjectMetamethod.Len)] public int FirstLength() => 2;
[LuaMetamethod(LuaObjectMetamethod.Len)] public int SecondLength() => 3;
}
"""
);
Assert.That(
result.Diagnostics,
Has.Exactly(1).Matches<Diagnostic>(x => x.Id == "LUACS007")
);
}
[Test]
public void DuplicateLuaNames_InTheSameTypeRemainErrors()
{
var result = CompileGeneratedSource(
"""
using Lua;
[LuaObject]
internal partial class DuplicateObject
{
[LuaMember("read")] public int FirstRead() => 1;
[LuaMember("read")] public int SecondRead() => 2;
}
"""
);
Assert.That(result.Success, Is.False);
Assert.That(result.Diagnostics, Has.Some.Matches<Diagnostic>(x => x.Id == "CS0102"));
}
[TestCase("class DocumentedObject", false)]
[TestCase("class DocumentedObject", true)]
[TestCase("class DocumentedObject<T>", false)]
[TestCase("class DocumentedObject<T>", true)]
[TestCase("record DocumentedObject", false)]
[TestCase("record DocumentedObject", true)]
public void GeneratedMembers_DoNotRequireXmlDocumentation(
string declaration,
bool warningsAsErrors
)
{
var typeParameterDocumentation = declaration.Contains("<T>")
? "/// <typeparam name=\"T\">The type argument.</typeparam>"
: "";
var result = CompileGeneratedSource(
$$"""
using Lua;
/// <summary>A documented Lua object.</summary>
{{typeParameterDocumentation}}
[LuaObject]
public partial {{declaration}}
{
/// <summary>Gets or sets the value.</summary>
[LuaMember]
public int Value { get; set; }
}
""",
warningsAsErrors
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[TestCase("Obsolete")]
[TestCase("Obsolete(\"Use the replacement member.\")")]
public void GeneratedWrappers_CanReferenceUserSelectedObsoleteMembers(string attribute)
{
var result = CompileGeneratedSource(
$$"""
using System;
using Lua;
[LuaObject]
internal partial class LegacyObject
{
[LuaMember, {{attribute}}]
public int Field;
[LuaMember, {{attribute}}]
public int Property { get; set; }
[LuaMember, {{attribute}}]
public void Method() { }
[LuaMetamethod(LuaObjectMetamethod.Add), {{attribute}}]
public static int Add(LegacyObject left, LegacyObject right) => 1;
}
"""
);
Assert.That(result.Success, Is.True, string.Join("\n", result.Diagnostics));
Assert.That(result.Diagnostics, Is.Empty);
}
[TestCase(false)]
[TestCase(true)]
public void GeneratedSuppressions_DoNotHideDiagnosticsInUserCode(bool warningsAsErrors)
{
var result = CompileGeneratedSource(
"""
using System;
using Lua;
/// <summary>A Lua object with diagnostics in user-written code.</summary>
[LuaObject]
public partial class UserObject
{
[LuaMember]
public int Undocumented { get; set; }
/// <summary>A legacy member without a message.</summary>
[LuaMember, Obsolete]
public void LegacyWithoutMessage() { }
/// <summary>A legacy member with a message.</summary>
[LuaMember, Obsolete("Use the replacement member.")]
public void LegacyWithMessage() { }
/// <summary>Calls the legacy members from user-written code.</summary>
public void CallLegacyMembers()
{
LegacyWithoutMessage();
LegacyWithMessage();
}
}
""",
warningsAsErrors
);
Assert.That(
result.Diagnostics.Select(x => x.Id),
Is.EquivalentTo(new[] { "CS1591", "CS0612", "CS0618" })
);
Assert.That(
result.Diagnostics.All(x => x.Location.SourceTree == result.UserSource),
Is.True
);
Assert.That(
result.Diagnostics.All(x =>
x.Severity
== (warningsAsErrors ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning)
),
Is.True
);
Assert.That(result.Success, Is.EqualTo(!warningsAsErrors));
}
[Test]
public void GeneratedSuppressions_DoNotHideObsoleteErrors()
{
var result = CompileGeneratedSource(
"""
using System;
using Lua;
[LuaObject]
internal partial class UnsupportedObject
{
[LuaMember, Obsolete("This API must not be used.", true)]
public void Method() { }
}
"""
);
Assert.That(result.Success, Is.False);
Assert.That(
result.Diagnostics,
Has.Some.Matches<Diagnostic>(x =>
x.Id == "CS0619" && x.Severity == DiagnosticSeverity.Error
)
);
}
static (
bool Success,
ImmutableArray<Diagnostic> Diagnostics,
SyntaxTree UserSource,
ImmutableArray<SyntaxTree> GeneratedTrees
) CompileGeneratedSource(string source, bool warningsAsErrors = true)
{
var parseOptions = CSharpParseOptions
.Default.WithLanguageVersion(LanguageVersion.Preview)
.WithDocumentationMode(DocumentationMode.Diagnose);
var syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions, "UserObject.cs");
var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
.Split(Path.PathSeparator)
.Select(path => MetadataReference.CreateFromFile(path))
.Append(MetadataReference.CreateFromFile(typeof(LuaValue).Assembly.Location))
.Append(MetadataReference.CreateFromFile(typeof(LuaObjectAttribute).Assembly.Location));
var compilation = CSharpCompilation.Create(
"GeneratedWarningConsumer",
[syntaxTree],
references,
new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
allowUnsafe: true
).WithGeneralDiagnosticOption(
warningsAsErrors ? ReportDiagnostic.Error : ReportDiagnostic.Default
)
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(
[new LuaObjectGenerator().AsSourceGenerator()],
parseOptions: parseOptions
);
driver = driver.RunGeneratorsAndUpdateCompilation(
compilation,
out var output,
out var diagnostics
);
Assert.That(driver.GetRunResult().GeneratedTrees, Is.Not.Empty);
using var assembly = new MemoryStream();
using var documentation = new MemoryStream();
var result = output.Emit(assembly, xmlDocumentationStream: documentation);
return (
result.Success,
diagnostics.AddRange(result.Diagnostics),
syntaxTree,
driver.GetRunResult().GeneratedTrees
);
}
[Test]
public void Test_AllowNullRejectsNonNullableValueTypes()
{
var syntaxTree = CSharpSyntaxTree.ParseText(
"""
using System.Diagnostics.CodeAnalysis;
using Lua;
[LuaObject]
public partial class InvalidAllowNullMember
{
[LuaMember, AllowNull]
public int Value;
[LuaMember]
public static void Method([AllowNull] int value) { }
}
""",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)
);
var references = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")!)
.Split(Path.PathSeparator)
.Select(path => MetadataReference.CreateFromFile(path))
.Append(MetadataReference.CreateFromFile(typeof(LuaValue).Assembly.Location))
.Append(MetadataReference.CreateFromFile(typeof(LuaObjectAttribute).Assembly.Location));
var compilation = CSharpCompilation.Create(
"InvalidAllowNullMember",
[syntaxTree],
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
GeneratorDriver driver = CSharpGeneratorDriver.Create(
new LuaObjectGenerator().AsSourceGenerator()
);
driver = driver.RunGenerators(compilation);
var diagnostics = driver.GetRunResult().Diagnostics;
Assert.That(diagnostics, Has.Exactly(2).Matches<Diagnostic>(x => x.Id == "LUACS008"));
}
}