-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQuantitiesGenerator.cs
More file actions
1225 lines (1071 loc) · 40.2 KB
/
QuantitiesGenerator.cs
File metadata and controls
1225 lines (1071 loc) · 40.2 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
// Copyright (c) ktsu.dev
// All rights reserved.
// Licensed under the MIT license.
namespace Semantics.SourceGenerators;
using System;
using System.Collections.Generic;
using System.Linq;
using ktsu.CodeBlocker;
using Microsoft.CodeAnalysis;
using Semantics.SourceGenerators.Models;
using Semantics.SourceGenerators.Templates;
/// <summary>
/// Source generator that creates quantity types from the unified vector schema in dimensions.json.
/// Uses a two-phase approach: first collects all cross-dimensional operators globally,
/// then generates each type with its assigned operators.
/// </summary>
[Generator]
public class QuantitiesGenerator : GeneratorBase<DimensionsMetadata>
{
private static readonly DiagnosticDescriptor UnknownDimensionReference = new(
id: "SEM001",
title: "Unknown dimension reference in physics relationship",
messageFormat: "Dimension '{0}' references unknown dimension '{1}' in {2}; the operator will not be generated. Check spelling and that the referenced dimension exists in dimensions.json.",
category: "Semantics.SourceGenerators",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public QuantitiesGenerator() : base("dimensions.json") { }
protected override void Generate(SourceProductionContext context, DimensionsMetadata metadata, CodeBlocker codeBlocker)
{
if (metadata.PhysicalDimensions == null || metadata.PhysicalDimensions.Count == 0)
{
return;
}
// Phase A: Build maps and collect operators
Dictionary<string, PhysicalDimension> dimensionMap = BuildDimensionMap(metadata);
Dictionary<string, int> typeFormMap = BuildTypeFormMap(metadata);
List<OperatorInfo> allOperators = CollectAllOperators(context, metadata, dimensionMap);
List<ProductInfo> allProducts = CollectAllProducts(context, metadata, dimensionMap);
Dictionary<string, List<OperatorInfo>> operatorsByOwner = GroupBy(allOperators, o => o.OwnerTypeName);
Dictionary<string, List<ProductInfo>> productsByOwner = GroupBy(allProducts, p => p.SelfTypeName);
// Phase B: Generate types
foreach (PhysicalDimension dim in metadata.PhysicalDimensions)
{
if (dim.Quantities.Vector0 != null)
{
EmitV0BaseType(context, dim, operatorsByOwner, typeFormMap);
}
if (dim.Quantities.Vector1 != null)
{
EmitV1BaseType(context, dim, operatorsByOwner, typeFormMap);
}
int[] vectorDims = [2, 3, 4];
foreach (int d in vectorDims)
{
VectorFormDefinition? form = GetFormDef(dim, d);
if (form != null)
{
EmitVectorType(context, dim, d, form, operatorsByOwner, productsByOwner, typeFormMap);
}
}
// Emit semantic overloads for all vector forms
int[] allForms = [0, 1, 2, 3, 4];
foreach (int f in allForms)
{
VectorFormDefinition? form = GetFormDef(dim, f);
if (form != null)
{
foreach (OverloadDefinition overload in form.Overloads)
{
EmitOverloadType(context, dim, f, form.Base, overload, typeFormMap);
}
}
}
}
}
#region Phase A: Map Building and Operator Collection
private static Dictionary<string, PhysicalDimension> BuildDimensionMap(DimensionsMetadata metadata)
{
Dictionary<string, PhysicalDimension> map = [];
foreach (PhysicalDimension dim in metadata.PhysicalDimensions)
{
map[dim.Name] = dim;
}
return map;
}
private static Dictionary<string, int> BuildTypeFormMap(DimensionsMetadata metadata)
{
Dictionary<string, int> map = [];
foreach (PhysicalDimension dim in metadata.PhysicalDimensions)
{
int[] forms = [0, 1, 2, 3, 4];
foreach (int f in forms)
{
VectorFormDefinition? form = GetFormDef(dim, f);
if (form != null)
{
map[form.Base] = f;
foreach (OverloadDefinition overload in form.Overloads)
{
map[overload.Name] = f;
}
}
}
}
return map;
}
private static List<OperatorInfo> CollectAllOperators(SourceProductionContext context, DimensionsMetadata metadata, Dictionary<string, PhysicalDimension> dimMap)
{
HashSet<string> seen = [];
List<OperatorInfo> result = [];
foreach (PhysicalDimension dim in metadata.PhysicalDimensions)
{
// Process integrals: Self * Other = Result
foreach (RelationshipDefinition integral in dim.Integrals)
{
if (!dimMap.TryGetValue(integral.Other, out PhysicalDimension? otherDim))
{
ReportUnknownReference(context, dim.Name, integral.Other, $"integrals[{integral.Other} -> {integral.Result}].other");
continue;
}
if (!dimMap.TryGetValue(integral.Result, out PhysicalDimension? resultDim))
{
ReportUnknownReference(context, dim.Name, integral.Result, $"integrals[{integral.Other} -> {integral.Result}].result");
continue;
}
// V0(Other) is the scalar multiplier
string? v0Other = otherDim.Quantities.Vector0?.Base;
if (v0Other == null)
{
continue;
}
int[] forms = [0, 1, 2, 3, 4];
foreach (int vn in forms)
{
string? selfType = GetBaseTypeName(dim, vn);
string? resultType = GetBaseTypeName(resultDim, vn);
if (selfType == null || resultType == null)
{
continue;
}
// Forward: VN(Self) * V0(Other) => VN(Result)
AddOp(result, seen, "*", selfType, v0Other, resultType, selfType);
// Commutative: V0(Other) * VN(Self) => VN(Result)
AddOp(result, seen, "*", v0Other, selfType, resultType, v0Other);
// Inverse: VN(Result) / V0(Other) => VN(Self)
AddOp(result, seen, "/", resultType, v0Other, selfType, resultType);
// Inverse: VN(Result) / VN(Self) => V0(Other) -- only if VN == V0
if (vn == 0)
{
AddOp(result, seen, "/", resultType, selfType, v0Other, resultType);
}
}
}
// Process derivatives: Self / Other = Result
foreach (RelationshipDefinition derivative in dim.Derivatives)
{
if (!dimMap.TryGetValue(derivative.Other, out PhysicalDimension? otherDim))
{
ReportUnknownReference(context, dim.Name, derivative.Other, $"derivatives[{derivative.Other} -> {derivative.Result}].other");
continue;
}
if (!dimMap.TryGetValue(derivative.Result, out PhysicalDimension? resultDim))
{
ReportUnknownReference(context, dim.Name, derivative.Result, $"derivatives[{derivative.Other} -> {derivative.Result}].result");
continue;
}
string? v0Other = otherDim.Quantities.Vector0?.Base;
if (v0Other == null)
{
continue;
}
int[] forms = [0, 1, 2, 3, 4];
foreach (int vn in forms)
{
string? selfType = GetBaseTypeName(dim, vn);
string? resultType = GetBaseTypeName(resultDim, vn);
if (selfType == null || resultType == null)
{
continue;
}
// Forward: VN(Self) / V0(Other) => VN(Result)
AddOp(result, seen, "/", selfType, v0Other, resultType, selfType);
// Inverse integral: VN(Result) * V0(Other) => VN(Self)
AddOp(result, seen, "*", resultType, v0Other, selfType, resultType);
// Commutative inverse: V0(Other) * VN(Result) => VN(Self)
AddOp(result, seen, "*", v0Other, resultType, selfType, v0Other);
}
}
}
return result;
}
private static List<ProductInfo> CollectAllProducts(SourceProductionContext context, DimensionsMetadata metadata, Dictionary<string, PhysicalDimension> dimMap)
{
HashSet<string> seen = [];
List<ProductInfo> result = [];
foreach (PhysicalDimension dim in metadata.PhysicalDimensions)
{
// Dot products: VN(Self) . VN(Other) => V0(Result)
foreach (RelationshipDefinition dot in dim.DotProducts)
{
if (!dimMap.TryGetValue(dot.Other, out PhysicalDimension? otherDim))
{
ReportUnknownReference(context, dim.Name, dot.Other, $"dotProducts[{dot.Other} -> {dot.Result}].other");
continue;
}
if (!dimMap.TryGetValue(dot.Result, out PhysicalDimension? resultDim))
{
ReportUnknownReference(context, dim.Name, dot.Result, $"dotProducts[{dot.Other} -> {dot.Result}].result");
continue;
}
string? v0Result = resultDim.Quantities.Vector0?.Base;
if (v0Result == null)
{
continue;
}
// Dot product for V1+ forms where both self and other have that form
int[] forms = [1, 2, 3, 4];
foreach (int vn in forms)
{
string? selfType = GetBaseTypeName(dim, vn);
string? otherType = GetBaseTypeName(otherDim, vn);
if (selfType == null || otherType == null)
{
continue;
}
string key = $"Dot:{selfType}:{otherType}:{v0Result}";
if (seen.Add(key))
{
result.Add(new ProductInfo("Dot", selfType, otherType, v0Result, vn));
}
}
}
// Cross products: V3(Self) x V3(Other) => V3(Result)
foreach (RelationshipDefinition cross in dim.CrossProducts)
{
if (!dimMap.TryGetValue(cross.Other, out PhysicalDimension? otherDim))
{
ReportUnknownReference(context, dim.Name, cross.Other, $"crossProducts[{cross.Other} -> {cross.Result}].other");
continue;
}
if (!dimMap.TryGetValue(cross.Result, out PhysicalDimension? resultDim))
{
ReportUnknownReference(context, dim.Name, cross.Result, $"crossProducts[{cross.Other} -> {cross.Result}].result");
continue;
}
string? selfV3 = GetBaseTypeName(dim, 3);
string? otherV3 = GetBaseTypeName(otherDim, 3);
string? resultV3 = GetBaseTypeName(resultDim, 3);
if (selfV3 == null || otherV3 == null || resultV3 == null)
{
continue;
}
string key = $"Cross:{selfV3}:{otherV3}:{resultV3}";
if (seen.Add(key))
{
result.Add(new ProductInfo("Cross", selfV3, otherV3, resultV3, 3));
}
}
}
return result;
}
private static void AddOp(List<OperatorInfo> list, HashSet<string> seen, string op, string left, string right, string ret, string owner)
{
// Skip self-division (base class already handles TSelf / TSelf => TStorage)
if (op == "/" && left == right)
{
return;
}
string key = $"{op}:{left}:{right}:{ret}";
if (seen.Add(key))
{
list.Add(new OperatorInfo(op, left, right, ret, owner));
}
}
private static void ReportUnknownReference(SourceProductionContext context, string owningDimension, string unknownReference, string fieldPath)
{
context.ReportDiagnostic(Diagnostic.Create(
UnknownDimensionReference,
Location.None,
owningDimension,
unknownReference,
fieldPath));
}
private static Dictionary<string, List<T>> GroupBy<T>(List<T> items, Func<T, string> keySelector)
{
Dictionary<string, List<T>> groups = [];
foreach (T item in items)
{
string key = keySelector(item);
if (!groups.TryGetValue(key, out List<T>? group))
{
group = [];
groups[key] = group;
}
group.Add(item);
}
return groups;
}
#endregion
#region Phase B: Type Generation
private void EmitV0BaseType(
SourceProductionContext context,
PhysicalDimension dim,
Dictionary<string, List<OperatorInfo>> operatorsByOwner,
Dictionary<string, int> typeFormMap)
{
VectorFormDefinition v0 = dim.Quantities.Vector0!;
string typeName = v0.Base;
string fullType = $"{typeName}<T>";
string? v1TypeName = dim.Quantities.Vector1?.Base;
using CodeBlocker cb = CodeBlocker.Create();
SourceFileTemplate sourceFile = new()
{
FileName = $"{typeName}.g.cs",
Namespace = "ktsu.Semantics.Quantities",
Usings = ["System.Numerics"],
};
ClassTemplate cls = new()
{
Comments =
[
"/// <summary>",
$"/// Magnitude (Vector0) quantity for the {dim.Name} dimension.",
"/// </summary>",
"/// <typeparam name=\"T\">The numeric storage type.</typeparam>",
],
Keywords = ["public", "record"],
Name = fullType,
BaseClass = $"PhysicalQuantity<{fullType}, T>",
Interfaces = [$"IVector0<{fullType}, T>"],
Constraints = ["where T : struct, INumber<T>"],
};
// Zero property (satisfies IVector0)
cls.Members.Add(new FieldTemplate()
{
Comments = ["/// <summary>Gets a quantity with value zero.</summary>"],
Keywords = ["public", "static", fullType],
Name = "Zero => Create(T.Zero)",
});
// Factory methods from available units
if (dim.AvailableUnits.Count > 0)
{
string firstUnit = dim.AvailableUnits[0];
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// Creates a new <see cref=\"{typeName}{{T}}\"/> from a value in {firstUnit}.",
"/// </summary>",
$"/// <param name=\"value\">The value in {firstUnit}.</param>",
$"/// <returns>A new <see cref=\"{typeName}{{T}}\"/> instance.</returns>",
],
Keywords = ["public", "static", fullType],
Name = $"From{firstUnit}",
Parameters = [new ParameterTemplate { Type = "T", Name = "value" }],
BodyFactory = (body) => body.Write(" => Create(value);"),
});
}
// V0 subtraction hiding: returns V1 if V1 exists for this dimension
if (v1TypeName != null)
{
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// Subtracts two {typeName} values, returning a signed {v1TypeName} result.",
"/// </summary>",
],
Attributes = ["System.Diagnostics.CodeAnalysis.SuppressMessage(\"Usage\", \"CA2225:Operator overloads have named alternates\", Justification = \"Physics quantity operator\")"],
Keywords = ["public", "static", $"{v1TypeName}<T>"],
Name = "operator -",
Parameters =
[
new ParameterTemplate { Type = fullType, Name = "left" },
new ParameterTemplate { Type = fullType, Name = "right" },
],
BodyFactory = (body) => body.Write($" => {v1TypeName}<T>.Create(left.Quantity - right.Quantity);"),
});
}
// Cross-dimensional operators
EmitScalarOperators(cls, typeName, operatorsByOwner, typeFormMap);
sourceFile.Classes.Add(cls);
WriteSourceFileTo(cb, sourceFile);
context.AddSource(sourceFile.FileName, cb.ToString());
}
private void EmitV1BaseType(
SourceProductionContext context,
PhysicalDimension dim,
Dictionary<string, List<OperatorInfo>> operatorsByOwner,
Dictionary<string, int> typeFormMap)
{
VectorFormDefinition v1 = dim.Quantities.Vector1!;
string typeName = v1.Base;
string fullType = $"{typeName}<T>";
string? v0TypeName = dim.Quantities.Vector0?.Base;
using CodeBlocker cb = CodeBlocker.Create();
SourceFileTemplate sourceFile = new()
{
FileName = $"{typeName}.g.cs",
Namespace = "ktsu.Semantics.Quantities",
Usings = ["System.Numerics"],
};
ClassTemplate cls = new()
{
Comments =
[
"/// <summary>",
$"/// Signed one-dimensional (Vector1) quantity for the {dim.Name} dimension.",
"/// </summary>",
"/// <typeparam name=\"T\">The numeric storage type.</typeparam>",
],
Keywords = ["public", "record"],
Name = fullType,
BaseClass = $"PhysicalQuantity<{fullType}, T>",
Interfaces = [$"IVector1<{fullType}, T>"],
Constraints = ["where T : struct, INumber<T>"],
};
// Zero property (satisfies IVector1)
cls.Members.Add(new FieldTemplate()
{
Comments = ["/// <summary>Gets a quantity with value zero.</summary>"],
Keywords = ["public", "static", fullType],
Name = "Zero => Create(T.Zero)",
});
// Factory methods
if (dim.AvailableUnits.Count > 0)
{
string firstUnit = dim.AvailableUnits[0];
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// Creates a new <see cref=\"{typeName}{{T}}\"/> from a value in {firstUnit}.",
"/// </summary>",
$"/// <param name=\"value\">The value in {firstUnit}.</param>",
$"/// <returns>A new <see cref=\"{typeName}{{T}}\"/> instance.</returns>",
],
Keywords = ["public", "static", fullType],
Name = $"From{firstUnit}",
Parameters = [new ParameterTemplate { Type = "T", Name = "value" }],
BodyFactory = (body) => body.Write(" => Create(value);"),
});
}
// Magnitude method returning V0 base
if (v0TypeName != null)
{
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// Gets the magnitude of this quantity as a <see cref=\"{v0TypeName}{{T}}\"/>.",
"/// </summary>",
$"/// <returns>The non-negative magnitude.</returns>",
],
Keywords = ["public", $"{v0TypeName}<T>"],
Name = "Magnitude",
Parameters = [],
BodyFactory = (body) => body.Write($" => {v0TypeName}<T>.Create(T.Abs(Value));"),
});
}
// Cross-dimensional operators
EmitScalarOperators(cls, typeName, operatorsByOwner, typeFormMap);
sourceFile.Classes.Add(cls);
WriteSourceFileTo(cb, sourceFile);
context.AddSource(sourceFile.FileName, cb.ToString());
}
private void EmitVectorType(
SourceProductionContext context,
PhysicalDimension dim,
int dims,
VectorFormDefinition form,
Dictionary<string, List<OperatorInfo>> operatorsByOwner,
Dictionary<string, List<ProductInfo>> productsByOwner,
Dictionary<string, int> typeFormMap)
{
string[] components = dims switch
{
2 => ["X", "Y"],
3 => ["X", "Y", "Z"],
4 => ["X", "Y", "Z", "W"],
_ => throw new ArgumentOutOfRangeException(nameof(dims)),
};
string typeName = form.Base;
string fullType = $"{typeName}<T>";
string interfaceName = $"IVector{dims}<{fullType}, T>";
string? v0TypeName = dim.Quantities.Vector0?.Base;
using CodeBlocker cb = CodeBlocker.Create();
WriteHeaderTo(cb);
cb.WriteLine("#pragma warning disable IDE0040 // Accessibility modifiers required");
cb.WriteLine("#pragma warning disable CA2225 // Operator overloads have named alternates");
cb.NewLine();
cb.WriteLine("namespace ktsu.Semantics.Quantities;");
cb.NewLine();
cb.WriteLine("using System;");
cb.WriteLine("using System.Numerics;");
cb.NewLine();
cb.WriteLine("/// <summary>");
cb.WriteLine($"/// {dims}D vector representation of {dim.Name}.");
cb.WriteLine("/// </summary>");
cb.WriteLine("/// <typeparam name=\"T\">The numeric component type.</typeparam>");
cb.WriteLine($"public record {fullType} : {interfaceName}");
cb.WriteLine("\twhere T : struct, INumber<T>");
using (new ScopeWithTrailingSemicolon(cb))
{
WriteVectorComponentProperties(cb, components);
WriteVectorStaticProperties(cb, fullType, components);
// Typed Magnitude() method returning V0 base
if (v0TypeName != null)
{
cb.WriteLine($"/// <summary>Gets the magnitude as a <see cref=\"{v0TypeName}{{T}}\"/>.</summary>");
cb.WriteLine($"public {v0TypeName}<T> Magnitude() => {v0TypeName}<T>.Create(Length());");
cb.NewLine();
}
WriteVectorMethods(cb, fullType, components, dims);
WriteVectorOperators(cb, fullType, components);
// Cross-dimensional operators (inlined for VN types)
EmitVectorCrossDimOperators(cb, typeName, fullType, components, operatorsByOwner, typeFormMap);
// Typed dot product methods
if (productsByOwner.TryGetValue(typeName, out List<ProductInfo>? products))
{
foreach (ProductInfo prod in products)
{
if (prod.Method == "Dot")
{
string dotExpr = string.Join(" + ", components.Select(c => $"({c} * other.{c})"));
cb.WriteLine($"/// <summary>Typed dot product: {typeName} . {prod.OtherTypeName} = {prod.ReturnTypeName}.</summary>");
cb.WriteLine($"public {prod.ReturnTypeName}<T> Dot({prod.OtherTypeName}<T> other) => {prod.ReturnTypeName}<T>.Create({dotExpr});");
cb.NewLine();
}
else if (prod.Method == "Cross" && dims == 3)
{
cb.WriteLine($"/// <summary>Typed cross product: {typeName} x {prod.OtherTypeName} = {prod.ReturnTypeName}.</summary>");
cb.WriteLine($"public {prod.ReturnTypeName}<T> Cross({prod.OtherTypeName}<T> other)");
using (new Scope(cb))
{
cb.WriteLine($"return new() {{ X = (Y * other.Z) - (Z * other.Y), Y = (Z * other.X) - (X * other.Z), Z = (X * other.Y) - (Y * other.X) }};");
}
cb.NewLine();
}
}
}
}
context.AddSource($"{typeName}.g.cs", cb.ToString());
}
private void EmitOverloadType(
SourceProductionContext context,
PhysicalDimension dim,
int vectorForm,
string baseTypeName,
OverloadDefinition overload,
Dictionary<string, int> typeFormMap)
{
string typeName = overload.Name;
string fullType = $"{typeName}<T>";
string baseFullType = $"{baseTypeName}<T>";
string? v1TypeName = dim.Quantities.Vector1?.Base;
// V0/V1 overloads inherit from PhysicalQuantity
if (vectorForm <= 1)
{
using CodeBlocker cb = CodeBlocker.Create();
string interfaceName = vectorForm == 0 ? $"IVector0<{fullType}, T>" : $"IVector1<{fullType}, T>";
SourceFileTemplate sourceFile = new()
{
FileName = $"{typeName}.g.cs",
Namespace = "ktsu.Semantics.Quantities",
Usings = ["System.Numerics"],
};
ClassTemplate cls = new()
{
Comments =
[
"/// <summary>",
$"/// {overload.Description}",
$"/// Semantic overload of <see cref=\"{baseTypeName}{{T}}\"/>.",
"/// </summary>",
"/// <typeparam name=\"T\">The numeric storage type.</typeparam>",
],
Keywords = ["public", "record"],
Name = fullType,
BaseClass = $"PhysicalQuantity<{fullType}, T>",
Interfaces = [interfaceName],
Constraints = ["where T : struct, INumber<T>"],
};
// Zero property
cls.Members.Add(new FieldTemplate()
{
Comments = ["/// <summary>Gets a quantity with value zero.</summary>"],
Keywords = ["public", "static", fullType],
Name = "Zero => Create(T.Zero)",
});
// Factory methods
if (dim.AvailableUnits.Count > 0)
{
string firstUnit = dim.AvailableUnits[0];
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Creates a new {typeName} from a value in {firstUnit}.</summary>"],
Keywords = ["public", "static", fullType],
Name = $"From{firstUnit}",
Parameters = [new ParameterTemplate { Type = "T", Name = "value" }],
BodyFactory = (body) => body.Write(" => Create(value);"),
});
}
// Implicit widening to base type
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Implicit conversion to {baseTypeName}.</summary>"],
Keywords = ["public", "static", "implicit", "operator"],
Name = baseFullType,
Parameters = [new ParameterTemplate { Type = fullType, Name = "value" }],
BodyFactory = (body) => body.Write($" => {baseFullType}.Create(value.Value);"),
});
// Explicit narrowing from base type
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Explicit conversion from {baseTypeName}.</summary>"],
Keywords = ["public", "static", "explicit", "operator"],
Name = fullType,
Parameters = [new ParameterTemplate { Type = baseFullType, Name = "value" }],
BodyFactory = (body) => body.Write($" => Create(value.Value);"),
});
// Factory-style narrowing from base
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Creates a {typeName} from a {baseTypeName} value.</summary>"],
Keywords = ["public", "static", fullType],
Name = "From",
Parameters = [new ParameterTemplate { Type = baseFullType, Name = "value" }],
BodyFactory = (body) => body.Write(" => Create(value.Value);"),
});
// V0 overload subtraction hiding (returns V1 base if exists)
if (vectorForm == 0 && v1TypeName != null)
{
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Subtracts two {typeName} values, returning a signed {v1TypeName} result.</summary>"],
Attributes = ["System.Diagnostics.CodeAnalysis.SuppressMessage(\"Usage\", \"CA2225:Operator overloads have named alternates\", Justification = \"Physics quantity operator\")"],
Keywords = ["public", "static", $"{v1TypeName}<T>"],
Name = "operator -",
Parameters =
[
new ParameterTemplate { Type = fullType, Name = "left" },
new ParameterTemplate { Type = fullType, Name = "right" },
],
BodyFactory = (body) => body.Write($" => {v1TypeName}<T>.Create(left.Quantity - right.Quantity);"),
});
}
// Relationship methods (e.g., Diameter.ToRadius(), Diameter.FromRadius())
foreach (KeyValuePair<string, string> rel in overload.Relationships)
{
// rel.Key is like "toRadius" or "fromRadius", rel.Value is the C# expression
string methodName = char.ToUpperInvariant(rel.Key[0]) + rel.Key.Substring(1);
if (methodName.StartsWith("To", StringComparison.Ordinal))
{
// Instance method: e.g., ToRadius() returns Radius<T>
string targetName = methodName.Substring(2);
string targetType = $"{targetName}<T>";
string expr = rel.Value; // uses "Value" referring to this instance
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Converts this {typeName} to a {targetName}.</summary>"],
Keywords = ["public", targetType],
Name = methodName,
Parameters = [],
BodyFactory = (body) => body.Write($" => {targetType}.Create({expr});"),
});
}
else if (methodName.StartsWith("From", StringComparison.Ordinal))
{
// Static factory: e.g., FromRadius(Radius<T> value) returns this type
string sourceName = methodName.Substring(4);
string sourceType = $"{sourceName}<T>";
// Replace "Value" with "source.Value" since this is a static method
string expr = rel.Value.Replace("Value", "source.Value");
cls.Members.Add(new MethodTemplate()
{
Comments = [$"/// <summary>Creates a {typeName} from a {sourceName} value.</summary>"],
Keywords = ["public", "static", fullType],
Name = methodName,
Parameters = [new ParameterTemplate { Type = sourceType, Name = "source" }],
BodyFactory = (body) => body.Write($" => Create({expr});"),
});
}
}
sourceFile.Classes.Add(cls);
WriteSourceFileTo(cb, sourceFile);
context.AddSource(sourceFile.FileName, cb.ToString());
}
else
{
// V2/3/4 overloads: these are more complex, generate as standalone records
// For now, V2+ overloads are rare and can be added later
// The strategy document shows them mainly for V3 (Position3D, Translation3D)
EmitVectorOverloadType(context, dim, vectorForm, baseTypeName, overload);
}
}
private void EmitVectorOverloadType(
SourceProductionContext context,
PhysicalDimension dim,
int dims,
string baseTypeName,
OverloadDefinition overload)
{
string[] components = dims switch
{
2 => ["X", "Y"],
3 => ["X", "Y", "Z"],
4 => ["X", "Y", "Z", "W"],
_ => throw new ArgumentOutOfRangeException(nameof(dims)),
};
string typeName = overload.Name;
string fullType = $"{typeName}<T>";
string baseFullType = $"{baseTypeName}<T>";
string interfaceName = $"IVector{dims}<{fullType}, T>";
using CodeBlocker cb = CodeBlocker.Create();
WriteHeaderTo(cb);
cb.WriteLine("#pragma warning disable IDE0040 // Accessibility modifiers required");
cb.WriteLine("#pragma warning disable CA2225 // Operator overloads have named alternates");
cb.NewLine();
cb.WriteLine("namespace ktsu.Semantics.Quantities;");
cb.NewLine();
cb.WriteLine("using System;");
cb.WriteLine("using System.Numerics;");
cb.NewLine();
cb.WriteLine("/// <summary>");
cb.WriteLine($"/// {overload.Description}");
cb.WriteLine($"/// Semantic overload of <see cref=\"{baseTypeName}{{T}}\"/>.");
cb.WriteLine("/// </summary>");
cb.WriteLine($"public record {fullType} : {interfaceName}");
cb.WriteLine("\twhere T : struct, INumber<T>");
using (new ScopeWithTrailingSemicolon(cb))
{
WriteVectorComponentProperties(cb, components);
WriteVectorStaticProperties(cb, fullType, components);
WriteVectorMethods(cb, fullType, components, dims);
WriteVectorOperators(cb, fullType, components);
// Implicit widening to base
string baseInit = string.Join(", ", components.Select(c => $"{c} = value.{c}"));
cb.WriteLine($"/// <summary>Implicit conversion to {baseTypeName}.</summary>");
cb.WriteLine($"public static implicit operator {baseFullType}({fullType} value) => new() {{ {baseInit} }};");
cb.NewLine();
// Explicit narrowing from base
cb.WriteLine($"/// <summary>Explicit conversion from {baseTypeName}.</summary>");
cb.WriteLine($"public static explicit operator {fullType}({baseFullType} value) => new() {{ {baseInit} }};");
cb.NewLine();
}
context.AddSource($"{typeName}.g.cs", cb.ToString());
}
#endregion
#region Operator Emission Helpers
private static void EmitScalarOperators(
ClassTemplate cls,
string ownerTypeName,
Dictionary<string, List<OperatorInfo>> operatorsByOwner,
Dictionary<string, int> typeFormMap)
{
if (!operatorsByOwner.TryGetValue(ownerTypeName, out List<OperatorInfo>? ops))
{
return;
}
foreach (OperatorInfo op in ops)
{
int leftForm = GetFormOrDefault(typeFormMap, op.LeftTypeName);
int rightForm = GetFormOrDefault(typeFormMap, op.RightTypeName);
// For V0/V1 owner types, use Multiply/Divide helpers when both operands are V0/V1
if (leftForm <= 1 && rightForm <= 1)
{
string helperName = op.Op == "*" ? "Multiply" : "Divide";
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// {(op.Op == "*" ? "Multiplies" : "Divides")} {op.LeftTypeName} {(op.Op == "*" ? "by" : "by")} {op.RightTypeName} to produce {op.ReturnTypeName}.",
"/// </summary>",
],
Attributes = ["System.Diagnostics.CodeAnalysis.SuppressMessage(\"Usage\", \"CA2225:Operator overloads have named alternates\", Justification = \"Physics quantity operator\")"],
Keywords = ["public", "static", $"{op.ReturnTypeName}<T>"],
Name = $"operator {op.Op}",
Parameters =
[
new ParameterTemplate { Type = $"{op.LeftTypeName}<T>", Name = "left" },
new ParameterTemplate { Type = $"{op.RightTypeName}<T>", Name = "right" },
],
BodyFactory = (body) => body.Write($" => {helperName}<{op.ReturnTypeName}<T>>(left, right);"),
});
}
else
{
// One operand is V2+ (VN type, multi-component)
// The owner is V0/V1, the other operand is VN
// Generate inline: left.Value {op} right.X, etc. OR left.X {op} right.Value, etc.
EmitInlineCrossDimOp(cls, op, typeFormMap);
}
}
}
private static void EmitInlineCrossDimOp(
ClassTemplate cls,
OperatorInfo op,
Dictionary<string, int> typeFormMap)
{
int leftForm = GetFormOrDefault(typeFormMap, op.LeftTypeName);
int rightForm = GetFormOrDefault(typeFormMap, op.RightTypeName);
int resultForm = GetFormOrDefault(typeFormMap, op.ReturnTypeName);
string[] resultComponents = resultForm switch
{
2 => ["X", "Y"],
3 => ["X", "Y", "Z"],
4 => ["X", "Y", "Z", "W"],
_ => [],
};
if (resultComponents.Length == 0)
{
return;
}
string bodyExpr;
if (leftForm >= 2 && rightForm <= 1)
{
// VN op V0: component-wise with right.Value
string initExpr = string.Join(", ", resultComponents.Select(c => $"{c} = left.{c} {op.Op} right.Value"));
bodyExpr = $" => new() {{ {initExpr} }};";
}
else if (leftForm <= 1 && rightForm >= 2)
{
// V0 op VN: component-wise with left.Value
if (op.Op == "*")
{
string initExpr = string.Join(", ", resultComponents.Select(c => $"{c} = left.Value {op.Op} right.{c}"));
bodyExpr = $" => new() {{ {initExpr} }};";
}
else
{
// V0 / VN doesn't make physical sense, skip
return;
}
}
else
{
return;
}
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// {(op.Op == "*" ? "Multiplies" : "Divides")} {op.LeftTypeName} {(op.Op == "*" ? "by" : "by")} {op.RightTypeName} to produce {op.ReturnTypeName}.",
"/// </summary>",
],
Attributes = ["System.Diagnostics.CodeAnalysis.SuppressMessage(\"Usage\", \"CA2225:Operator overloads have named alternates\", Justification = \"Physics quantity operator\")"],
Keywords = ["public", "static", $"{op.ReturnTypeName}<T>"],
Name = $"operator {op.Op}",
Parameters =
[
new ParameterTemplate { Type = $"{op.LeftTypeName}<T>", Name = "left" },
new ParameterTemplate { Type = $"{op.RightTypeName}<T>", Name = "right" },
],
BodyFactory = (body) => body.Write(bodyExpr),
});
}
private static void EmitVectorCrossDimOperators(
CodeBlocker cb,
string ownerTypeName,
string ownerFullType,
string[] components,
Dictionary<string, List<OperatorInfo>> operatorsByOwner,
Dictionary<string, int> typeFormMap)
{
if (!operatorsByOwner.TryGetValue(ownerTypeName, out List<OperatorInfo>? ops))
{
return;
}
foreach (OperatorInfo op in ops)
{
int leftForm = GetFormOrDefault(typeFormMap, op.LeftTypeName);
int rightForm = GetFormOrDefault(typeFormMap, op.RightTypeName);
int resultForm = GetFormOrDefault(typeFormMap, op.ReturnTypeName);
string[] resultComponents = resultForm switch
{
2 => ["X", "Y"],
3 => ["X", "Y", "Z"],
4 => ["X", "Y", "Z", "W"],