Skip to content

Annotate is native aot compatible #1543

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

Closed
Closed
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public string Generate()
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
#if NET
using System.Numerics;
Expand Down Expand Up @@ -154,7 +155,7 @@ private void GenerateStaticConstructor()

Writer.WL($@"
BaseUnit = {_unitEnumName}.{_quantity.BaseUnit};
Units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>().ToArray();
Units = EnumHelpers.GetValues<{_unitEnumName}>();
Zero = new {_quantity.Name}(0, BaseUnit);
Info = new QuantityInfo<{_unitEnumName}>(""{_quantity.Name}"",
new UnitInfo<{_unitEnumName}>[]
Expand Down Expand Up @@ -305,7 +306,7 @@ private void GenerateProperties()

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Enum IQuantity.Unit => Unit;

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
UnitKey IQuantity.UnitKey => UnitKey.ForUnit(Unit);

Expand Down Expand Up @@ -1195,7 +1196,7 @@ public string ToString(string? format, IFormatProvider? provider)
#endregion
" );
}

/// <inheritdoc cref="GetObsoleteAttributeOrNull(string)"/>
private static string? GetObsoleteAttributeOrNull(Quantity quantity) => GetObsoleteAttributeOrNull(quantity.ObsoleteText);

Expand Down
7 changes: 5 additions & 2 deletions CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,14 @@ public static bool TryParse(IFormatProvider? formatProvider, Type quantityType,
};
}

internal static IEnumerable<Type> GetQuantityTypes()
internal static void RegisterDefaultConversions(UnitConverter unitConverter)
{");
foreach (var quantity in _quantities)
{
Writer.WL($@"
yield return typeof({quantity.Name});");
{quantity.Name}.RegisterDefaultConversions(unitConverter);");
}

Writer.WL(@"
}
}
Expand Down
15 changes: 8 additions & 7 deletions CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ internal class UnitTestBaseClassGenerator : GeneratorBase
/// Example: "LengthUnit.Centimeter".
/// </summary>
private readonly string _otherOrBaseUnitFullName;

/// <summary>
/// Indicates whether the quantity is dimensionless.
/// </summary>
Expand Down Expand Up @@ -178,6 +178,7 @@ public string Generate()
using System.Globalization;
using System.Linq;
using System.Threading;
using UnitsNet.InternalHelpers;
using UnitsNet.Tests.Helpers;
using UnitsNet.Tests.TestsBase;
using UnitsNet.Units;
Expand Down Expand Up @@ -374,7 +375,7 @@ public void As_UnitSystem_ReturnsValueInDimensionlessUnit()
var quantity = new {_quantity.Name}(value: 1, unit: {_baseUnitFullName});

var convertedValue = quantity.As(UnitSystem.SI);

Assert.Equal(quantity.Value, convertedValue);
}}

Expand Down Expand Up @@ -420,7 +421,7 @@ public void ToUnitSystem_ReturnsValueInDimensionlessUnit()
public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull()
{{
UnitSystem nullUnitSystem = null!;
Assert.Multiple(() =>
Assert.Multiple(() =>
{{
var quantity = new {_quantity.Name}(value: 1, unit: {_quantity.Name}.BaseUnit);
Assert.Throws<ArgumentNullException>(() => quantity.ToUnit(nullUnitSystem));
Expand Down Expand Up @@ -496,23 +497,23 @@ public virtual void ToUnit_UnitSystem_SI_ReturnsQuantityInSIUnits()
IQuantity<{_unitEnumName}> convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI);

Assert.Equal(expectedUnit, convertedQuantity.Unit);
Assert.Equal(expectedValue, convertedQuantity.Value);
Assert.Equal(expectedValue, convertedQuantity.Value);
}}, () =>
{{
IQuantity quantityToConvert = quantity;

IQuantity convertedQuantity = quantityToConvert.ToUnit(UnitSystem.SI);

Assert.Equal(expectedUnit, convertedQuantity.Unit);
Assert.Equal(expectedValue, convertedQuantity.Value);
Assert.Equal(expectedValue, convertedQuantity.Value);
}});
}}

[Fact]
public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull()
{{
UnitSystem nullUnitSystem = null!;
Assert.Multiple(() =>
Assert.Multiple(() =>
{{
var quantity = new {_quantity.Name}(value: 1, unit: {_quantity.Name}.BaseUnit);
Assert.Throws<ArgumentNullException>(() => quantity.ToUnit(nullUnitSystem));
Expand Down Expand Up @@ -1011,7 +1012,7 @@ public void EqualsReturnsFalseOnNull()
[Fact]
public void HasAtLeastOneAbbreviationSpecified()
{{
var units = Enum.GetValues(typeof({_unitEnumName})).Cast<{_unitEnumName}>();
var units = EnumHelpers.GetValues<{_unitEnumName}>();
foreach (var unit in units)
{{
var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit);
Expand Down
17 changes: 17 additions & 0 deletions PerfTests/PerfTest_Startup_Aot/PerfTest_Startup_Aot.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<RootNamespace>perftest</RootNamespace>

<PublishAot>true</PublishAot>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\UnitsNet\UnitsNet.csproj" />
</ItemGroup>

</Project>
4 changes: 4 additions & 0 deletions PerfTests/PerfTest_Startup_Aot/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
using UnitsNet;
using UnitsNet.Units;

Console.WriteLine(Power.From(5, PowerUnit.Watt));
8 changes: 8 additions & 0 deletions PerfTests/PerfTest_Startup_Aot/profile.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# shellcheck disable=SC2155
declare -r dirname=$(dirname -- "$0")

pushd "$dirname" || exit
dotnet publish
dotnet timeit "$dirname/timeit.json"
popd || exit
8 changes: 8 additions & 0 deletions PerfTests/PerfTest_Startup_Aot/timeit.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"warmUpCount": 10,
"count": 20,
"scenarios": [{ "name": "Default" }],
"processName": "../../Artifacts/PerfTest_Startup_Aot/net9.0/win-x64/publish/PerfTest_Startup_Aot.exe",
"workingDirectory": "$(CWD)/",
"processTimeout": 15
}
1 change: 1 addition & 0 deletions UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<Nullable>enable</Nullable>
<RootNamespace>UnitsNet</RootNamespace>
<TargetFrameworks>netstandard2.0;net8.0;net9.0</TargetFrameworks>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">true</IsAotCompatible>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
<Nullable>enable</Nullable>
<RootNamespace>UnitsNet.Serialization.JsonNet</RootNamespace>
<TargetFrameworks>netstandard2.0;net8.0;net9.0</TargetFrameworks>
<IsAotCompatible Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net7.0'))">true</IsAotCompatible>
</PropertyGroup>

<!-- Strong name signing -->
Expand Down
6 changes: 5 additions & 1 deletion UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

using System;
using System.Collections.Concurrent;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
Expand All @@ -15,6 +15,10 @@ namespace UnitsNet.Serialization.JsonNet
/// Contains shared functionality used by <see cref="UnitsNetIQuantityJsonConverter"/> and <see cref="UnitsNetIComparableJsonConverter"/>
/// </summary>
/// <typeparam name="T">The type being converted. Should either be <see cref="IQuantity"/> or <see cref="IComparable"/></typeparam>
#if NET
[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")]
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
#endif
public abstract class UnitsNetBaseJsonConverter<T> : NullableQuantityConverter<T>
{
private readonly ConcurrentDictionary<string, (Type Quantity, Type Unit)> _registeredTypes = new();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand All @@ -15,6 +16,10 @@ namespace UnitsNet.Serialization.JsonNet
/// Should only be used when UnitsNet types are assigned to properties of type IComparable.
/// Requires TypeNameHandling on <see cref="JsonSerializerSettings"/> to be set to something other than <see cref="TypeNameHandling.None"/> so that it outputs $type when serializing.
/// </summary>
#if NET
[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")]
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
#endif
public sealed class UnitsNetIComparableJsonConverter : UnitsNetBaseJsonConverter<IComparable?>
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Diagnostics.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

Expand All @@ -12,6 +13,10 @@ namespace UnitsNet.Serialization.JsonNet
/// JSON.net converter for IQuantity types (e.g. all units in UnitsNet)
/// Use this converter to serialize and deserialize UnitsNet types to and from JSON
/// </summary>
#if NET
[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")]
[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")]
#endif
public sealed class UnitsNetIQuantityJsonConverter : UnitsNetBaseJsonConverter<IQuantity?>
{
/// <summary>
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading