-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathTestScaffoldGenerator.cs
More file actions
3847 lines (3464 loc) · 175 KB
/
Copy pathTestScaffoldGenerator.cs
File metadata and controls
3847 lines (3464 loc) · 175 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace AiDotNet.Generators;
/// <summary>
/// Roslyn incremental source generator that cross-references model classes against test classes
/// to identify untested models, auto-generate test scaffolds, and produce a coverage report.
/// </summary>
/// <remarks>
/// <para>
/// Discovers all concrete IFullModel implementations decorated with [ModelDomain] and checks
/// for matching test classes. For untested models, resolves the appropriate test base class
/// from [ModelCategory]/[ModelTask] metadata and interface hierarchy, then generates a
/// minimal test class that exercises all inherited invariant tests.
/// </para>
/// <para>
/// Model discovery works in two modes:
/// <list type="bullet">
/// <item>Source mode: finds model classes defined as source in the current compilation (when running in the source project)</item>
/// <item>Reference mode: finds model classes from referenced assemblies (when running in the test project)</item>
/// </list>
/// </para>
/// </remarks>
[Generator]
public class TestScaffoldGenerator : IIncrementalGenerator
{
// Interface detection prefixes
private const string IFullModelName = "AiDotNet.Interfaces.IFullModel";
private const string INeuralNetworkModelName = "AiDotNet.Interfaces.INeuralNetworkModel";
private const string IDiffusionModelName = "AiDotNet.Interfaces.IDiffusionModel";
private const string IGaussianProcessPrefix = "AiDotNet.Interfaces.IGaussianProcess<";
private const string IActivationFunctionPrefix = "AiDotNet.Interfaces.IActivationFunction<";
private const string ILossFunctionPrefix = "AiDotNet.Interfaces.ILossFunction<";
// Non-model algorithm interface prefixes (for invariant test generation)
private const string ICausalDiscoveryPrefix = "AiDotNet.CausalDiscovery.ICausalDiscoveryAlgorithm<";
private const string IActiveLearningPrefix = "AiDotNet.Interfaces.IActiveLearningStrategy<";
private const string IContinualLearningPrefix = "AiDotNet.Interfaces.IContinualLearningStrategy<";
private const string IDistillationPrefix = "AiDotNet.Interfaces.IDistillationStrategy<";
private const string ISafetyModulePrefix = "AiDotNet.Interfaces.ISafetyModule<";
// Base classes whose descendants cannot be auto-constructed for testing.
// These are compositional/wrapper patterns that require a user-provided inner model.
private static readonly string[] ExcludedBaseClasses =
[
"MetaLearnerBase", // Meta-learning: wraps an IFullModel chosen by the user
"MetaLearningModelBase", // Meta-learning variant with different naming
"NeuralProcessBase", // Neural processes: inherits MetaLearnerBase
"ShardedModelBase", // Distributed training: wraps a model for tensor/data parallelism
"NoisePredictorBase", // Noise predictors: internal diffusion components, not standalone
"SSLMethodBase", // Self-supervised learning: wraps encoder + projector
"AudioSafetyModuleBase", // Audio safety: wraps another model for content moderation
"TextSafetyModuleBase", // Text safety: wraps another model for content moderation
"ImageWatermarkerBase", // Watermarking: wraps images, not a standalone model
"SupervisedAutoMLModelBase", // AutoML: wraps other models for hyperparameter search
];
// Attribute metadata names
private const string ModelDomainAttr = "AiDotNet.Attributes.ModelDomainAttribute";
private const string ModelCategoryAttr = "AiDotNet.Attributes.ModelCategoryAttribute";
private const string ModelTaskAttr = "AiDotNet.Attributes.ModelTaskAttribute";
private const string ModelInputAttr = "AiDotNet.Attributes.ModelInputAttribute";
private const string ModelMetadataExemptAttr = "AiDotNet.Attributes.ModelMetadataExemptAttribute";
// Activation/Loss/Layer attribute metadata names
private const string ActivationPropertyAttr = "AiDotNet.Attributes.ActivationPropertyAttribute";
private const string LossPropertyAttr = "AiDotNet.Attributes.LossPropertyAttribute";
private const string LayerPropertyAttr = "AiDotNet.Attributes.LayerPropertyAttribute";
private const string LossFunctionBasePrefix = "AiDotNet.LossFunctions.LossFunctionBase<";
private const string ISelfSupervisedLossPrefix = "AiDotNet.Interfaces.ISelfSupervisedLoss<";
private const string ILayerPrefix = "AiDotNet.Interfaces.ILayer<";
private const string LayerBasePrefix = "AiDotNet.NeuralNetworks.Layers.LayerBase<";
// ModelCategory enum values (must match AiDotNet.Enums.ModelCategory)
private const int CategoryGAN = 4;
private const int CategoryDiffusion = 5;
private const int CategoryGaussianProcess = 8;
private const int CategoryTimeSeriesModel = 13;
private const int CategoryGraphNetwork = 17;
private const int CategoryEmbeddingModel = 18;
private const int CategoryNeuralNetwork = 0;
private const int CategoryMetaLearning = 20;
// ModelTask enum values (must match AiDotNet.Enums.ModelTask)
private const int TaskClassification = 0;
private const int TaskRegression = 1;
private const int TaskClustering = 2;
private static readonly DiagnosticDescriptor UntestedModel = new(
id: "AIDN040",
title: "Model has no test coverage",
messageFormat: "Model '{0}' has no corresponding test class and could not be auto-generated (missing category/task metadata)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Model has no test coverage and lacks sufficient metadata for auto-generation. Add [ModelCategory] and [ModelTask] attributes, or create a manual test class.");
private static readonly DiagnosticDescriptor CoverageSummary = new(
id: "AIDN041",
title: "Model test coverage summary",
messageFormat: "{0} of {1} annotated models have test coverage ({2:F1}%)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor ActivationCoverageSummary = new(
id: "AIDN042",
title: "Activation function test coverage summary",
messageFormat: "{0} of {1} activation functions have test coverage ({2:F1}%)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor LossCoverageSummary = new(
id: "AIDN043",
title: "Loss function test coverage summary",
messageFormat: "{0} of {1} loss functions have test coverage ({2:F1}%)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor LayerCoverageSummary = new(
id: "AIDN044",
title: "Layer test coverage summary",
messageFormat: "{0} of {1} layers have test coverage ({2:F1}%)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor AlgorithmCoverageSummary = new(
id: "AIDN045",
title: "Non-model algorithm test coverage summary",
messageFormat: "{0} of {1} non-model algorithms have test coverage ({2:F1}%)",
category: "AiDotNet.TestCoverage",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public void Initialize(IncrementalGeneratorInitializationContext context)
{
// Collect model classes from source (works when running in the source project)
var modelClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsModelCandidate(node),
transform: static (ctx, _) => GetModelClassOrNull(ctx))
.Where(static s => s is not null);
// Collect test classes (classes ending in Tests/Test or containing [Fact]/[Theory])
var testClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsTestCandidate(node),
transform: static (ctx, _) => GetTestClassName(ctx))
.Where(static s => s is not null);
// Collect activation function classes from source
var activationClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsModelCandidate(node),
transform: static (ctx, _) => GetActivationFunctionOrNull(ctx))
.Where(static s => s is not null);
// Collect loss function classes from source
var lossClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsModelCandidate(node),
transform: static (ctx, _) => GetLossFunctionOrNull(ctx))
.Where(static s => s is not null);
// Collect layer classes from source
var layerClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsModelCandidate(node),
transform: static (ctx, _) => GetLayerOrNull(ctx))
.Where(static s => s is not null);
// Collect non-model algorithm classes (causal discovery, active learning, etc.)
var algorithmClasses = context.SyntaxProvider.CreateSyntaxProvider(
predicate: static (node, _) => IsModelCandidate(node),
transform: static (ctx, _) => GetNonModelAlgorithmOrNull(ctx))
.Where(static s => s is not null);
var combined = modelClasses.Collect()
.Combine(testClasses.Collect())
.Combine(activationClasses.Collect())
.Combine(lossClasses.Collect())
.Combine(layerClasses.Collect())
.Combine(algorithmClasses.Collect())
.Combine(context.CompilationProvider);
context.RegisterSourceOutput(combined, static (spc, source) =>
{
var ((((((models, tests), activations), losses), layers), algorithms), compilation) = source;
Execute(spc, models, tests, compilation);
ExecuteActivationAndLossGeneration(spc, activations, losses, compilation);
ExecuteLayerGeneration(spc, layers, compilation);
ExecuteNonModelAlgorithmGeneration(spc, algorithms, compilation);
});
}
private static bool IsModelCandidate(SyntaxNode node)
{
if (node is not ClassDeclarationSyntax cds)
return false;
if (cds.BaseList is null || cds.BaseList.Types.Count == 0)
return false;
foreach (var modifier in cds.Modifiers)
{
if (modifier.Text == "abstract")
return false;
}
return true;
}
private static bool IsTestCandidate(SyntaxNode node)
{
if (node is not ClassDeclarationSyntax cds)
return false;
// Check if class name ends with "Tests" or "Test"
if (cds.Identifier.Text.EndsWith("Tests", System.StringComparison.Ordinal) ||
cds.Identifier.Text.EndsWith("Test", System.StringComparison.Ordinal))
{
return true;
}
// Check if any method has a test attribute (xUnit, NUnit, or MSTest)
foreach (var member in cds.Members)
{
if (member is MethodDeclarationSyntax method)
{
foreach (var attrList in method.AttributeLists)
{
foreach (var attr in attrList.Attributes)
{
var name = attr.Name.ToString();
// xUnit
if (name == "Fact" || name == "Theory" ||
name == "Xunit.Fact" || name == "Xunit.Theory")
return true;
// NUnit
if (name == "Test" || name == "TestCase" ||
name == "NUnit.Framework.Test" || name == "NUnit.Framework.TestCase")
return true;
// MSTest
if (name == "TestMethod" ||
name == "Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod")
return true;
}
}
}
}
return false;
}
private static INamedTypeSymbol? GetModelClassOrNull(GeneratorSyntaxContext ctx)
{
var symbol = ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol;
if (symbol is null || symbol.IsAbstract)
return null;
foreach (var iface in symbol.AllInterfaces)
{
if (iface.IsGenericType &&
iface.OriginalDefinition.ToDisplayString().StartsWith(IFullModelName, System.StringComparison.Ordinal))
{
return symbol;
}
}
return null;
}
private static string? GetTestClassName(GeneratorSyntaxContext ctx)
{
if (ctx.Node is not ClassDeclarationSyntax cds)
return null;
return cds.Identifier.Text;
}
/// <summary>
/// Returns the type symbol if it implements IActivationFunction<T> and has [ActivationProperty].
/// </summary>
private static INamedTypeSymbol? GetActivationFunctionOrNull(GeneratorSyntaxContext ctx)
{
var symbol = ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol;
if (symbol is null || symbol.IsAbstract)
return null;
// Check for [ActivationProperty] attribute
bool hasActivationProperty = false;
foreach (var attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null &&
attr.AttributeClass.ToDisplayString().EndsWith("ActivationPropertyAttribute", System.StringComparison.Ordinal))
{
hasActivationProperty = true;
break;
}
}
if (!hasActivationProperty)
return null;
// Verify it implements IActivationFunction<T>
foreach (var iface in symbol.AllInterfaces)
{
if (iface.IsGenericType &&
iface.OriginalDefinition.ToDisplayString().StartsWith(IActivationFunctionPrefix, System.StringComparison.Ordinal))
{
return symbol;
}
}
return null;
}
/// <summary>
/// Returns the type symbol if it extends LayerBase<T> (or implements ILayer<T>)
/// and has [LayerProperty].
/// </summary>
private static INamedTypeSymbol? GetLayerOrNull(GeneratorSyntaxContext ctx)
{
var symbol = ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol;
if (symbol is null || symbol.IsAbstract)
return null;
// Check for [LayerProperty] attribute
bool hasLayerProperty = false;
foreach (var attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null &&
attr.AttributeClass.ToDisplayString().EndsWith("LayerPropertyAttribute", System.StringComparison.Ordinal))
{
hasLayerProperty = true;
break;
}
}
if (!hasLayerProperty)
return null;
// Check if it implements ILayer<T> or extends LayerBase<T>
foreach (var iface in symbol.AllInterfaces)
{
if (iface.IsGenericType &&
iface.OriginalDefinition.ToDisplayString().StartsWith(ILayerPrefix, System.StringComparison.Ordinal))
{
return symbol;
}
}
// Check base type chain for LayerBase<T>
var baseType = symbol.BaseType;
while (baseType is not null)
{
if (baseType.IsGenericType &&
baseType.OriginalDefinition.ToDisplayString().StartsWith(LayerBasePrefix, System.StringComparison.Ordinal))
{
return symbol;
}
baseType = baseType.BaseType;
}
return null;
}
/// <summary>
/// Classifies which non-model algorithm category a type belongs to.
/// </summary>
private enum AlgorithmCategory { None, CausalDiscovery, ActiveLearning, ContinualLearning, Distillation }
/// <summary>
/// Returns the type symbol if it implements a non-model algorithm interface
/// (ICausalDiscoveryAlgorithm, IActiveLearningStrategy, IContinualLearningStrategy, IDistillationStrategy)
/// and has a [ModelDomain] attribute. These classes get invariant tests but are NOT IFullModel models.
/// </summary>
private static INamedTypeSymbol? GetNonModelAlgorithmOrNull(GeneratorSyntaxContext ctx)
{
var symbol = ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol;
if (symbol is null || symbol.IsAbstract)
return null;
// Must have [ModelDomain] attribute
bool hasModelDomain = false;
foreach (var attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null &&
attr.AttributeClass.ToDisplayString().EndsWith("ModelDomainAttribute", System.StringComparison.Ordinal))
{
hasModelDomain = true;
break;
}
}
if (!hasModelDomain)
return null;
// Skip classes that already implement IFullModel (handled by model test generation)
if (ImplementsIFullModel(symbol))
return null;
// Check for non-model algorithm interfaces
foreach (var iface in symbol.AllInterfaces)
{
if (!iface.IsGenericType) continue;
var display = iface.OriginalDefinition.ToDisplayString();
if (display.StartsWith(ICausalDiscoveryPrefix, System.StringComparison.Ordinal) ||
display.StartsWith(IActiveLearningPrefix, System.StringComparison.Ordinal) ||
display.StartsWith(IContinualLearningPrefix, System.StringComparison.Ordinal) ||
display.StartsWith(IDistillationPrefix, System.StringComparison.Ordinal))
{
return symbol;
}
}
return null;
}
/// <summary>
/// Determines which algorithm category a type belongs to based on its interfaces.
/// </summary>
private static AlgorithmCategory ClassifyAlgorithm(INamedTypeSymbol type)
{
foreach (var iface in type.AllInterfaces)
{
if (!iface.IsGenericType) continue;
var display = iface.OriginalDefinition.ToDisplayString();
if (display.StartsWith(ICausalDiscoveryPrefix, System.StringComparison.Ordinal))
return AlgorithmCategory.CausalDiscovery;
if (display.StartsWith(IActiveLearningPrefix, System.StringComparison.Ordinal))
return AlgorithmCategory.ActiveLearning;
if (display.StartsWith(IDistillationPrefix, System.StringComparison.Ordinal))
return AlgorithmCategory.Distillation;
if (display.StartsWith(IContinualLearningPrefix, System.StringComparison.Ordinal))
return AlgorithmCategory.ContinualLearning;
}
return AlgorithmCategory.None;
}
/// <summary>
/// Returns the type symbol if it extends LossFunctionBase<T> (or implements ILossFunction<T>)
/// and has [LossProperty].
/// </summary>
private static INamedTypeSymbol? GetLossFunctionOrNull(GeneratorSyntaxContext ctx)
{
var symbol = ctx.SemanticModel.GetDeclaredSymbol(ctx.Node) as INamedTypeSymbol;
if (symbol is null || symbol.IsAbstract)
return null;
// Check for [LossProperty] attribute
bool hasLossProperty = false;
foreach (var attr in symbol.GetAttributes())
{
if (attr.AttributeClass is not null &&
attr.AttributeClass.ToDisplayString().EndsWith("LossPropertyAttribute", System.StringComparison.Ordinal))
{
hasLossProperty = true;
break;
}
}
if (!hasLossProperty)
return null;
// Check if it implements ILossFunction<T> or extends LossFunctionBase<T>
foreach (var iface in symbol.AllInterfaces)
{
if (iface.IsGenericType &&
iface.OriginalDefinition.ToDisplayString().StartsWith(ILossFunctionPrefix, System.StringComparison.Ordinal))
{
return symbol;
}
}
// Also check base type chain for LossFunctionBase
var baseType = symbol.BaseType;
while (baseType is not null)
{
if (baseType.IsGenericType &&
baseType.OriginalDefinition.ToDisplayString().StartsWith(LossFunctionBasePrefix, System.StringComparison.Ordinal))
{
return symbol;
}
baseType = baseType.BaseType;
}
// Also check for ISelfSupervisedLoss<T>
foreach (var iface in symbol.AllInterfaces)
{
if (iface.IsGenericType &&
iface.OriginalDefinition.ToDisplayString().StartsWith(ISelfSupervisedLossPrefix, System.StringComparison.Ordinal))
{
return symbol;
}
}
return null;
}
private static void Execute(
SourceProductionContext context,
ImmutableArray<INamedTypeSymbol?> sourceModels,
ImmutableArray<string?> testClassNames,
Compilation compilation)
{
var domainAttrSymbol = compilation.GetTypeByMetadataName(ModelDomainAttr);
var categoryAttrSymbol = compilation.GetTypeByMetadataName(ModelCategoryAttr);
var taskAttrSymbol = compilation.GetTypeByMetadataName(ModelTaskAttr);
var exemptAttrSymbol = compilation.GetTypeByMetadataName(ModelMetadataExemptAttr);
var architectureSymbol = compilation.GetTypeByMetadataName("AiDotNet.NeuralNetworks.NeuralNetworkArchitecture`1");
// Build test class name set for fast lookup
var testNames = new HashSet<string>(System.StringComparer.OrdinalIgnoreCase);
foreach (var name in testClassNames)
{
if (name is not null)
testNames.Add(name);
}
var testedModels = new List<ModelTestInfo>();
var untestedModels = new List<ModelTestInfo>();
var seen = new HashSet<string>();
// First: collect models from source (syntax-based discovery)
foreach (var modelClass in sourceModels)
{
if (modelClass is null)
continue;
ProcessModelSymbol(modelClass, domainAttrSymbol, categoryAttrSymbol, taskAttrSymbol,
exemptAttrSymbol, architectureSymbol, testNames, testedModels, untestedModels, seen);
}
// Detect if we're in the source project (not the test project).
string assemblyName = compilation.AssemblyName ?? string.Empty;
bool isTestProject = assemblyName.IndexOf("Test", System.StringComparison.OrdinalIgnoreCase) >= 0;
bool modelsFoundFromSource = seen.Count > 0 && !isTestProject;
// Second: if no source models were found, discover from referenced assemblies.
if (!modelsFoundFromSource)
{
DiscoverModelsFromReferencedAssemblies(compilation, domainAttrSymbol, categoryAttrSymbol,
taskAttrSymbol, exemptAttrSymbol, architectureSymbol, testNames, testedModels, untestedModels, seen);
}
testedModels.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, System.StringComparison.Ordinal));
untestedModels.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, System.StringComparison.Ordinal));
// Auto-generate test classes for untested models (test project only)
if (!modelsFoundFromSource)
{
var autoGenerated = new List<ModelTestInfo>();
var generatedTestNames = new HashSet<string>(System.StringComparer.OrdinalIgnoreCase);
foreach (var model in untestedModels)
{
var family = ResolveTestBaseClass(model);
if (family is null)
continue;
var testClassName = StripBacktick(model.ClassName) + "Tests";
// Avoid duplicate test class names and conflicts with existing tests.
// A duplicate means this model was already auto-generated (same model
// discovered from multiple referenced assemblies) — still count as covered.
if (!generatedTestNames.Add(testClassName))
{
autoGenerated.Add(model);
testNames.Add(testClassName);
continue;
}
if (testNames.Contains(testClassName))
continue;
// Use constructor call if the model has a zero-arg constructor and is type-compatible.
// For models with architecture-only constructors, emit a default architecture.
// Otherwise, emit a throw so the test compiles but fails at runtime with a clear message.
// Skip test generation entirely for compositional/wrapper patterns
// that can't be auto-constructed (meta-learning, distributed, etc.)
if (model.InheritsFromExcludedBase)
continue;
bool canConstruct = (model.HasParameterlessConstructor || model.HasArchitectureOnlyConstructor) &&
IsCompatibleWithFamily(model, family.Value);
EmitGeneratedTestClass(context, model, family.Value, testClassName, canConstruct);
autoGenerated.Add(model);
testNames.Add(testClassName);
}
// Move auto-generated from untested → tested (only if constructible)
foreach (var model in autoGenerated)
{
untestedModels.Remove(model);
// Only count as "has tests" if the test can actually construct the model.
// Runtime-throwing scaffolds don't provide real test coverage.
bool constructible = !string.IsNullOrEmpty(model.ClassName);
model.HasTests = constructible;
testedModels.Add(model);
}
// Re-sort after moves
testedModels.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, System.StringComparison.Ordinal));
untestedModels.Sort((a, b) => string.Compare(a.ClassName, b.ClassName, System.StringComparison.Ordinal));
// Emit AIDN040 for remaining untested models
foreach (var model in untestedModels)
{
context.ReportDiagnostic(Diagnostic.Create(
UntestedModel,
Location.None,
model.ClassName));
}
// Emit AIDN041 summary
var totalCount = testedModels.Count + untestedModels.Count;
if (totalCount > 0)
{
var coveragePct = testedModels.Count * 100.0 / totalCount;
context.ReportDiagnostic(Diagnostic.Create(
CoverageSummary,
Location.None,
testedModels.Count,
totalCount,
coveragePct));
}
}
EmitTestCoverageClass(context, testedModels, untestedModels);
}
/// <summary>
/// Processes a single model type symbol, extracting metadata and checking for test coverage.
/// </summary>
private static void ProcessModelSymbol(
INamedTypeSymbol modelClass,
INamedTypeSymbol? domainAttrSymbol,
INamedTypeSymbol? categoryAttrSymbol,
INamedTypeSymbol? taskAttrSymbol,
INamedTypeSymbol? exemptAttrSymbol,
INamedTypeSymbol? architectureSymbol,
HashSet<string> testNames,
List<ModelTestInfo> testedModels,
List<ModelTestInfo> untestedModels,
HashSet<string> seen)
{
var fullName = modelClass.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat);
if (!seen.Add(fullName))
return;
// Skip classes marked with [ModelMetadataExempt]
if (exemptAttrSymbol is not null && HasAttribute(modelClass.GetAttributes(), exemptAttrSymbol))
return;
// Extract attributes and detect input/output types
bool hasModelDomain = false;
var domains = new List<int>();
var categories = new List<int>();
var tasks = new List<int>();
// NOTE: These boolean flags are a lossy representation of the actual generic
// type parameters. A more precise approach would track the full INamedTypeSymbol
// for input/output types. Current approach is sufficient for test scaffolding
// (determines which test helper to call) but can't distinguish e.g. Tensor<float>
// from Tensor<double> or custom TInput types.
bool usesTensorInput = false;
bool usesMatrixInput = false;
bool usesVectorOutput = false;
foreach (var attr in modelClass.GetAttributes())
{
if (attr.AttributeClass is null)
continue;
// Use SymbolEqualityComparer first, fall back to string matching
// for cross-assembly scenarios where symbol resolution may differ
bool isDomain = (domainAttrSymbol is not null &&
SymbolEqualityComparer.Default.Equals(attr.AttributeClass, domainAttrSymbol)) ||
attr.AttributeClass.ToDisplayString().EndsWith("ModelDomainAttribute", System.StringComparison.Ordinal);
bool isCategory = (categoryAttrSymbol is not null &&
SymbolEqualityComparer.Default.Equals(attr.AttributeClass, categoryAttrSymbol)) ||
attr.AttributeClass.ToDisplayString().EndsWith("ModelCategoryAttribute", System.StringComparison.Ordinal);
bool isTask = (taskAttrSymbol is not null &&
SymbolEqualityComparer.Default.Equals(attr.AttributeClass, taskAttrSymbol)) ||
attr.AttributeClass.ToDisplayString().EndsWith("ModelTaskAttribute", System.StringComparison.Ordinal);
bool isInput = attr.AttributeClass.ToDisplayString().EndsWith("ModelInputAttribute", System.StringComparison.Ordinal);
if (isDomain)
{
hasModelDomain = true;
if (attr.ConstructorArguments.Length >= 1 && attr.ConstructorArguments[0].Value is int d)
domains.Add(d);
}
else if (isCategory)
{
if (attr.ConstructorArguments.Length >= 1 && attr.ConstructorArguments[0].Value is int c)
categories.Add(c);
}
else if (isTask)
{
if (attr.ConstructorArguments.Length >= 1 && attr.ConstructorArguments[0].Value is int t)
tasks.Add(t);
}
else if (isInput && attr.ConstructorArguments.Length >= 2)
{
// [ModelInput(typeof(Tensor<>), typeof(Tensor<>))] or [ModelInput(typeof(Matrix<>), typeof(Vector<>))]
// For metadata types, ConstructorArguments[0].Value is an INamedTypeSymbol
var inputTypeSym = attr.ConstructorArguments[0].Value as INamedTypeSymbol;
var outputTypeSym = attr.ConstructorArguments[1].Value as INamedTypeSymbol;
if (inputTypeSym is not null)
{
var inputName = inputTypeSym.Name;
if (inputName.Contains("Tensor"))
usesTensorInput = true;
else if (inputName.Contains("Matrix"))
usesMatrixInput = true;
}
if (outputTypeSym is not null)
{
if (outputTypeSym.Name.Contains("Vector"))
usesVectorOutput = true;
}
}
}
if (!hasModelDomain)
return;
// Detect interfaces and refine input types from the type hierarchy
bool implementsNeuralNetworkModel = false;
bool implementsDiffusionModel = false;
bool implementsGaussianProcess = false;
foreach (var iface in modelClass.AllInterfaces)
{
if (!iface.IsGenericType)
continue;
var display = iface.OriginalDefinition.ToDisplayString();
if (display.StartsWith(INeuralNetworkModelName, System.StringComparison.Ordinal))
{
implementsNeuralNetworkModel = true;
}
else if (display.StartsWith(IDiffusionModelName, System.StringComparison.Ordinal))
{
implementsDiffusionModel = true;
}
else if (display.StartsWith(IGaussianProcessPrefix, System.StringComparison.Ordinal))
{
implementsGaussianProcess = true;
}
// Detect IFullModel type arguments for input/output types
if (display.StartsWith(IFullModelName, System.StringComparison.Ordinal) &&
iface.TypeArguments.Length >= 3)
{
var inputTypeDisplay = iface.TypeArguments[1].ToDisplayString();
var outputTypeDisplay = iface.TypeArguments[2].ToDisplayString();
if (inputTypeDisplay.Contains("Matrix"))
usesMatrixInput = true;
else if (inputTypeDisplay.Contains("Tensor"))
usesTensorInput = true;
if (outputTypeDisplay.Contains("Vector"))
usesVectorOutput = true;
}
}
// Walk the base type chain to detect mid-level hierarchy bases
bool extendsAudioNN = false, extendsDocumentNN = false, extendsVisionLanguage = false;
bool extendsSegmentation = false, extendsVideoNN = false;
bool extendsTts = false, extendsFinancial = false, extendsNER = false, extendsCode = false;
bool extendsLatentDiffusion = false, extendsNonLinearRegression = false;
bool extendsProbabilisticClassifier = false;
// Phase B gap + Phase C
bool extendsForecasting = false, extendsThreeDDiffusion = false;
bool extendsAnomalyDetector = false, extendsSurvival = false;
bool extendsCausal = false, extendsRLAgent = false;
// Phase B leaf-level
bool extendsVideoDiffusion = false, extendsAudioDiffusion = false;
bool extendsFrameInterpolation = false, extendsVideoSR = false, extendsVideoDenoising = false;
bool extendsAudioClassifier = false, extendsOpticalFlow = false, extendsSpeakerRecognition = false;
bool extendsEnsembleClassifier = false, extendsNaiveBayes = false, extendsSVM = false;
bool extendsVideoInpainting = false, extendsVideoStabilization = false;
bool extendsLinearClassifier = false, extendsMetaClassifier = false;
bool extendsOrdinalClassifier = false, extendsSemiSupervised = false;
bool extendsMultiLabel = false, extendsFinancialNLP = false;
bool extendsRiskModel = false, extendsPortfolioOptimizer = false;
bool extendsTransformerNER = false, extendsSpanBasedNER = false, extendsSequenceLabelingNER = false;
var baseType = modelClass.BaseType;
while (baseType is not null)
{
var baseName = baseType.Name;
// Phase B extended leaf-level checks
if (baseName.StartsWith("VideoInpaintingBase", System.StringComparison.Ordinal))
extendsVideoInpainting = true;
else if (baseName.StartsWith("VideoStabilizationBase", System.StringComparison.Ordinal))
extendsVideoStabilization = true;
else if (baseName.StartsWith("LinearClassifierBase", System.StringComparison.Ordinal))
extendsLinearClassifier = true;
else if (baseName.StartsWith("MetaClassifierBase", System.StringComparison.Ordinal))
extendsMetaClassifier = true;
else if (baseName.StartsWith("OrdinalClassifierBase", System.StringComparison.Ordinal))
extendsOrdinalClassifier = true;
else if (baseName.StartsWith("SemiSupervisedClassifierBase", System.StringComparison.Ordinal))
extendsSemiSupervised = true;
else if (baseName.StartsWith("MultiLabelClassifierBase", System.StringComparison.Ordinal))
extendsMultiLabel = true;
else if (baseName.StartsWith("FinancialNLPModelBase", System.StringComparison.Ordinal))
extendsFinancialNLP = true;
else if (baseName.StartsWith("RiskModelBase", System.StringComparison.Ordinal))
extendsRiskModel = true;
else if (baseName.StartsWith("PortfolioOptimizerBase", System.StringComparison.Ordinal))
extendsPortfolioOptimizer = true;
else if (baseName.StartsWith("TransformerNERBase", System.StringComparison.Ordinal))
extendsTransformerNER = true;
else if (baseName.StartsWith("SpanBasedNERBase", System.StringComparison.Ordinal))
extendsSpanBasedNER = true;
else if (baseName.StartsWith("SequenceLabelingNERBase", System.StringComparison.Ordinal))
extendsSequenceLabelingNER = true;
// Phase B leaf-level checks (most specific first)
else if (baseName.StartsWith("VideoDiffusionModelBase", System.StringComparison.Ordinal))
extendsVideoDiffusion = true;
else if (baseName.StartsWith("AudioDiffusionModelBase", System.StringComparison.Ordinal))
extendsAudioDiffusion = true;
else if (baseName.StartsWith("FrameInterpolationBase", System.StringComparison.Ordinal))
extendsFrameInterpolation = true;
else if (baseName.StartsWith("VideoSuperResolutionBase", System.StringComparison.Ordinal))
extendsVideoSR = true;
else if (baseName.StartsWith("VideoDenoisingBase", System.StringComparison.Ordinal))
extendsVideoDenoising = true;
else if (baseName.StartsWith("AudioClassifierBase", System.StringComparison.Ordinal))
extendsAudioClassifier = true;
else if (baseName.StartsWith("OpticalFlowBase", System.StringComparison.Ordinal))
extendsOpticalFlow = true;
else if (baseName.StartsWith("SpeakerRecognitionBase", System.StringComparison.Ordinal))
extendsSpeakerRecognition = true;
else if (baseName.StartsWith("EnsembleClassifierBase", System.StringComparison.Ordinal))
extendsEnsembleClassifier = true;
else if (baseName.StartsWith("NaiveBayesBase", System.StringComparison.Ordinal))
extendsNaiveBayes = true;
else if (baseName.StartsWith("SVMBase", System.StringComparison.Ordinal))
extendsSVM = true;
// Phase A mid-level checks
else if (baseName.StartsWith("AudioNeuralNetworkBase", System.StringComparison.Ordinal))
extendsAudioNN = true;
else if (baseName.StartsWith("DocumentNeuralNetworkBase", System.StringComparison.Ordinal))
extendsDocumentNN = true;
else if (baseName.StartsWith("VisionLanguageModelBase", System.StringComparison.Ordinal))
extendsVisionLanguage = true;
else if (baseName.StartsWith("SegmentationModelBase", System.StringComparison.Ordinal) ||
baseName.EndsWith("SegmentationBase", System.StringComparison.Ordinal))
extendsSegmentation = true;
else if (baseName.StartsWith("VideoNeuralNetworkBase", System.StringComparison.Ordinal) ||
baseName.EndsWith("VideoBase", System.StringComparison.Ordinal))
extendsVideoNN = true;
else if (baseName.StartsWith("TtsModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("AcousticModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("VocoderBase", System.StringComparison.Ordinal))
extendsTts = true;
else if (baseName.StartsWith("ForecastingModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("TimeSeriesFoundationModelBase", System.StringComparison.Ordinal))
extendsForecasting = true;
else if (baseName.StartsWith("FinancialModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("RiskModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("PortfolioOptimizerBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("FinancialNLPModelBase", System.StringComparison.Ordinal))
extendsFinancial = true;
else if (baseName.StartsWith("NERNeuralNetworkBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("SequenceLabelingNERBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("SpanBasedNERBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("TransformerNERBase", System.StringComparison.Ordinal))
extendsNER = true;
else if (baseName.StartsWith("CodeModelBase", System.StringComparison.Ordinal))
extendsCode = true;
else if (baseName.StartsWith("ThreeDDiffusionModelBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("3DDiffusionModelBase", System.StringComparison.Ordinal))
extendsThreeDDiffusion = true;
else if (baseName.StartsWith("AnomalyDetectorBase", System.StringComparison.Ordinal))
extendsAnomalyDetector = true;
else if (baseName.StartsWith("SurvivalModelBase", System.StringComparison.Ordinal))
extendsSurvival = true;
else if (baseName.StartsWith("CausalModelBase", System.StringComparison.Ordinal))
extendsCausal = true;
else if (baseName.StartsWith("ReinforcementLearningAgentBase", System.StringComparison.Ordinal) ||
baseName.StartsWith("DeepReinforcementLearningAgentBase", System.StringComparison.Ordinal))
extendsRLAgent = true;
else if (baseName.StartsWith("LatentDiffusionModelBase", System.StringComparison.Ordinal))
extendsLatentDiffusion = true;
else if (baseName.StartsWith("NonLinearRegressionBase", System.StringComparison.Ordinal))
extendsNonLinearRegression = true;
else if (baseName.StartsWith("ProbabilisticClassifierBase", System.StringComparison.Ordinal))
extendsProbabilisticClassifier = true;
baseType = baseType.BaseType;
}
// Detect a public constructor callable with zero arguments:
// either parameterless, or all parameters have default values.
bool hasParameterlessCtor = false;
bool hasArchitectureOnlyCtor = false;
string? architectureParamTypeName = null;
foreach (var ctor in modelClass.InstanceConstructors)
{
if (ctor.DeclaredAccessibility != Accessibility.Public)
continue;
if (ctor.Parameters.Length == 0)
{
hasParameterlessCtor = true;
break;
}
// Check if all parameters have default values (callable with zero args)
bool allOptional = true;
foreach (var param in ctor.Parameters)
{
if (!param.HasExplicitDefaultValue)
{
allOptional = false;
break;
}
}
if (allOptional)
{
hasParameterlessCtor = true;
break;
}
// Check if only the first parameter is required and is NeuralNetworkArchitecture<T>.
// The rest must all have default values. This allows generating a default architecture.
if (ctor.Parameters.Length >= 1)
{
var firstParam = ctor.Parameters[0];
// Check if the first parameter type IS exactly NeuralNetworkArchitecture<T>.
// Derived types (CodeSynthesisArchitecture<T>, etc.) have incompatible constructors
// and need manual test classes — they stay as NotImplementedException.
bool isArchitectureParam = IsExactlyArchitecture(firstParam.Type, architectureSymbol);
if (isArchitectureParam && !firstParam.HasExplicitDefaultValue)
{
bool restOptional = true;
for (int pi = 1; pi < ctor.Parameters.Length; pi++)
{
// Only explicit default values make a parameter optional.
// Nullable type annotations (string?) do NOT imply optionality.
if (!ctor.Parameters[pi].HasExplicitDefaultValue)
{
restOptional = false;
break;
}
}
if (restOptional)
{
hasArchitectureOnlyCtor = true;
// Store the actual param type for derived architectures.
// For generic types, replace the type parameter with 'double'.
string paramTypeName = firstParam.Type.ToDisplayString();
if (firstParam.Type is INamedTypeSymbol { IsGenericType: true } namedParamType)
{
// Get the unbound definition and reconstruct with double
string openName = namedParamType.OriginalDefinition.ToDisplayString();
// Replace the type parameter (e.g., T) with double
architectureParamTypeName = openName.Replace("<T>", "<double>");
}
else
{
architectureParamTypeName = paramTypeName;
}
}
}
}
}
var className = modelClass.Name;
var info = new ModelTestInfo
{
ClassName = className,
FullyQualifiedName = fullName,
TypeParameterCount = modelClass.TypeParameters.Length,
Domains = domains,
Categories = categories,
Tasks = tasks,
ImplementsNeuralNetworkModel = implementsNeuralNetworkModel,
ImplementsDiffusionModel = implementsDiffusionModel,
ImplementsGaussianProcess = implementsGaussianProcess,
UsesTensorInput = usesTensorInput,
UsesMatrixInput = usesMatrixInput,
UsesVectorOutput = usesVectorOutput,
HasParameterlessConstructor = hasParameterlessCtor,
HasArchitectureOnlyConstructor = hasArchitectureOnlyCtor,
InheritsFromExcludedBase = InheritsFromAnyExcludedBase(modelClass),
ArchitectureParamTypeName = architectureParamTypeName,
ExtendsAudioNeuralNetworkBase = extendsAudioNN,
ExtendsDocumentNeuralNetworkBase = extendsDocumentNN,
ExtendsVisionLanguageModelBase = extendsVisionLanguage,
ExtendsSegmentationModelBase = extendsSegmentation,
ExtendsVideoNeuralNetworkBase = extendsVideoNN,
ExtendsTtsModelBase = extendsTts,
ExtendsFinancialModelBase = extendsFinancial,
ExtendsNERNeuralNetworkBase = extendsNER,
ExtendsCodeModelBase = extendsCode,
ExtendsVideoDiffusionModelBase = extendsVideoDiffusion,
ExtendsAudioDiffusionModelBase = extendsAudioDiffusion,