-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQuantitiesGenerator.cs
More file actions
1544 lines (1356 loc) · 51.4 KB
/
QuantitiesGenerator.cs
File metadata and controls
1544 lines (1356 loc) · 51.4 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 System.Text.Json;
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);
private static readonly DiagnosticDescriptor MetadataValidationFailed = new(
id: "SEM002",
title: "dimensions.json metadata validation failed",
messageFormat: "dimensions.json validation issue: {0}",
category: "Semantics.SourceGenerators",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
private static readonly DiagnosticDescriptor RelationshipFormMissing = new(
id: "SEM003",
title: "Relationship requires a vector form not declared on a participating dimension",
messageFormat: "Relationship in dimension '{0}' ({1}) explicitly requests form V{2}, but '{3}' does not declare that form. The operator will not be generated.",
category: "Semantics.SourceGenerators",
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true);
public QuantitiesGenerator() : base("dimensions.json") { }
/// <summary>
/// Holds the metadata that drives quantity emission. Combined from dimensions.json and
/// units.json so factory methods can apply per-unit conversion factors. Plain class
/// (not a positional record) because the netstandard2.0 source-generator target lacks
/// <c>System.Runtime.CompilerServices.IsExternalInit</c>.
/// </summary>
private sealed class CombinedMetadata
{
public DimensionsMetadata Dimensions { get; }
public UnitsMetadata Units { get; }
public CombinedMetadata(DimensionsMetadata dimensions, UnitsMetadata units)
{
Dimensions = dimensions;
Units = units;
}
}
/// <summary>
/// Override to load both dimensions.json and units.json. The base class only loads a single
/// metadata file; we need both because per-unit conversion factors are required to emit
/// <c>From{Unit}</c> factories that aren't the SI base unit.
/// </summary>
public override void Initialize(IncrementalGeneratorInitializationContext context)
{
IncrementalValueProvider<DimensionsMetadata?> dimensionsProvider = LoadJson<DimensionsMetadata>(context, "dimensions.json");
IncrementalValueProvider<UnitsMetadata?> unitsProvider = LoadJson<UnitsMetadata>(context, "units.json");
IncrementalValueProvider<CombinedMetadata?> combined = dimensionsProvider.Combine(unitsProvider).Select(static (pair, _) =>
pair.Left == null ? null : new CombinedMetadata(pair.Left, pair.Right ?? new UnitsMetadata()));
context.RegisterSourceOutput(combined, (ctx, metadata) =>
{
if (metadata == null)
{
return;
}
using CodeBlocker codeBlocker = CodeBlocker.Create();
GenerateInner(ctx, metadata.Dimensions, metadata.Units, codeBlocker);
});
}
private static IncrementalValueProvider<TMeta?> LoadJson<TMeta>(IncrementalGeneratorInitializationContext context, string filename)
where TMeta : class
{
return context.AdditionalTextsProvider
.Where(file => file.Path.EndsWith(filename, StringComparison.InvariantCulture))
.Select((file, ct) => file.GetText(ct)?.ToString() ?? "")
.Where(content => !string.IsNullOrEmpty(content))
.Select((content, _) =>
{
try
{
return JsonSerializer.Deserialize<TMeta>(content, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
}
catch (JsonException)
{
return null;
}
})
.Where(m => m != null)
.Collect()
.Select((arr, _) => arr.FirstOrDefault());
}
/// <summary>
/// The legacy abstract <see cref="GeneratorBase{T}.Generate"/> entry point is unused: the
/// overridden <see cref="Initialize"/> handles registration and calls
/// <see cref="GenerateInner"/> directly. This shim exists to satisfy the abstract contract.
/// </summary>
protected override void Generate(SourceProductionContext context, DimensionsMetadata metadata, CodeBlocker codeBlocker)
=> GenerateInner(context, metadata, new UnitsMetadata(), codeBlocker);
private void GenerateInner(SourceProductionContext context, DimensionsMetadata metadata, UnitsMetadata units, CodeBlocker codeBlocker)
{
if (metadata.PhysicalDimensions == null || metadata.PhysicalDimensions.Count == 0)
{
return;
}
// Issue #60: surface schema-level metadata problems as diagnostics so they
// show up in the build log instead of crashing mid-emit.
List<string> validationIssues = metadata.Validate();
foreach (string issue in validationIssues)
{
context.ReportDiagnostic(Diagnostic.Create(
MetadataValidationFailed,
Location.None,
issue));
}
Dictionary<string, UnitDefinition> unitMap = BuildUnitMap(units);
// 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, unitMap);
}
if (dim.Quantities.Vector1 != null)
{
EmitV1BaseType(context, dim, operatorsByOwner, typeFormMap, unitMap);
}
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, unitMap);
}
}
}
}
}
#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;
}
// For integrals the "Other" multiplier is V0 only; the form propagates
// between Self and Result, so SEM003 should fire if either Self or
// Result is missing a declared form. (V0-only Other was already
// rejected above via the v0Other null check.)
int[] forms = ResolveForms(
context,
integral,
[0, 1, 2, 3, 4],
dim,
resultDim,
$"integrals[{integral.Other} -> {integral.Result}]");
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 = ResolveForms(
context,
derivative,
[0, 1, 2, 3, 4],
dim,
resultDim,
$"derivatives[{derivative.Other} -> {derivative.Result}]");
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 is undefined for V0; default forms are V1+.
int[] forms = ResolveForms(
context,
dot,
[1, 2, 3, 4],
dim,
otherDim,
$"dotProducts[{dot.Other} -> {dot.Result}]");
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;
}
// Cross product is intrinsically 3D. Default to V3 only; explicit Forms
// other than [3] are accepted but the operator emit below only handles V3.
// Pass resultDim so SEM003 surfaces when the declared form is missing on
// the result type too (e.g. Force × Length → Torque at V2: Torque has no V2).
int[] forms = ResolveForms(
context,
cross,
[3],
dim,
otherDim,
$"crossProducts[{cross.Other} -> {cross.Result}]",
resultDim);
if (Array.IndexOf(forms, 3) < 0)
{
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));
}
/// <summary>
/// Resolves the forms at which a relationship should emit operators. When the metadata
/// declares <see cref="RelationshipDefinition.Forms"/> explicitly, that list wins and
/// any form missing from one of the participating dimensions is reported as
/// <c>SEM003</c>. When the list is empty, returns <paramref name="defaultForms"/>
/// (which the caller filters silently — preserving the legacy behaviour for relationships
/// that haven't opted into form-specific declarations).
/// </summary>
private static int[] ResolveForms(
SourceProductionContext context,
RelationshipDefinition rel,
int[] defaultForms,
PhysicalDimension dim,
PhysicalDimension otherDim,
string fieldPath,
PhysicalDimension? resultDim = null)
{
if (rel.Forms.Count == 0)
{
return defaultForms;
}
List<int> kept = [];
foreach (int form in rel.Forms)
{
if (form < 0 || form > 4)
{
continue;
}
if (GetBaseTypeName(dim, form) == null)
{
ReportFormMissing(context, dim.Name, fieldPath, form, dim.Name);
continue;
}
if (GetBaseTypeName(otherDim, form) == null)
{
ReportFormMissing(context, dim.Name, fieldPath, form, otherDim.Name);
continue;
}
if (resultDim != null && GetBaseTypeName(resultDim, form) == null)
{
ReportFormMissing(context, dim.Name, fieldPath, form, resultDim.Name);
continue;
}
kept.Add(form);
}
return [.. kept];
}
private static void ReportFormMissing(SourceProductionContext context, string owningDimension, string fieldPath, int form, string offendingDimension)
{
context.ReportDiagnostic(Diagnostic.Create(
RelationshipFormMissing,
Location.None,
owningDimension,
fieldPath,
form,
offendingDimension));
}
private static Dictionary<string, UnitDefinition> BuildUnitMap(UnitsMetadata units)
{
Dictionary<string, UnitDefinition> map = [];
if (units.UnitCategories == null)
{
return map;
}
foreach (UnitCategory cat in units.UnitCategories)
{
foreach (UnitDefinition unit in cat.Units)
{
map[unit.Name] = unit;
}
}
return map;
}
/// <summary>
/// Emits one <c>From{Unit}</c> static factory per entry in <paramref name="availableUnits"/>.
/// The first unit is treated as the SI base unit (no conversion). Subsequent units use the
/// conversion factor / magnitude / offset declared in <paramref name="unitMap"/>.
/// When <paramref name="applyV0Guard"/> is true, the converted value is wrapped with
/// <c>Vector0Guards.EnsureNonNegative</c> so a negative input — including one that becomes
/// negative after a unit conversion (e.g. <c>FromCelsius(-300)</c>) — throws
/// <see cref="System.ArgumentException"/>. This locks in the V0 non-negativity invariant
/// from #50 across every per-unit factory introduced for #48.
/// </summary>
private static void AddUnitFactories(
ClassTemplate cls,
List<string> availableUnits,
Dictionary<string, UnitDefinition> unitMap,
string typeName,
string fullType,
string crefForComment,
bool applyV0Guard)
{
if (availableUnits == null || availableUnits.Count == 0)
{
return;
}
string baseUnit = availableUnits[0];
foreach (string unitName in availableUnits)
{
bool isBase = unitName == baseUnit;
string conversionExpr = isBase
? "value"
: BuildToBaseExpression(unitName, unitMap);
string body = applyV0Guard
? $" => Create(Vector0Guards.EnsureNonNegative({conversionExpr}, nameof(value)));"
: $" => Create({conversionExpr});";
// Issue #49: factory names use the plural form. Prefer an explicit FactoryName from
// units.json (covers irregular plurals like Foot→Feet, mass nouns like Hertz, and
// already-plural compounds like MetersPerSecond). Fall back to "{Name}s" for units
// that haven't been migrated yet — wrong for those edge cases but produces a build
// rather than a hard failure.
string factorySuffix = unitMap.TryGetValue(unitName, out UnitDefinition? unitDef)
&& !string.IsNullOrEmpty(unitDef?.FactoryName)
? unitDef!.FactoryName
: unitName + "s";
List<string> comments =
[
"/// <summary>",
$"/// Creates a new {crefForComment} from a value in {unitName}.",
"/// </summary>",
$"/// <param name=\"value\">The value in {unitName}.</param>",
$"/// <returns>A new {crefForComment} instance.</returns>",
];
if (applyV0Guard)
{
comments.Add("/// <exception cref=\"System.ArgumentException\">Thrown when the resulting magnitude would be negative.</exception>");
}
cls.Members.Add(new MethodTemplate()
{
Comments = comments,
Keywords = ["public", "static", fullType],
Name = $"From{factorySuffix}",
Parameters = [new ParameterTemplate { Type = "T", Name = "value" }],
BodyFactory = (b) => b.Write(body),
});
}
}
/// <summary>
/// Builds the C# expression converting <c>value</c> in <paramref name="unitName"/> to the SI
/// base unit. Honours magnitude (<c>Kilo</c>, <c>Centi</c>, …), conversionFactor (lookup in
/// <see cref="ConversionConstants"/>), and offset (additive, after scaling).
/// </summary>
private static string BuildToBaseExpression(string unitName, Dictionary<string, UnitDefinition> unitMap)
{
// If we don't have unit metadata, fall back to identity. The dimensions.json author is
// responsible for keeping availableUnits in sync with units.json; if a unit is missing,
// the emitted factory passes the value through unchanged so the build still succeeds.
// (A future SEM00x diagnostic could surface this gap.)
if (!unitMap.TryGetValue(unitName, out UnitDefinition? unit) || unit == null)
{
return "value";
}
string scaled = "value";
bool hasMagnitude = !string.IsNullOrEmpty(unit.Magnitude) && unit.Magnitude != "1";
bool hasFactor = !string.IsNullOrEmpty(unit.ConversionFactor) && unit.ConversionFactor != "1";
if (hasMagnitude)
{
scaled = $"(value * T.CreateChecked(MetricMagnitudes.{unit.Magnitude}))";
}
else if (hasFactor)
{
scaled = $"(value * T.CreateChecked(Units.ConversionConstants.{unit.ConversionFactor}))";
}
bool hasOffset = !string.IsNullOrEmpty(unit.Offset) && unit.Offset != "0";
if (hasOffset)
{
scaled = $"({scaled} + T.CreateChecked(Units.ConversionConstants.{unit.Offset}))";
}
return scaled;
}
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,
Dictionary<string, UnitDefinition> unitMap)
{
VectorFormDefinition v0 = dim.Quantities.Vector0!;
string typeName = v0.Base;
string fullType = $"{typeName}<T>";
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 for every available unit (#48). The V0 non-negativity invariant from
// #50 is enforced by AddUnitFactories — for non-base units the guard runs *after* the
// conversion, so an input that is non-negative in its source unit but negative in the
// SI base unit (e.g. -300 °C → -26.85 K) still throws.
AddUnitFactories(
cls,
dim.AvailableUnits,
unitMap,
typeName,
fullType,
"<see cref=\"" + typeName + "{T}\"/>",
applyV0Guard: true);
// V0 - V0 returns the same V0 of T.Abs(left - right) (locked decision in #52).
// We emit this on every V0 base type so the derived operator wins overload resolution
// over PhysicalQuantity's plain subtraction (which can produce a negative magnitude
// and would trip the non-negativity guard from #50).
cls.Members.Add(new MethodTemplate()
{
Comments =
[
"/// <summary>",
$"/// Subtracts two {typeName} values, returning the absolute difference as a non-negative {typeName}.",
"/// Magnitude subtraction stays a magnitude (per the unified-vector model).",
"/// </summary>",
],
Attributes = ["System.Diagnostics.CodeAnalysis.SuppressMessage(\"Usage\", \"CA2225:Operator overloads have named alternates\", Justification = \"Physics quantity operator\")"],
Keywords = ["public", "static", fullType],
Name = "operator -",
Parameters =
[
new ParameterTemplate { Type = fullType, Name = "left" },
new ParameterTemplate { Type = fullType, Name = "right" },
],
BodyFactory = (body) => body.Write(" => Create(T.Abs(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,
Dictionary<string, UnitDefinition> unitMap)
{
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 for every available unit.
// V1 quantities are signed; no V0 non-negativity guard.
AddUnitFactories(
cls,
dim.AvailableUnits,
unitMap,
typeName,
fullType,
"<see cref=\"" + typeName + "{T}\"/>",
applyV0Guard: false);
// 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,
Dictionary<string, UnitDefinition> unitMap)
{
string typeName = overload.Name;
string fullType = $"{typeName}<T>";
string baseFullType = $"{baseTypeName}<T>";
// 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 for every available unit (#48); overloads inherit the dimension's
// units. V0 overloads enforce the same non-negativity invariant as their V0 base
// type (#50); V1 overloads accept any sign.