Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Redesign UnitSystem to support non-SI systems and configurable default units #709

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
38 changes: 19 additions & 19 deletions CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,23 +192,25 @@ private void GenerateInstanceConstructors()
/// <param name=""value"">The numeric value to construct this quantity with.</param>
/// <param name=""unitSystem"">The unit system to create the quantity with.</param>
/// <exception cref=""ArgumentNullException"">The given <see cref=""UnitSystem""/> is null.</exception>
/// <exception cref=""ArgumentException"">No unit was found for the given <see cref=""UnitSystem""/>.</exception>
/// <exception cref=""ArgumentException"">No default unit was found for the given <see cref=""UnitSystem""/>.</exception>
public {_quantity.Name}({_valueType} value, UnitSystem unitSystem)
{{
if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem));

var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var firstUnitInfo = unitInfos.FirstOrDefault();
");

Writer.WL(_quantity.BaseType == "double"
? @"
_value = Guard.EnsureValidNumber(value, nameof(value));"
_value = Guard.EnsureValidNumber(value, nameof(value));
"
: @"
_value = value;");
Writer.WL(@"
_unit = firstUnitInfo?.Value ?? throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem));
}
_value = value;
");

Writer.WL($@"
var defaultUnitInfo = unitSystem.GetDefaultUnitInfo(QuantityType) as UnitInfo<{_unitEnumName}>;

_unit = defaultUnitInfo?.Value ?? throw new ArgumentException(""No default unit was defined for the given UnitSystem."", nameof(unitSystem));
}}
");
}

Expand Down Expand Up @@ -838,13 +840,12 @@ public double As(UnitSystem unitSystem)
if(unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));

var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var defaultUnitInfo = unitSystem.GetDefaultUnitInfo(QuantityType) as UnitInfo<{_unitEnumName}>;

var firstUnitInfo = unitInfos.FirstOrDefault();
if(firstUnitInfo == null)
throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem));
if(defaultUnitInfo == null)
throw new ArgumentException(""No default unit was found for the given UnitSystem."", nameof(unitSystem));

return As(firstUnitInfo.Value);
return As(defaultUnitInfo.Value);
}}

/// <inheritdoc />
Expand Down Expand Up @@ -881,13 +882,12 @@ IQuantity IQuantity.ToUnit(Enum unit)
if(unitSystem is null)
throw new ArgumentNullException(nameof(unitSystem));

var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits);
var defaultUnitInfo = unitSystem.GetDefaultUnitInfo(QuantityType) as UnitInfo<{_unitEnumName}>;

var firstUnitInfo = unitInfos.FirstOrDefault();
if(firstUnitInfo == null)
throw new ArgumentException(""No units were found for the given UnitSystem."", nameof(unitSystem));
if(defaultUnitInfo == null)
throw new ArgumentException(""No default unit was found for the given UnitSystem."", nameof(unitSystem));

return ToUnit(firstUnitInfo.Value);
return ToUnit(defaultUnitInfo.Value);
}}

/// <inheritdoc />
Expand Down
103 changes: 103 additions & 0 deletions CodeGen/Generators/UnitsNetGen/UnitSystemInfoGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using System;
using System.Linq;
using CodeGen.Helpers;
using CodeGen.JsonTypes;

namespace CodeGen.Generators.UnitsNetGen
{
internal class UnitSystemInfoGenerator : GeneratorBase
{
private readonly Quantity[] _quantities;
private readonly string _unitSystemName;

public UnitSystemInfoGenerator(string unitSystemName, Quantity[] quantities)
{
_quantities = quantities;
_unitSystemName = unitSystemName;
}

public override string Generate()
{
Writer.WL(GeneratedFileHeader);
Writer.WL($@"
// ReSharper disable once CheckNamespace
namespace UnitsNet.UnitSystems
{{

public partial class {_unitSystemName}
{{
/// <summary>
/// Returns the list of unit mappings for the current unit system
/// </summary>
/// <returns>The list of unit system infos</returns>
public static UnitSystemInfo[] GetDefaultSystemUnits()
{{
return new UnitSystemInfo[]
{{");
foreach (Quantity quantity in _quantities)
{
UnitSystemMapping unitSystemMapping = quantity.UnitSystems.FirstOrDefault(x => x.UnitSystem == _unitSystemName);
if (unitSystemMapping == null)
{
var firstCommonUnitIndex = Array.FindIndex(quantity.Units, x => x.UnitSystems.Contains(_unitSystemName));

if (firstCommonUnitIndex < 0)
{
Writer.WL(4, "null,"); // no mapping for current quantity
}
else
{
Writer.WL(4, $@"new UnitSystemInfo(null, new UnitInfo[]{{");
Writer.WL(5, $@"{quantity.Name}.Info.UnitInfos[{firstCommonUnitIndex}],");
var startingIndex = firstCommonUnitIndex + 1;
while (true)
{
var nextIndex = Array.FindIndex(quantity.Units, startingIndex, x => x.UnitSystems.Contains(_unitSystemName));
if (nextIndex < 0)
{
Writer.WL(5, @"}),");
break;
}
else
{
Writer.WL(5, $@"{quantity.Name}.Info.UnitInfos[{nextIndex}],");
startingIndex = nextIndex + 1;
}
}
}
}
else
{
// find the unit index in the generated unit infos
var defaultIndex = Array.FindIndex(quantity.Units, x => x.SingularName == unitSystemMapping.BaseUnit);

Writer.WL(4, $@"new UnitSystemInfo({quantity.Name}.Info.UnitInfos[{defaultIndex}], new UnitInfo[]{{");
var startingIndex = 0;
while(true)
{
var nextIndex = Array.FindIndex(quantity.Units, startingIndex, x => x.UnitSystems.Contains(_unitSystemName));
if (nextIndex < 0)
{
Writer.WL(5, @"}),");
break;
}
else
{
Writer.WL(5, $@"{quantity.Name}.Info.UnitInfos[{nextIndex}],");
startingIndex = nextIndex + 1;
}
}
}
}

Writer.WL(@"
};
}
}
}
");

return Writer.ToString();
}
}
}
110 changes: 84 additions & 26 deletions CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using CodeGen.JsonTypes;

Expand All @@ -15,6 +16,11 @@ namespace CodeGen.Generators.UnitsNetGen
/// </example>
internal class UnitTestBaseClassGenerator : GeneratorBase
{
/// <summary>
/// The list of all unit systems that are currently supported in Units.Net.
/// </summary>
private static string[] SupportedUnitSystems = {"SI", "CGS", "BI", "EE", "USC", "FPS", "Astronomical"};

/// <summary>
/// The quantity to generate test base class for.
/// </summary>
Expand All @@ -29,6 +35,7 @@ internal class UnitTestBaseClassGenerator : GeneratorBase
/// Example: "LengthUnit"
/// </summary>
private readonly string _unitEnumName;
private readonly Dictionary<string, Unit> _unitSystemUnits = new Dictionary<string, Unit>();

/// <summary>
/// Example: " m" for Length quantity with leading whitespace or "" for Ratio quantity where base unit does not have an abbreviation.
Expand All @@ -52,6 +59,14 @@ public UnitTestBaseClassGenerator(Quantity quantity)
throw new ArgumentException($"No unit found with SingularName equal to BaseUnit [{_quantity.BaseUnit}]. This unit must be defined.",
nameof(quantity));
_unitEnumName = $"{quantity.Name}Unit";

foreach (var unitSystemMapping in quantity.UnitSystems)
{
_unitSystemUnits.Add(unitSystemMapping.UnitSystem, quantity.Units.FirstOrDefault(u => u.SingularName == unitSystemMapping.BaseUnit) ??
throw new ArgumentException($"No unit found with SingularName equal to the one defined for '{unitSystemMapping.UnitSystem}' [{unitSystemMapping.BaseUnit}]. This unit must be defined.",
nameof(quantity)));
}

_baseUnitEnglishAbbreviation = GetEnglishAbbreviation(_baseUnit);
_baseUnitFullName = $"{_unitEnumName}.{_baseUnit.SingularName}";
_numberSuffix = quantity.BaseType == "decimal" ? "m" : "";
Expand Down Expand Up @@ -145,21 +160,30 @@ public void Ctor_NullAsUnitSystem_ThrowsArgumentNullException()
}}

[Fact]
public void Ctor_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{
Func<object> TestCode = () => new {_quantity.Name}(value: 1, unitSystem: UnitSystem.SI);
if (SupportsSIUnitSystem)
{{
var quantity = ({_quantity.Name}) TestCode();
Assert.Equal(1, quantity.Value);
}}
else
{{
Assert.Throws<ArgumentException>(TestCode);
}}
public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{");
foreach (var unit in _unitSystemUnits)
{
var asQuantityVariableName = $"{unit.Key.ToLowerInvariant()}Quantity";

Writer.WL($@"
var {asQuantityVariableName} = new {_quantity.Name}(1, UnitSystem.{unit.Key});
Assert.Equal(1, (double){asQuantityVariableName}.Value);
Assert.Equal({_unitEnumName}.{unit.Value.SingularName}, {asQuantityVariableName}.Unit);");
Writer.WL();
}
foreach (var unitSystem in SupportedUnitSystems.Where(x => !_unitSystemUnits.ContainsKey(x))) Writer.WL($@"
Assert.Throws<ArgumentException>(() => new {_quantity.Name}(1, UnitSystem.{unitSystem}));");
Writer.WL($@"
}}

[Fact]
public void Ctor_WithNullUnitSystem_ThrowsArgumentNullException()
{{
Assert.Throws<ArgumentNullException>(() => new {_quantity.Name}(1, null));");
Writer.WL($@"
}}

public void {_quantity.Name}_QuantityInfo_ReturnsQuantityInfoDescribingQuantity()
{{
var quantity = new {_quantity.Name}(1, {_baseUnitFullName});
Expand Down Expand Up @@ -230,20 +254,25 @@ public void As()
}}

[Fact]
public void As_SIUnitSystem_ThrowsArgumentExceptionIfNotSupported()
public void As_UnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{
var quantity = new {_quantity.Name}(value: 1, unit: {_quantity.Name}.BaseUnit);
Func<object> AsWithSIUnitSystem = () => quantity.As(UnitSystem.SI);
var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
if(_unitSystemUnits.Any()) Writer.WL();
foreach (var unitSystem in _unitSystemUnits) Writer.WL($@"
AssertEx.EqualTolerance({unitSystem.Value.PluralName}InOne{_baseUnit.SingularName}, {baseUnitVariableName}.As(UnitSystem.{unitSystem.Key}), {unitSystem.Value.PluralName}Tolerance);");
if(_unitSystemUnits.Count < SupportedUnitSystems.Length) Writer.WL();
foreach (var unitSystem in SupportedUnitSystems.Where(x => !_unitSystemUnits.ContainsKey(x))) Writer.WL($@"
Assert.Throws<ArgumentException>(() => {baseUnitVariableName}.As(UnitSystem.{unitSystem}));");
Writer.WL($@"
}}

if (SupportsSIUnitSystem)
{{
var value = (double) AsWithSIUnitSystem();
Assert.Equal(1, value);
}}
else
{{
Assert.Throws<ArgumentException>(AsWithSIUnitSystem);
}}
[Fact]
public void As_WithNullUnitSystem_ThrowsArgumentNullException()
{{
var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
Writer.WL($@"
Assert.Throws<ArgumentNullException>(() => {baseUnitVariableName}.As(null));");
Writer.WL($@"
}}

[Fact]
Expand All @@ -254,7 +283,7 @@ public void ToUnit()
{
var asQuantityVariableName = $"{unit.SingularName.ToLowerInvariant()}Quantity";

Writer.WL("");
Writer.WL();
Writer.WL($@"
var {asQuantityVariableName} = {baseUnitVariableName}.ToUnit({GetUnitFullName(unit)});
AssertEx.EqualTolerance({unit.PluralName}InOne{_baseUnit.SingularName}, (double){asQuantityVariableName}.Value, {unit.PluralName}Tolerance);
Expand All @@ -263,6 +292,35 @@ public void ToUnit()
Writer.WL($@"
}}

[Fact]
public void To_UnitSystem_ThrowsArgumentExceptionIfNotSupported()
{{
var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
foreach (var unit in _unitSystemUnits)
{
var asQuantityVariableName = $"{unit.Key.ToLowerInvariant()}Quantity";

Writer.WL();
Writer.WL($@"
var {asQuantityVariableName} = {baseUnitVariableName}.ToUnit(UnitSystem.{unit.Key});
AssertEx.EqualTolerance({unit.Value.PluralName}InOne{_baseUnit.SingularName}, (double){asQuantityVariableName}.Value, {unit.Value.PluralName}Tolerance);
Assert.Equal({_unitEnumName}.{unit.Value.SingularName}, {asQuantityVariableName}.Unit);");
}
if(_unitSystemUnits.Count < SupportedUnitSystems.Length) Writer.WL();
foreach (var unitSystem in SupportedUnitSystems.Where(x => !_unitSystemUnits.ContainsKey(x))) Writer.WL($@"
Assert.Throws<ArgumentException>(() => {baseUnitVariableName}.ToUnit(UnitSystem.{unitSystem}));");
Writer.WL($@"
}}

[Fact]
public void ToUnit_WithNullUnitSystem_ThrowsNullException()
{{
var {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);");
Writer.WL($@"
Assert.Throws<ArgumentNullException>(() => {baseUnitVariableName}.ToUnit(null));");
Writer.WL($@"
}}

[Fact]
public void ToBaseUnit_ReturnsQuantityWithBaseUnit()
{{
Expand Down Expand Up @@ -321,7 +379,7 @@ public void ArithmeticOperators()
}
else
{
Writer.WL("");
Writer.WL();
}

Writer.WL($@"
Expand Down
16 changes: 16 additions & 0 deletions CodeGen/Generators/UnitsNetGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,11 @@ public static void Generate(string rootDir, Quantity[] quantities)
// Ensure output directories exist
Directory.CreateDirectory($"{outputDir}/Quantities");
Directory.CreateDirectory($"{outputDir}/Units");
Directory.CreateDirectory($"{outputDir}/UnitSystems");

Directory.CreateDirectory($"{extensionsOutputDir}");
Directory.CreateDirectory($"{extensionsTestOutputDir}");

Directory.CreateDirectory($"{testProjectDir}/GeneratedCode");
Directory.CreateDirectory($"{testProjectDir}/GeneratedCode/TestsBase");
Directory.CreateDirectory($"{testProjectDir}/GeneratedCode/QuantityTests");
Expand All @@ -68,6 +71,12 @@ public static void Generate(string rootDir, Quantity[] quantities)
Log.Information(sb.ToString());
}

var unitSystems = quantities.SelectMany(x => x.Units.SelectMany(u=> u.UnitSystems)).Distinct();
foreach (string unitSystem in unitSystems)
{
GenerateUnitSystemMappings(unitSystem, quantities, $"{outputDir}/UnitSystems/{unitSystem}.g.cs");
}

GenerateIQuantityTests(quantities, $"{testProjectDir}/GeneratedCode/IQuantityTests.g.cs");

Log.Information("");
Expand Down Expand Up @@ -164,5 +173,12 @@ private static void GenerateUnitConverter(Quantity[] quantities, string filePath
File.WriteAllText(filePath, content, Encoding.UTF8);
Log.Information("UnitConverter.g.cs: ".PadRight(AlignPad) + "(OK)");
}

private static void GenerateUnitSystemMappings(string unitSystemName, Quantity[] quantities, string filePath)
{
var content = new UnitSystemInfoGenerator(unitSystemName, quantities).Generate();
File.WriteAllText(filePath, content, Encoding.UTF8);
Log.Information($"{unitSystemName}.g.cs: ".PadRight(AlignPad) + "(OK)");
}
}
}
Loading