From 834f5a1f8a0c93fd1eda52ceb7994baae67540ff Mon Sep 17 00:00:00 2001 From: chait Date: Sat, 7 Nov 2026 17:55:50 +0800 Subject: [PATCH 1/8] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E5=88=B0=20.NET=2010?= =?UTF-8?q?=EF=BC=8C=E8=A7=A3=E5=86=B3=E6=96=B9=E6=A1=88=E6=94=B9=E7=94=A8?= =?UTF-8?q?=20.slnx?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - TFM 统一 net10.0,依赖升到 10.0.14,Docker/CI 同步切换 - hosting 迁至 Generic Host;KnownNetworks 改 KnownIPNetworks(保留原配置键) - 内置 Jil 2.17.0 源码并修复 .NET 9+ TimeSpan.FromSeconds 反射歧义 - 删除 Opserver.sln,新增 Opserver.slnx --- .github/workflows/main.yml | 8 +- Dockerfile | 6 +- Opserver.sln | 77 - Opserver.slnx | 29 + ...n.DotSettings => Opserver.slnx.DotSettings | 0 appveyor.yml | 4 +- docs/Docs.csproj | 4 +- src/Directory.Build.props | 2 +- src/Opserver.Core/Opserver.Core.csproj | 25 +- src/Opserver.Web/Opserver.Web.csproj | 8 +- src/Opserver.Web/Program.cs | 6 +- src/Opserver.Web/Startup.cs | 7 +- tests/Directory.Build.props | 6 +- tests/Opserver.Tests/Opserver.Tests.csproj | 10 +- vendor/Jil/Common/ConstructionException.cs | 26 + vendor/Jil/Common/EnumValues.cs | 86 + vendor/Jil/Common/ExtensionMethods.cs | 1419 +++++ vendor/Jil/Common/FlagsEnumCombiner.cs | 65 + vendor/Jil/Common/PeekSupportingTextReader.cs | 43 + vendor/Jil/Common/UnionCharsetArrays.cs | 23 + vendor/Jil/Common/UnionCharsets.cs | 23 + vendor/Jil/Common/Utils.cs | 1719 ++++++ vendor/Jil/DateTimeFormat.cs | 83 + vendor/Jil/DeserializationException.cs | 190 + vendor/Jil/Deserialize/AnonymousTypeLookup.cs | 71 + vendor/Jil/Deserialize/DeserializeIndirect.cs | 84 + vendor/Jil/Deserialize/EnumLookup.cs | 248 + vendor/Jil/Deserialize/InlineDeserializer.cs | 2878 +++++++++ .../Deserialize/InterfaceImplementation.cs | 122 + vendor/Jil/Deserialize/Methods.Get.cs | 332 ++ .../Deserialize/Methods.ISO8601DateTime.cs | 1066 ++++ .../Deserialize/Methods.ISO8601TimeSpan.cs | 402 ++ vendor/Jil/Deserialize/Methods.ReadNumbers.cs | 2108 +++++++ vendor/Jil/Deserialize/Methods.ThunkReader.cs | 5154 +++++++++++++++++ vendor/Jil/Deserialize/Methods.cs | 1817 ++++++ vendor/Jil/Deserialize/NameAutomata.cs | 485 ++ vendor/Jil/Deserialize/SetterLookup.cs | 141 + vendor/Jil/Deserialize/ThunkReader.cs | 46 + vendor/Jil/Deserialize/TypeCaches.cs | 131 + vendor/Jil/Deserialize/UnionLookup.cs | 169 + .../DynamicDeserializer.ThunkReader.cs | 246 + .../DeserializeDynamic/DynamicDeserializer.cs | 273 + .../DeserializeDynamic/JsonObject.Dynamic.cs | 1514 +++++ .../JsonObject.Enumerators.cs | 456 ++ .../JsonObject.FastNumber.cs | 408 ++ .../DeserializeDynamic/JsonObject.Static.cs | 386 ++ .../JsonObject.TypeConverter.cs | 122 + vendor/Jil/DeserializeDynamic/JsonObject.cs | 119 + .../Methods.ISO8601DateTime.cs | 1267 ++++ .../Methods.ISO8601TimeSpan.cs | 386 ++ .../DeserializeDynamic/Methods.ThunkReader.cs | 457 ++ vendor/Jil/DeserializeDynamic/Methods.cs | 1769 ++++++ .../Jil/DeserializeDynamic/ObjectBuilder.cs | 157 + vendor/Jil/InfiniteRecursionException.cs | 32 + vendor/Jil/InternalsVisibleTo.cs | 7 + vendor/Jil/JSON.cs | 4850 ++++++++++++++++ vendor/Jil/Jil.csproj | 28 + vendor/Jil/JilDirectiveAttribute.cs | 97 + vendor/Jil/LICENSE | 20 + vendor/Jil/Options.cs | 488 ++ vendor/Jil/SerializationNameFormat.cs | 55 + vendor/Jil/Serialize/InlineSerializer.cs | 4493 ++++++++++++++ vendor/Jil/Serialize/Methods.Get.cs | 184 + vendor/Jil/Serialize/Methods.ThunkWriter.cs | 1565 +++++ vendor/Jil/Serialize/Methods.cs | 1694 ++++++ vendor/Jil/Serialize/SerializeDynamicThunk.cs | 45 + vendor/Jil/Serialize/ThunkWriter.cs | 432 ++ vendor/Jil/Serialize/TypeCaches.cs | 3601 ++++++++++++ vendor/Jil/Serialize/UnionMembersNullSigil.cs | 13 + .../Jil/SerializeDynamic/DynamicSerializer.cs | 876 +++ vendor/Jil/SerializeDynamic/NullTypeCache.cs | 13 + vendor/Jil/SerializeDynamic/OptionsLookup.cs | 363 ++ .../RecursiveSerializerCache.cs | 54 + vendor/Jil/SerializerException.cs | 37 + vendor/Jil/UnspecifiedDateTimeKindBehavior.cs | 25 + 75 files changed, 45537 insertions(+), 118 deletions(-) delete mode 100644 Opserver.sln create mode 100644 Opserver.slnx rename Opserver.sln.DotSettings => Opserver.slnx.DotSettings (100%) create mode 100644 vendor/Jil/Common/ConstructionException.cs create mode 100644 vendor/Jil/Common/EnumValues.cs create mode 100644 vendor/Jil/Common/ExtensionMethods.cs create mode 100644 vendor/Jil/Common/FlagsEnumCombiner.cs create mode 100644 vendor/Jil/Common/PeekSupportingTextReader.cs create mode 100644 vendor/Jil/Common/UnionCharsetArrays.cs create mode 100644 vendor/Jil/Common/UnionCharsets.cs create mode 100644 vendor/Jil/Common/Utils.cs create mode 100644 vendor/Jil/DateTimeFormat.cs create mode 100644 vendor/Jil/DeserializationException.cs create mode 100644 vendor/Jil/Deserialize/AnonymousTypeLookup.cs create mode 100644 vendor/Jil/Deserialize/DeserializeIndirect.cs create mode 100644 vendor/Jil/Deserialize/EnumLookup.cs create mode 100644 vendor/Jil/Deserialize/InlineDeserializer.cs create mode 100644 vendor/Jil/Deserialize/InterfaceImplementation.cs create mode 100644 vendor/Jil/Deserialize/Methods.Get.cs create mode 100644 vendor/Jil/Deserialize/Methods.ISO8601DateTime.cs create mode 100644 vendor/Jil/Deserialize/Methods.ISO8601TimeSpan.cs create mode 100644 vendor/Jil/Deserialize/Methods.ReadNumbers.cs create mode 100644 vendor/Jil/Deserialize/Methods.ThunkReader.cs create mode 100644 vendor/Jil/Deserialize/Methods.cs create mode 100644 vendor/Jil/Deserialize/NameAutomata.cs create mode 100644 vendor/Jil/Deserialize/SetterLookup.cs create mode 100644 vendor/Jil/Deserialize/ThunkReader.cs create mode 100644 vendor/Jil/Deserialize/TypeCaches.cs create mode 100644 vendor/Jil/Deserialize/UnionLookup.cs create mode 100644 vendor/Jil/DeserializeDynamic/DynamicDeserializer.ThunkReader.cs create mode 100644 vendor/Jil/DeserializeDynamic/DynamicDeserializer.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.Dynamic.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.Enumerators.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.FastNumber.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.Static.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.TypeConverter.cs create mode 100644 vendor/Jil/DeserializeDynamic/JsonObject.cs create mode 100644 vendor/Jil/DeserializeDynamic/Methods.ISO8601DateTime.cs create mode 100644 vendor/Jil/DeserializeDynamic/Methods.ISO8601TimeSpan.cs create mode 100644 vendor/Jil/DeserializeDynamic/Methods.ThunkReader.cs create mode 100644 vendor/Jil/DeserializeDynamic/Methods.cs create mode 100644 vendor/Jil/DeserializeDynamic/ObjectBuilder.cs create mode 100644 vendor/Jil/InfiniteRecursionException.cs create mode 100644 vendor/Jil/InternalsVisibleTo.cs create mode 100644 vendor/Jil/JSON.cs create mode 100644 vendor/Jil/Jil.csproj create mode 100644 vendor/Jil/JilDirectiveAttribute.cs create mode 100644 vendor/Jil/LICENSE create mode 100644 vendor/Jil/Options.cs create mode 100644 vendor/Jil/SerializationNameFormat.cs create mode 100644 vendor/Jil/Serialize/InlineSerializer.cs create mode 100644 vendor/Jil/Serialize/Methods.Get.cs create mode 100644 vendor/Jil/Serialize/Methods.ThunkWriter.cs create mode 100644 vendor/Jil/Serialize/Methods.cs create mode 100644 vendor/Jil/Serialize/SerializeDynamicThunk.cs create mode 100644 vendor/Jil/Serialize/ThunkWriter.cs create mode 100644 vendor/Jil/Serialize/TypeCaches.cs create mode 100644 vendor/Jil/Serialize/UnionMembersNullSigil.cs create mode 100644 vendor/Jil/SerializeDynamic/DynamicSerializer.cs create mode 100644 vendor/Jil/SerializeDynamic/NullTypeCache.cs create mode 100644 vendor/Jil/SerializeDynamic/OptionsLookup.cs create mode 100644 vendor/Jil/SerializeDynamic/RecursiveSerializerCache.cs create mode 100644 vendor/Jil/SerializerException.cs create mode 100644 vendor/Jil/UnspecifiedDateTimeKindBehavior.cs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f6b98955e..56b140dc7 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -4,12 +4,12 @@ on: [push] jobs: build: - runs-on: windows-2019 + runs-on: windows-2022 steps: - name: Setup .NET - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v4 with: - dotnet-version: 8.0.x - - uses: actions/checkout@v3 + dotnet-version: 10.0.x + - uses: actions/checkout@v4 - name: Build with dotnet run: dotnet build diff --git a/Dockerfile b/Dockerfile index d37788531..873b00671 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /app # Global -COPY ./*.sln ./nuget.config ./ +COPY ./*.slnx ./nuget.config ./ # Apps COPY src/*/*.csproj ./ RUN for file in $(ls *.csproj); do mkdir -p src/${file%.*}/ && mv $file src/${file%.*}/; done @@ -22,7 +22,7 @@ WORKDIR /app/src/Opserver.Web RUN dotnet publish -c Release -o publish # Build runtime image -FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS web +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS web WORKDIR /app COPY --from=web-publish /app/src/Opserver.Web/publish ./ ENTRYPOINT ["dotnet", "Opserver.Web.dll"] \ No newline at end of file diff --git a/Opserver.sln b/Opserver.sln deleted file mode 100644 index b59c3045f..000000000 --- a/Opserver.sln +++ /dev/null @@ -1,77 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29021.104 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Opserver.Core", "src\Opserver.Core\Opserver.Core.csproj", "{C58AFF99-F4D9-4A83-866E-18DA0A633F6B}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{52AF00E9-833A-44FE-BE7B-0DC7B84E2814}" - ProjectSection(SolutionItems) = preProject - .editorconfig = .editorconfig - .filenesting.json = .filenesting.json - appveyor.yml = appveyor.yml - azure-pipelines.yml = azure-pipelines.yml - Build.bat = Build.bat - global.json = global.json - nuget.config = nuget.config - readme.md = readme.md - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Opserver.Web", "src\Opserver.Web\Opserver.Web.csproj", "{B3D85A10-C7B4-4254-B387-688EF4C138EB}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{D924C9E2-44B2-4ACE-8BD9-C21348F5B6FB}" - ProjectSection(SolutionItems) = preProject - src\Directory.Build.props = src\Directory.Build.props - src\Opserver.ruleset = src\Opserver.ruleset - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{5304B28F-5CF0-4191-A195-EB4C8EEC068F}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{08F532FF-9F35-4D92-AD15-5A30BC8F2AF8}" - ProjectSection(SolutionItems) = preProject - .github\workflows\main.yml = .github\workflows\main.yml - EndProjectSection -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{79E50956-EA86-4F7A-A4B0-5691EF9B78F3}" - ProjectSection(SolutionItems) = preProject - tests\Directory.Build.props = tests\Directory.Build.props - EndProjectSection -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Opserver.Tests", "tests\Opserver.Tests\Opserver.Tests.csproj", "{11819295-F035-4298-AAF3-3D1C76BF1480}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Docs", "docs\Docs.csproj", "{8E99613D-D22E-487E-A9E2-EA5304AEB6A8}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {C58AFF99-F4D9-4A83-866E-18DA0A633F6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C58AFF99-F4D9-4A83-866E-18DA0A633F6B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C58AFF99-F4D9-4A83-866E-18DA0A633F6B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C58AFF99-F4D9-4A83-866E-18DA0A633F6B}.Release|Any CPU.Build.0 = Release|Any CPU - {B3D85A10-C7B4-4254-B387-688EF4C138EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {B3D85A10-C7B4-4254-B387-688EF4C138EB}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B3D85A10-C7B4-4254-B387-688EF4C138EB}.Release|Any CPU.ActiveCfg = Release|Any CPU - {B3D85A10-C7B4-4254-B387-688EF4C138EB}.Release|Any CPU.Build.0 = Release|Any CPU - {11819295-F035-4298-AAF3-3D1C76BF1480}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {11819295-F035-4298-AAF3-3D1C76BF1480}.Debug|Any CPU.Build.0 = Debug|Any CPU - {11819295-F035-4298-AAF3-3D1C76BF1480}.Release|Any CPU.ActiveCfg = Release|Any CPU - {11819295-F035-4298-AAF3-3D1C76BF1480}.Release|Any CPU.Build.0 = Release|Any CPU - {8E99613D-D22E-487E-A9E2-EA5304AEB6A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8E99613D-D22E-487E-A9E2-EA5304AEB6A8}.Release|Any CPU.ActiveCfg = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(NestedProjects) = preSolution - {C58AFF99-F4D9-4A83-866E-18DA0A633F6B} = {D924C9E2-44B2-4ACE-8BD9-C21348F5B6FB} - {B3D85A10-C7B4-4254-B387-688EF4C138EB} = {D924C9E2-44B2-4ACE-8BD9-C21348F5B6FB} - {08F532FF-9F35-4D92-AD15-5A30BC8F2AF8} = {5304B28F-5CF0-4191-A195-EB4C8EEC068F} - {11819295-F035-4298-AAF3-3D1C76BF1480} = {79E50956-EA86-4F7A-A4B0-5691EF9B78F3} - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {003C9475-D1B9-4600-9BB2-39769162858D} - EndGlobalSection -EndGlobal diff --git a/Opserver.slnx b/Opserver.slnx new file mode 100644 index 000000000..70efcb991 --- /dev/null +++ b/Opserver.slnx @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Opserver.sln.DotSettings b/Opserver.slnx.DotSettings similarity index 100% rename from Opserver.sln.DotSettings rename to Opserver.slnx.DotSettings diff --git a/appveyor.yml b/appveyor.yml index fbd4ec522..e18d2e6ec 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,7 @@ -image: Visual Studio 2019 +image: Visual Studio 2022 install: - - choco install dotnet-sdk --version 8.0.100 + - choco install dotnet-sdk --version 10.0.100 skip_branch_with_pr: true skip_tags: true diff --git a/docs/Docs.csproj b/docs/Docs.csproj index 016f27412..d37cac26a 100644 --- a/docs/Docs.csproj +++ b/docs/Docs.csproj @@ -1,5 +1,5 @@ - + - net6.0 + net10.0 \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 21c82dae4..5237d9d26 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -24,7 +24,7 @@ - + diff --git a/src/Opserver.Core/Opserver.Core.csproj b/src/Opserver.Core/Opserver.Core.csproj index b16a9181c..b13fdd418 100644 --- a/src/Opserver.Core/Opserver.Core.csproj +++ b/src/Opserver.Core/Opserver.Core.csproj @@ -2,28 +2,31 @@ Opserver Opserver.Core - net8.0 + net10.0 true embedded - - - - - - + + + + + + + + - - - + + + @@ -31,6 +34,6 @@ - + \ No newline at end of file diff --git a/src/Opserver.Web/Opserver.Web.csproj b/src/Opserver.Web/Opserver.Web.csproj index d69dc84d8..71443443a 100644 --- a/src/Opserver.Web/Opserver.Web.csproj +++ b/src/Opserver.Web/Opserver.Web.csproj @@ -2,16 +2,16 @@ Exe Opserver - net8.0 + net10.0 - + - + @@ -25,6 +25,6 @@ - + diff --git a/src/Opserver.Web/Program.cs b/src/Opserver.Web/Program.cs index c8e233c13..77abff303 100644 --- a/src/Opserver.Web/Program.cs +++ b/src/Opserver.Web/Program.cs @@ -1,9 +1,9 @@ using System; using System.Diagnostics; using System.Threading.Tasks; -using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Opserver.Helpers; @@ -17,7 +17,7 @@ private static async Task Main(string[] args) { try { - var host = WebHost.CreateDefaultBuilder(args) + var host = Host.CreateDefaultBuilder(args) .ConfigureAppConfiguration( (_, config) => { @@ -47,7 +47,7 @@ private static async Task Main(string[] args) .AddConsole(); } ) - .UseStartup() + .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup()) .Build(); await host.RunAsync(); diff --git a/src/Opserver.Web/Startup.cs b/src/Opserver.Web/Startup.cs index cda0d391c..9ad1fa4ff 100644 --- a/src/Opserver.Web/Startup.cs +++ b/src/Opserver.Web/Startup.cs @@ -136,11 +136,12 @@ public void ConfigureServices(IServiceCollection services) } var knownProxies = forwardedHeaders.GetSection(nameof(ForwardedHeadersOptions.KnownProxies)).Get>(); - var knownNetworks = forwardedHeaders.GetSection(nameof(ForwardedHeadersOptions.KnownNetworks)).Get>(); + // 配置键沿用 "KnownNetworks" 以兼容既有部署配置,仅内部映射到 .NET 10 的 KnownIPNetworks + var knownNetworks = forwardedHeaders.GetSection("KnownNetworks").Get>(); if (knownNetworks != null || knownProxies != null) { options.KnownProxies.Clear(); - options.KnownNetworks.Clear(); + options.KnownIPNetworks.Clear(); } if (knownProxies != null) @@ -157,7 +158,7 @@ public void ConfigureServices(IServiceCollection services) foreach (var knownNetwork in knownNetworks) { var ipNet = IPNet.Parse(knownNetwork); - options.KnownNetworks.Add(new Microsoft.AspNetCore.HttpOverrides.IPNetwork(ipNet.IPAddress, ipNet.CIDR)); + options.KnownIPNetworks.Add(new System.Net.IPNetwork(ipNet.IPAddress, ipNet.CIDR)); } } } diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index 559912403..27c274878 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -1,12 +1,12 @@ Library - 2.4.1 + 2.9.3 - + - + \ No newline at end of file diff --git a/tests/Opserver.Tests/Opserver.Tests.csproj b/tests/Opserver.Tests/Opserver.Tests.csproj index 5cb796eb7..9fd67d005 100644 --- a/tests/Opserver.Tests/Opserver.Tests.csproj +++ b/tests/Opserver.Tests/Opserver.Tests.csproj @@ -2,16 +2,16 @@ Opserver.Tests Opserver.Tests - net8.0 + net10.0 - - + + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/vendor/Jil/Common/ConstructionException.cs b/vendor/Jil/Common/ConstructionException.cs new file mode 100644 index 000000000..a0ff72876 --- /dev/null +++ b/vendor/Jil/Common/ConstructionException.cs @@ -0,0 +1,26 @@ +using System; + +namespace Jil.Common +{ + // Just a common type to act as a "couldn't build this junk!" catch-all + sealed class ConstructionException : Exception + { + /// + /// Gets a message that describes the current exception. + /// + public override string Message + { + // this is overridden just so I can make _really_ damn sure + // that Message is always stashed in Data + get + { + return (string)Data[Utils.ExceptionMessageDataKey]; + } + } + + public ConstructionException(string msg) : base(msg) + { + Data[Utils.ExceptionMessageDataKey] = msg; + } + } +} diff --git a/vendor/Jil/Common/EnumValues.cs b/vendor/Jil/Common/EnumValues.cs new file mode 100644 index 000000000..639158738 --- /dev/null +++ b/vendor/Jil/Common/EnumValues.cs @@ -0,0 +1,86 @@ +using Sigil; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Jil.Common +{ + static class EnumValues + where TEnum : struct + { + static readonly Dictionary PreCalculated; + + static EnumValues() + { + PreCalculated = new Dictionary(StringComparer.OrdinalIgnoreCase); + + foreach (var val in Enum.GetValues(typeof(TEnum))) + { + var name = typeof(TEnum).GetEnumValueName(val); + PreCalculated[name] = (TEnum)val; + } + } + + public static bool TryParse(string str, out TEnum ret) + { + return PreCalculated.TryGetValue(str, out ret); + } + } + + static class EnumValues + { + delegate bool TryParseProxy(string str, out object val); + + static readonly Hashtable Cache = new Hashtable(); + + static int NextName = 0; + static string GetNextName() + { + var r = Interlocked.Increment(ref NextName); + + return "ev_n" + r; + } + + public static bool TryParse(Type enumType, string str, out object ret) + { + var invoke = (TryParseProxy)Cache[enumType]; + if (invoke != null) return invoke(str, out ret); + + var emit = Emit.NewDynamicMethod(doVerify: Utils.DoVerify); + var specific = typeof(EnumValues<>).MakeGenericType(enumType).GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static); + + using (var loc = emit.DeclareLocal(enumType, GetNextName())) + { + emit.LoadArgument(0); // string + emit.LoadLocalAddress(loc); // string enum& + emit.Call(specific); // bool + emit.LoadArgument(1); // bool object& + emit.LoadLocal(loc); // bool object& enum + emit.Box(enumType); // bool object& object + emit.StoreIndirect(); // bool + emit.Return(); // --empty-- + } + + var parse = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + + lock (Cache) + { + if (Cache.ContainsKey(enumType)) + { + parse = (TryParseProxy)Cache[enumType]; + } + else + { + Cache[enumType] = parse; + } + } + + return parse(str, out ret); + } + } +} diff --git a/vendor/Jil/Common/ExtensionMethods.cs b/vendor/Jil/Common/ExtensionMethods.cs new file mode 100644 index 000000000..7307322fe --- /dev/null +++ b/vendor/Jil/Common/ExtensionMethods.cs @@ -0,0 +1,1419 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Common +{ + static class ExtensionMethods + { + public static ConstructorInfo GetPublicOrPrivateConstructor(this Type onType, params Type[] parameterTypes) + { + return onType.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, parameterTypes); + } + + public static ConstructorInfo GetConstructor(this Type type, BindingFlags flags, Type[] parameterTypes) + { + var info = type.GetTypeInfo(); + var cons = info.GetConstructors(flags); + foreach (var con in cons) + { + var ps = con.GetParameters(); + if (ps.Length != parameterTypes.Length) continue; + + var allMatch = true; + + for (var i = 0; i < ps.Length; i++) + { + var p = ps[i].ParameterType; + var pt = parameterTypes[i]; + if (pt != p) + { + allMatch = false; + } + } + + if (allMatch) return con; + } + + return null; + } + + public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags, Type[] parameterTypes) + { + var info = type.GetTypeInfo(); + var mtds = info.GetMethods(flags).Where(m => m.Name == name); + + foreach (var mtd in mtds) + { + var ps = mtd.GetParameters(); + if (ps.Length != parameterTypes.Length) continue; + + var allMatch = true; + for (var i = 0; i < ps.Length; i++) + { + var p = ps[i].ParameterType; + var pt = parameterTypes[i]; + if (p != pt) + { + allMatch = false; + } + } + + if (allMatch) + { + return mtd; + } + } + + return null; + } + + public static Module Module(this Type type) + { + var info = type.GetTypeInfo(); + return info.Module; + } + + public static Type GetNestedType(this Type type, string name) + { + var info = type.GetTypeInfo(); + var ret = info.GetNestedType(name); + + return ret; + } + + public static bool IsValueType(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsValueType; + } + + public static string ResolveString(this Module module, int handle) + { +#if NETSTANDARD1_6 + throw new NotImplementedException("Cannot resolve string references in IL on dotNetCore"); +#else + return module.ResolveString(handle); +#endif + } + + public static Type BaseType(this Type type) + { + var info = type.GetTypeInfo(); + + return info.BaseType; + } + + public static bool IsGenericType(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsGenericType; + } + + public static bool ShouldConvertEnum(this MemberInfo member, Type enumType) + { + Type ignored; + return member.ShouldConvertEnum(enumType, out ignored); + } + + public static bool ShouldConvertEnum(this MemberInfo member, Type enumType, out Type toType) + { + var attr = member.GetCustomAttribute(); + if (attr == null || attr.TreatEnumerationAs == null) + { + toType = null; + return false; + } + + var primitiveType = Enum.GetUnderlyingType(enumType); + var convert = attr.TreatEnumerationAs; + + bool underlyingSigned, targetSigned; + int underlyingSize, targetSize; + + if (!GetEnumUnderlyingPrimitiveInfo(primitiveType, out underlyingSigned, out underlyingSize) || !GetEnumUnderlyingPrimitiveInfo(primitiveType, out targetSigned, out targetSize)) + { + throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], convert is not an acceptable integer primitive type"); + } + + // possible cases + // both are signed and target is equal or large to underlying => OK + // underlying is unsigned, and target is unsigned and equal or larger => OK + // underlying is unsigned and target is signed and larger => OK + // underlying is signed, target is unsigned => NOPE + // underlying is unsigned, target is signed and equal or smaller => NOPE + + if (underlyingSigned && !targetSigned) + { + throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], there is a signed/unsigned mismatch"); + } + + if (!underlyingSigned && (targetSigned && targetSize <= underlyingSize)) + { + throw new ConstructionException("Cannot map enum [" + enumType + "] with underlying type [" + primitiveType + "] to [" + convert + "], target type is not large enough"); + } + + toType = convert; + return true; + } + + static bool GetEnumUnderlyingPrimitiveInfo(Type primitiveType, out bool signed, out int numBytes) + { + if (primitiveType == typeof(byte)) + { + signed = false; + numBytes = 1; + return true; + } + + if (primitiveType == typeof(sbyte)) + { + signed = true; + numBytes = 1; + return true; + } + + if (primitiveType == typeof(short)) + { + signed = true; + numBytes = 2; + return true; + } + + if (primitiveType == typeof(ushort)) + { + signed = false; + numBytes = 2; + return true; + } + + if (primitiveType == typeof(int)) + { + signed = true; + numBytes = 4; + return true; + } + + if (primitiveType == typeof(uint)) + { + signed = false; + numBytes = 4; + return true; + } + + if (primitiveType == typeof(long)) + { + signed = true; + numBytes = 8; + return true; + } + + if (primitiveType == typeof(ulong)) + { + signed = false; + numBytes = 8; + return true; + } + + signed = false; + numBytes = -1; + + return false; + } + + public static TextReader MakeSupportPeek(this TextReader inner) + { + var asStringReader = inner as StringReader; + if (asStringReader != null) return asStringReader; + + var asStreamReader = inner as StreamReader; + if(asStreamReader != null && asStreamReader.BaseStream.CanSeek) return asStreamReader; + + return new PeekSupportingTextReader(inner); + } + + public static string GetEnumValueName(this Type enumType, object enumVal) + { + var field = enumType.GetFields().Single(f => f.Name == Enum.GetName(enumType, enumVal)); + + var enumMember = field.GetCustomAttribute(); + if (enumMember == null || enumMember.Value == null) + { + return Enum.GetName(enumType, enumVal); + } + + return enumMember.Value; + } + + public static bool IsFlagsEnum(this Type enumType) + { + return enumType.GetCustomAttribute() != null; + } + + public static T GetCustomAttribute(this Type type) + where T : Attribute + { + var info = type.GetTypeInfo(); + var data = info.CustomAttributes.Where(a => a.AttributeType == typeof(T)).SingleOrDefault(); + + if (data == null) return null; + + var cons = data.Constructor; + var args = data.ConstructorArguments.Select(a => a.Value).ToArray(); + var ret = cons.Invoke(args); + + return (T)ret; + } + + public static bool IsInterface(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsInterface; + } + + public static bool IsSealed(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsSealed; + } + + public static bool IsPublic(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsPublic; + } + + public static bool IsGenericContainer(this Type forType, Type containerType) + { + return forType.IsInterface() && forType.IsGenericType() && forType.GetGenericTypeDefinition() == containerType; + } + + public static bool IsGenericDictionary(this Type forType) + { + return IsGenericContainer(forType, typeof(IDictionary<,>)); + } + + public static bool IsGenericEnumerable(this Type forType) + { + return IsGenericContainer(forType, typeof(IEnumerable<>)); + } + + public static bool IsGenericReadOnlyList(this Type forType) + { + return IsGenericContainer(forType, typeof(IReadOnlyList<>)); + } + + public static bool IsGenericReadOnlyDictionary(this Type forType) + { + return IsGenericContainer(forType, typeof(IReadOnlyDictionary<,>)); + } + + public static string GetSerializationName(this MemberInfo member, SerializationNameFormat serializationNameFormat) + { + var jilDirectiveAttr = member.GetCustomAttribute(); + if (jilDirectiveAttr != null && jilDirectiveAttr.Name != null) return jilDirectiveAttr.Name; + + var dataMemberAttr = member.GetCustomAttribute(); + if (dataMemberAttr != null && dataMemberAttr.Name != null) return dataMemberAttr.Name; + + switch (serializationNameFormat) + { + case SerializationNameFormat.CamelCase: + return member.Name.ToCamelCase(); + default: + return member.Name; + } + } + + public static string ToCamelCase(this string s) + { + if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) return s; + + var cArr = s.ToCharArray(); + for (var i = 0; i < cArr.Length; i++) + { + if (i > 0 && i + 1 < cArr.Length && !char.IsUpper(cArr[i + 1])) break; + cArr[i] = char.ToLowerInvariant(cArr[i]); + } + + return new string(cArr); + } + + public static bool IsLoadArgumentOpCode(this OpCode op) + { + return + op == OpCodes.Ldarg || + op == OpCodes.Ldarg_0 || + op == OpCodes.Ldarg_1 || + op == OpCodes.Ldarg_2 || + op == OpCodes.Ldarg_3 || + op == OpCodes.Ldarg_S; + } + + /// + /// HACK: This is a best effort attempt to divine if a type is anonymous based on the language spec. + /// + /// Reference section 7.6.10.6 of the C# language spec as of 2012/11/19 + /// + /// It checks: + /// - is a class + /// - descends directly from object + /// - has [CompilerGenerated] + /// - has a single constructor + /// - that constructor takes exactly the same parameters as its public properties + /// - all public properties are not writable + /// - has a private field for every public property + /// - overrides Equals(object) + /// - overrides GetHashCode() + /// + public static bool IsAnonymouseClass(this Type type) // don't fix the typo, it's fitting. + { + if (type.IsValueType()) return false; + if (type.BaseType() != typeof(object)) return false; + + var compilerGenerated = type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == typeof(CompilerGeneratedAttribute)); + if (!compilerGenerated) return false; + + var allCons = type.GetConstructors(); + if (allCons.Length != 1) return false; + + var cons = allCons[0]; + if (!cons.IsPublic) return false; + + var props = type.GetProperties(); + if (props.Any(p => p.CanWrite)) return false; + + var propTypes = props.Select(t => t.PropertyType).ToList(); + + foreach (var param in cons.GetParameters()) + { + if (!propTypes.Contains(param.ParameterType)) return false; + + propTypes.Remove(param.ParameterType); + } + + if (propTypes.Count != 0) return false; + + var fields = type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); + if (fields.Any(f => !f.IsPrivate)) return false; + + propTypes = props.Select(t => t.PropertyType).ToList(); + foreach (var field in fields) + { + if (!propTypes.Contains(field.FieldType)) return false; + + propTypes.Remove(field.FieldType); + } + + if (propTypes.Count != 0) return false; + + var equals = type.GetMethod("Equals", new Type[] { typeof(object) }); + var hashCode = type.GetMethod("GetHashCode", new Type[0]); + + if (!equals.IsOverride() || !hashCode.IsOverride()) return false; + + return true; + } + + public static bool IsOverride(this MethodInfo method) + { + return method.GetBaseDefinition() != method; + } + + public static bool IsUserDefinedType(this Type type) + { + return !type.IsListType() && !type.IsDictionaryType() && !type.IsEnum() && !type.IsPrimitiveType(); + } + + public static bool IsEnum(this Type type) + { + var info = type.GetTypeInfo(); + + return info.IsEnum; + } + + public static bool IsConstant(this MemberInfo member) + { + var asField = member as FieldInfo; + if (asField != null) return asField.IsConstant(); + + var asProp = member as PropertyInfo; + if (asProp != null) return asProp.IsConstant(); + + throw new Exception("Expected member to be a FieldInfo or PropertyInfo, found: " + member); + } + + public static bool IsConstant(this FieldInfo field) + { + try + { + return field.IsLiteral && field.ReturnType().IsPropagatableType() && field.GetRawConstantValue() != null; + } + catch (Exception) + { + // Something went sideways, bail + return false; + } + } + + static readonly IEnumerable ReadOnlyOpCodes = + new[] + { + OpCodes.Ldc_I4, // Constant integer numbers + OpCodes.Ldc_I4_0, + OpCodes.Ldc_I4_1, + OpCodes.Ldc_I4_2, + OpCodes.Ldc_I4_3, + OpCodes.Ldc_I4_4, + OpCodes.Ldc_I4_5, + OpCodes.Ldc_I4_6, + OpCodes.Ldc_I4_7, + OpCodes.Ldc_I4_8, + OpCodes.Ldc_I4_M1, + OpCodes.Ldc_I4_S, + OpCodes.Ldc_I8, + + OpCodes.Ldc_R4, // Constant floating point numbers + OpCodes.Ldc_R8, + + OpCodes.Ldstr, // Constant strings + + OpCodes.Conv_I, // Conversion operators + OpCodes.Conv_I1, + OpCodes.Conv_I2, + OpCodes.Conv_I4, + OpCodes.Conv_I8, + OpCodes.Conv_Ovf_I, + OpCodes.Conv_Ovf_I_Un, + OpCodes.Conv_Ovf_I1, + OpCodes.Conv_Ovf_I1_Un, + OpCodes.Conv_Ovf_I2, + OpCodes.Conv_Ovf_I2_Un, + OpCodes.Conv_Ovf_I4, + OpCodes.Conv_Ovf_I4_Un, + OpCodes.Conv_Ovf_I8, + OpCodes.Conv_Ovf_I8_Un, + OpCodes.Conv_R4, + OpCodes.Conv_R8, + + OpCodes.Ldnull // always null + }; + + static readonly IEnumerable ConstantLoadOpCodes = + new[] + { + OpCodes.Ldc_I4_0, + OpCodes.Ldc_I4_1, + OpCodes.Ldc_I4_2, + OpCodes.Ldc_I4_3, + OpCodes.Ldc_I4_4, + OpCodes.Ldc_I4_5, + OpCodes.Ldc_I4_6, + OpCodes.Ldc_I4_7, + OpCodes.Ldc_I4_8, + OpCodes.Ldc_I4_M1, + + OpCodes.Ldnull + }; + + public static bool IsConstant(this PropertyInfo prop) + { + var getMtd = prop.GetMethod; + + // virtual methods can't be proven constant, who knows what overrides are out there + if (getMtd == null || getMtd.IsVirtual) return false; + + var instrs = Utils.Decompile(getMtd); + if (instrs == null) return false; + + // anything control flow-y, call-y, load-y, etc. means the property isn't constant + var hasNonConstantInstructions = instrs.Any(a => !ReadOnlyOpCodes.Contains(a.Item1) && a.Item1 != OpCodes.Ret); + if (hasNonConstantInstructions) return false; + + // if *two* constants are in play (somehow) we can't tell which one to propagate so break it + var numberOfConstants = instrs.Count(a => ConstantLoadOpCodes.Contains(a.Item1) || a.Item2.HasValue || a.Item3.HasValue || a.Item4.HasValue); + if (numberOfConstants != 1) return false; + + return true; + } + + public static string GetConstantJSONStringEquivalent(this MemberInfo member, bool jsonp) + { + var asField = member as FieldInfo; + if (asField != null) return asField.GetConstantJSONStringEquivalent(jsonp); + + var asProp = member as PropertyInfo; + if (asProp != null) return asProp.GetConstantJSONStringEquivalent(jsonp); + + throw new Exception("Expected member to be a FieldInfo or PropetyInfo, found: " + member); + } + + public static string GetConstantJSONStringEquivalent(this PropertyInfo prop, bool jsonp) + { +#if NETSTANDARD1_6 + throw new NotImplementedException("It's not possible to determine a constant value for a property in dotnet core."); +#else + + var instrs = Utils.Decompile(prop.GetMethod); + + var constInstr = instrs.Single(o => ConstantLoadOpCodes.Contains(o.Item1) || o.Item2.HasValue || o.Item3.HasValue || o.Item4.HasValue); + + object equivObj = null; + + if (ConstantLoadOpCodes.Contains(constInstr.Item1)) + { + if (constInstr.Item1 == OpCodes.Ldnull) + { + equivObj = null; + } + else + { + if (constInstr.Item1 == OpCodes.Ldc_I4_0) equivObj = 0; + if (constInstr.Item1 == OpCodes.Ldc_I4_1) equivObj = 1; + if (constInstr.Item1 == OpCodes.Ldc_I4_2) equivObj = 2; + if (constInstr.Item1 == OpCodes.Ldc_I4_3) equivObj = 3; + if (constInstr.Item1 == OpCodes.Ldc_I4_4) equivObj = 4; + if (constInstr.Item1 == OpCodes.Ldc_I4_5) equivObj = 5; + if (constInstr.Item1 == OpCodes.Ldc_I4_6) equivObj = 6; + if (constInstr.Item1 == OpCodes.Ldc_I4_7) equivObj = 7; + if (constInstr.Item1 == OpCodes.Ldc_I4_8) equivObj = 8; + if (constInstr.Item1 == OpCodes.Ldc_I4_M1) equivObj = -1; + + if (equivObj == null) throw new Exception("Couldn't determine constant being loaded"); + } + } + else + { + if (constInstr.Item1 == OpCodes.Ldstr) + { + var handle = constInstr.Item2.Value; + equivObj = prop.Module.ResolveString(handle); + } + + if (constInstr.Item1 == OpCodes.Ldc_R8) + { + equivObj = constInstr.Item4.Value; + } + + if (constInstr.Item1 == OpCodes.Ldc_R4) + { + equivObj = constInstr.Item4.Value; + } + + if (constInstr.Item1 == OpCodes.Ldc_I4) + { + equivObj = constInstr.Item2.Value; + } + + if (constInstr.Item1 == OpCodes.Ldc_I4_S) + { + equivObj = (sbyte)constInstr.Item2.Value; + } + + if (constInstr.Item1 == OpCodes.Ldc_I8) + { + equivObj = constInstr.Item3.Value; + } + } + + if (equivObj != null && equivObj.GetType() != prop.ReturnType()) + { + equivObj = ConvertType(equivObj, equivObj.GetType(), prop.ReturnType()); + } + + return GetConstantJSONStringEquivalent(prop.ReturnType(), equivObj, jsonp); +#endif + } + + private static object ConvertType(object val, Type fromType, Type toType) + { + if (toType.IsEnum()) + { + toType = Enum.GetUnderlyingType(toType); + } + + if (toType == typeof(sbyte)) + { + if (fromType.IsSigned()) + { + var l = (long)Convert.ChangeType(val, typeof(long)); + + return (sbyte)l; + } + + var ul = (ulong)Convert.ChangeType(val, typeof(ulong)); + + return (sbyte)ul; + } + + if (toType == typeof(ushort)) + { + if (fromType.IsSigned()) + { + var l = (long)Convert.ChangeType(val, typeof(long)); + + return (ushort)l; + } + + var ul = (ulong)Convert.ChangeType(val, typeof(ulong)); + + return (ushort)ul; + } + + if (toType == typeof(uint)) + { + if (fromType.IsSigned()) + { + var l = (long)Convert.ChangeType(val, typeof(long)); + + return (uint)l; + } + + var ul = (ulong)Convert.ChangeType(val, typeof(ulong)); + + return (uint)ul; + } + + if (toType == typeof(ulong)) + { + if (fromType.IsSigned()) + { + long l = (long)Convert.ChangeType(val, typeof(long)); + + return (ulong)l; + } + + return Convert.ChangeType(val, typeof(ulong)); + } + + return Convert.ChangeType(val, toType); + } + + public static bool IsUnsigned(this Type t) + { + return !t.IsSigned(); + } + + public static bool IsSigned(this Type t) + { + return + t == typeof(sbyte) || + t == typeof(short) || + t == typeof(int) || + t == typeof(long); + } + + public static string GetConstantJSONStringEquivalent(this FieldInfo field, bool jsonp) + { + var obj = field.GetRawConstantValue(); + + return GetConstantJSONStringEquivalent(field.ReturnType(), obj, jsonp); + } + + private static string GetConstantJSONStringEquivalent(Type type, object obj, bool jsonp) + { + if (obj == null) return "null"; + + var asStr = obj as string; + if (asStr != null) + { + return "\"" + asStr.JsonEscape(jsonp) + "\""; + } + + var asChar = obj is char ? (char?)(char)obj : (char?)null; + if (asChar != null) + { + return "\"" + asChar.Value.JsonEscape(jsonp) + "\""; + } + + var asBool = obj is bool ? (bool?)(bool)obj : (bool?)null; + if (asBool != null) + { + return asBool.Value ? "true" : "false"; + } + + if (type.IsEnum()) + { + return "\"" + type.GetEnumValueName(obj).JsonEscape(jsonp) + "\""; + } + + var formattable = obj as IFormattable; + if (formattable != null) + return formattable.ToString(null, CultureInfo.InvariantCulture); + else + return obj.ToString(); + } + + public static bool IsPropagatableType(this Type t) + { + return + t == typeof(string) || + t == typeof(char) || + t == typeof(float) || + t == typeof(double) || + t == typeof(byte) || + t == typeof(sbyte) || + t == typeof(short) || + t == typeof(ushort) || + t == typeof(int) || + t == typeof(uint) || + t == typeof(long) || + t == typeof(ulong) || + t == typeof(bool) || + t.IsEnum(); + } + + public static bool ShouldUseMember(this MemberInfo memberInfo) + { + var jilDirectiveAttributes = memberInfo.GetCustomAttributes(); + if (jilDirectiveAttributes.Count() > 0) return !jilDirectiveAttributes.Any(d => d.Ignore); + + var ignoreDataMemberAttributes = memberInfo.GetCustomAttributes(); + return ignoreDataMemberAttributes.Count() == 0; + } + + public static MethodInfo ShouldSerializeMethod(this PropertyInfo prop, Type serializingType) + { + var mtdName = "ShouldSerialize" + prop.Name; + + var ret = + serializingType + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where(m => m.Name == mtdName && m.ReturnType == typeof(bool) && m.GetParameters().Length == 0) + .SingleOrDefault(); + + return ret; + } + + public static Type ReturnType(this MemberInfo m) + { + var asField = m as FieldInfo; + var asProp = m as PropertyInfo; + + return + asField != null ? asField.FieldType : asProp.PropertyType; + } + + public static bool IsNullableType(this Type t) + { + var underlying = GetUnderlyingType(t); + + return underlying != null; + } + + public static Type GetUnderlyingType(this Type t) + { + return Nullable.GetUnderlyingType(t); + } + + public static bool IsContainerType(this Type t, Type containerType) + { + try + { + return + (t.IsGenericType() && t.GetGenericTypeDefinition() == containerType) || + t.GetInterfaces().Any(i => i.IsGenericType() && i.GetGenericTypeDefinition() == containerType); + } + catch (Exception) { return false; } + } + + public static bool IsListType(this Type t) + { + return t.IsContainerType(typeof(IList<>)); + } + + public static bool IsCollectionType(this Type t) + { + return t.IsContainerType(typeof(ICollection<>)); + } + + public static bool IsEnumerableType(this Type t) + { + return t.IsContainerType(typeof(IEnumerable<>)); + } + + public static bool IsReadOnlyListType(this Type t) + { + return t.IsContainerType(typeof(IReadOnlyList<>)); + } + + public static bool IsReadOnlyDictionaryType(this Type t) + { + return t.IsContainerType(typeof(IReadOnlyDictionary<,>)); + } + + public static Type GetListInterface(this Type t) + { + return t.GetContainerInterface(typeof(IList<>)); + } + + public static Type GetSetInterface(this Type t) + { + return t.GetContainerInterface(typeof(ISet<>)); + } + + public static Type GetReadOnlyListInterface(this Type t) + { + return t.GetContainerInterface(typeof(IReadOnlyList<>)); + } + + public static Type GetEnumerableInterface(this Type t) + { + return t.GetContainerInterface(typeof(IEnumerable<>)); + } + + public static Type GetCollectionInterface(this Type t) + { + return t.GetContainerInterface(typeof(ICollection<>)); + } + + public static Type GetReadOnlyCollectionInterface(this Type t) + { + return t.GetContainerInterface(typeof(IReadOnlyCollection<>)); + } + + public static bool IsDictionaryType(this Type t) + { + return t.IsContainerType(typeof(IDictionary<,>)); + } + + public static bool IsSetType(this Type t) + { + return t.IsContainerType(typeof(ISet<>)); + } + + public static Type GetContainerInterface(this Type t, Type containerType) + { + return + (t.IsGenericType() && t.GetGenericTypeDefinition() == containerType) + ? t + : t.GetInterfaces().First(i => i.IsGenericType() && i.GetGenericTypeDefinition() == containerType); + } + + public static Type GetDictionaryInterface(this Type t) + { + return t.GetContainerInterface(typeof(IDictionary<,>)); + } + + public static Type GetReadOnlyDictionaryInterface(this Type t) + { + return t.GetContainerInterface(typeof(IReadOnlyDictionary<,>)); + } + + public static bool IsExactlyDictionaryType(this Type t) + { + if (!t.IsGenericType()) return false; + + var generic = t.GetGenericTypeDefinition(); + + return generic == typeof(Dictionary<,>); + } + + public static bool IsSimpleInterface(this Type t) + { + // not an interface? bail + if (!t.IsInterface()) return false; + + // not public? bail + if (!t.IsPublic()) return false; + + var members = t.GetAllInterfaceMembers(); + + var mtds = members.OfType().ToList(); + var props = members.OfType().ToList(); + + // something weird here, bail + if (mtds.Count + props.Count != members.Count) return false; + + // any methods that aren't property accessors? bail + if (mtds.Any(m => !props.Any(p => p.GetMethod == m || p.SetMethod == m))) return false; + + // define a property that takes parameters? bail + if (props.Any(p => p.GetIndexParameters().Length != 0)) return false; + + return true; + } + + public static List GetAllInterfaceMembers(this Type t) + { + if (!t.IsInterface()) throw new Exception("Expected interface, found: " + t); + + var pending = new Stack(); + pending.Push(t); + + var ret = new List(); + + while (pending.Count > 0) + { + var current = pending.Pop(); + + ret.AddRange(current.GetMembers()); + + if (current.BaseType() != null) + { + pending.Push(current.BaseType()); + } + + current.GetInterfaces().ForEach(i => pending.Push(i)); + } + + return ret; + } + + public static void ForEach(this IEnumerable e, Action func) + { + foreach (var x in e) + { + func(x); + } + } + + public static bool IsPrimitiveType(this Type t) + { + return + t == typeof(string) || + t == typeof(char) || + t == typeof(float) || + t == typeof(double) || + t == typeof(decimal) || + t == typeof(byte) || + t == typeof(sbyte) || + t == typeof(short) || + t == typeof(ushort) || + t == typeof(int) || + t == typeof(uint) || + t == typeof(long) || + t == typeof(ulong) || + t == typeof(bool) || + t == typeof(DateTime) || + t == typeof(DateTimeOffset) || + t == typeof(Guid) || + t == typeof(TimeSpan); + } + + public static bool IsPrimitiveWrapper(this Type type) + { + return type.GetCustomAttribute() != null; + } + + public static MemberInfo GetPrimitiveWrapperPropertyOrField(this Type primitiveWrapperType) + { + var members = primitiveWrapperType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + + var candidates = + members.Where( + m => + { + var f = m as FieldInfo; + if (f != null) + return f.GetCustomAttribute() == null && f.FieldType.IsPrimitiveType(); + var p = m as PropertyInfo; + if (p != null) + return p.PropertyType.IsPrimitiveType(); + return false; + } + ); + + var candidateCount = candidates.Count(); + + if(candidateCount != 1) + { + throw new ConstructionException("Primitive wrappers can only have 1 declared primitive member, found " + candidateCount + " for " + primitiveWrapperType.Name); + } + + return candidates.Single(); + } + + public static bool IsStringyType(this MemberInfo member) + { + var asField = member as FieldInfo; + if (asField != null) + { + return asField.FieldType.IsStringyType(); + } + + var asProperty = member as PropertyInfo; + if (asProperty != null) + { + return asProperty.PropertyType.IsStringyType(); + } + + throw new InvalidOperationException(); + } + + public static bool IsStringyType(this Type t) + { + return + t == typeof(string) || + t == typeof(char); + } + + // From: http://www.ietf.org/rfc/rfc4627.txt?number=4627 + public static string JsonEscape(this string str, bool jsonp) + { + var ret = ""; + foreach (var c in str) + { + ret += c.JsonEscape(jsonp); + } + + return ret; + } + + public static void JsonEscapeFast(this string str, bool jsonp, System.IO.TextWriter output) + { + for (var i = 0; i < str.Length; i++) + { + var c = str[i]; + + if (jsonp) + { + if (c == '\u2028') + { + output.Write(@"\u2028"); + continue; + } + + if (c == '\u2029') + { + output.Write(@"\u2029"); + continue; + } + } + + if (c == '\\') + { + output.Write(@"\\"); + continue; + } + + if (c == '"') + { + output.Write(@"\"""); + continue; + } + + switch (c) + { + case '\u0000': output.Write(@"\u0000"); continue; + case '\u0001': output.Write(@"\u0001"); continue; + case '\u0002': output.Write(@"\u0002"); continue; + case '\u0003': output.Write(@"\u0003"); continue; + case '\u0004': output.Write(@"\u0004"); continue; + case '\u0005': output.Write(@"\u0005"); continue; + case '\u0006': output.Write(@"\u0006"); continue; + case '\u0007': output.Write(@"\u0007"); continue; + case '\u0008': output.Write(@"\u0008"); continue; + case '\u0009': output.Write(@"\t"); continue; + case '\u000A': output.Write(@"\n"); continue; + case '\u000B': output.Write(@"\v"); continue; + case '\u000C': output.Write(@"\f"); continue; + case '\u000D': output.Write(@"\r"); continue; + case '\u000E': output.Write(@"\u000E"); continue; + case '\u000F': output.Write(@"\u000F"); continue; + case '\u0010': output.Write(@"\u0010"); continue; + case '\u0011': output.Write(@"\u0011"); continue; + case '\u0012': output.Write(@"\u0012"); continue; + case '\u0013': output.Write(@"\u0013"); continue; + case '\u0014': output.Write(@"\u0014"); continue; + case '\u0015': output.Write(@"\u0015"); continue; + case '\u0016': output.Write(@"\u0016"); continue; + case '\u0017': output.Write(@"\u0017"); continue; + case '\u0018': output.Write(@"\u0018"); continue; + case '\u0019': output.Write(@"\u0019"); continue; + case '\u001A': output.Write(@"\u001A"); continue; + case '\u001B': output.Write(@"\u001B"); continue; + case '\u001C': output.Write(@"\u001C"); continue; + case '\u001D': output.Write(@"\u001D"); continue; + case '\u001E': output.Write(@"\u001E"); continue; + case '\u001F': output.Write(@"\u001F"); continue; + } + + output.Write(c); + } + } + + public static string JsonEscape(this char c, bool jsonp) + { + switch (c) + { + case '\\': return @"\\"; + case '"': return @"\"""; + case '\u0000': return @"\u0000"; + case '\u0001': return @"\u0001"; + case '\u0002': return @"\u0002"; + case '\u0003': return @"\u0003"; + case '\u0004': return @"\u0004"; + case '\u0005': return @"\u0005"; + case '\u0006': return @"\u0006"; + case '\u0007': return @"\u0007"; + case '\u0008': return @"\u0008"; + case '\u0009': return @"\t"; + case '\u000A': return @"\n"; + case '\u000B': return @"\v"; + case '\u000C': return @"\f"; + case '\u000D': return @"\r"; + case '\u000E': return @"\u000E"; + case '\u000F': return @"\u000F"; + case '\u0010': return @"\u0010"; + case '\u0011': return @"\u0011"; + case '\u0012': return @"\u0012"; + case '\u0013': return @"\u0013"; + case '\u0014': return @"\u0014"; + case '\u0015': return @"\u0015"; + case '\u0016': return @"\u0016"; + case '\u0017': return @"\u0017"; + case '\u0018': return @"\u0018"; + case '\u0019': return @"\u0019"; + case '\u001A': return @"\u001A"; + case '\u001B': return @"\u001B"; + case '\u001C': return @"\u001C"; + case '\u001D': return @"\u001D"; + case '\u001E': return @"\u001E"; + case '\u001F': return @"\u001F"; + + case '\u2028': + if (jsonp) + { + return @"\u2028"; + } + else + { + goto default; + } + + case '\u2029': + if (jsonp) + { + return @"\u2029"; + } + else + { + goto default; + } + + default: return c.ToString(); + } + } + + public static object DefaultValue(this Type t) + { + if (!t.IsValueType()) return null; + + return Activator.CreateInstance(t); + } + + public static bool IsNumberType(this Type t) + { + return t.IsIntegerNumberType() || t.IsFloatingPointNumberType(); + } + + public static bool IsIntegerNumberType(this Type t) + { + return + t == typeof(byte) || + t == typeof(sbyte) || + t == typeof(short) || + t == typeof(ushort) || + t == typeof(int) || + t == typeof(uint) || + t == typeof(long) || + t == typeof(ulong); + } + + public static bool IsFloatingPointNumberType(this Type t) + { + return + t == typeof(float) || + t == typeof(double) || + t == typeof(decimal); + } + + public static List InvolvedTypes(this Type t) + { + var ret = new List(); + + var pending = new Stack(); + pending.Push(t); + + while (pending.Count > 0) + { + var cur = pending.Pop(); + if (!ret.Contains(cur)) + { + ret.Add(cur); + } + else + { + continue; + } + + if (cur.IsNullableType()) + { + var inner = Nullable.GetUnderlyingType(cur); + pending.Push(inner); + continue; + } + + if (cur.IsListType()) + { + var elem = cur.GetListInterface().GetGenericArguments()[0]; + pending.Push(elem); + continue; + } + + if (cur.IsDictionaryType()) + { + var key = cur.GetDictionaryInterface().GetGenericArguments()[0]; + var val = cur.GetDictionaryInterface().GetGenericArguments()[1]; + + pending.Push(key); + pending.Push(val); + + continue; + } + + if (cur.IsEnumerableType()) + { + var val = cur.GetEnumerableInterface().GetGenericArguments()[0]; + pending.Push(val); + + continue; + } + + cur.GetFields().ForEach(f => pending.Push(f.FieldType)); + cur.GetProperties().Where(p => p.GetMethod != null && p.GetMethod.GetParameters().Length == 0).ForEach(p => pending.Push(p.PropertyType)); + } + + return ret; + } + + public static HashSet FindRecursiveOrReusedTypes(this Type forType) + { + var recursive = Utils.FindRecursiveTypes(forType); + var reusedTypes = Utils.FindReusedTypes(forType); + + return new HashSet(recursive.Concat(reusedTypes)); + } + + public static HashSet FindChildTypes(this Type forType) + { + var ret = new HashSet(); + var seen = new HashSet(); + var pending = new Stack(); + + pending.Push(forType); + + while (pending.Any()) + { + var cur = pending.Pop(); + seen.Add(cur); + + if (seen.Contains(cur)) + { + // already visited + continue; + } + + if (cur.IsPrimitiveType()) + { + // no members + continue; + } + + if (cur.IsNullableType()) + { + // nullables shouldn't be serialized directly + + var underlyingType = Nullable.GetUnderlyingType(cur); + if (!seen.Contains(underlyingType)) + { + pending.Push(underlyingType); + } + + continue; + } + + if (cur.IsListType()) + { + ret.Add(cur); + + var listI = cur.GetListInterface(); + var valType = listI.GetGenericArguments()[0]; + if (!seen.Contains(valType)) + { + pending.Push(valType); + } + + continue; + } + + if (cur.IsDictionaryType()) + { + ret.Add(cur); + + var dictI = cur.GetDictionaryInterface(); + var valType = dictI.GetGenericArguments()[1]; + if (!seen.Contains(valType)) + { + pending.Push(valType); + } + + continue; + } + + if (cur.IsEnumerableType()) + { + ret.Add(cur); + + + var enumI = cur.GetEnumerableInterface(); + var valType = enumI.GetGenericArguments()[0]; + if (!seen.Contains(valType)) + { + pending.Push(valType); + } + + continue; + } + + foreach (var field in cur.GetFields(BindingFlags.Instance | BindingFlags.Public)) + { + if (!field.ShouldUseMember()) continue; + + if (!seen.Contains(field.FieldType)) + { + pending.Push(field.FieldType); + } + } + + foreach (var prop in cur.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.GetMethod != null)) + { + if (!prop.ShouldUseMember()) continue; + + if (!seen.Contains(prop.PropertyType)) + { + pending.Push(prop.PropertyType); + } + } + } + + ret.Remove(forType); + + return ret; + } + } +} diff --git a/vendor/Jil/Common/FlagsEnumCombiner.cs b/vendor/Jil/Common/FlagsEnumCombiner.cs new file mode 100644 index 000000000..1d2c7695b --- /dev/null +++ b/vendor/Jil/Common/FlagsEnumCombiner.cs @@ -0,0 +1,65 @@ +using Sigil; +using System; +using System.Collections; + +namespace Jil.Common +{ + class FlagsEnumCombiner + where TEnum : struct + { + public static readonly Func Combine; + + static FlagsEnumCombiner() + { + { + var emit = Emit>.NewDynamicMethod(doVerify: Utils.DoVerify); + emit.LoadArgument(0); // enum + emit.LoadArgument(1); // enum enum + emit.Or(); // enum + emit.Return(); // --empty-- + + Combine = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + } + } + } + + class FlagsEnumCombiner + { + delegate void CombineInPlaceDelegate(object newFlag, object accumFlag); + static readonly Hashtable CombineInPlaceCache = new Hashtable(); + + public static void CombineInPlace(Type enumType, object a, object b) + { + var cached = (CombineInPlaceDelegate)CombineInPlaceCache[enumType]; + if (cached != null) + { + cached(a, b); + return; + } + + var emit = Emit.NewDynamicMethod(doVerify: Utils.DoVerify); + emit.LoadArgument(1); // object + emit.Unbox(enumType); // enum& + emit.LoadArgument(0); // enum& object + emit.UnboxAny(enumType); // enum& enum + emit.LoadArgument(1); // enum& enum object + emit.UnboxAny(enumType); // enum& enum enum + emit.Or(); // enum& enum + emit.StoreObject(enumType); // --empty-- + emit.Return(); + + var newDel = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + + lock (CombineInPlaceCache) + { + cached = (CombineInPlaceDelegate)CombineInPlaceCache[enumType]; + if (cached == null) + { + CombineInPlaceCache[enumType] = cached = newDel; + } + } + + cached(a, b); + } + } +} diff --git a/vendor/Jil/Common/PeekSupportingTextReader.cs b/vendor/Jil/Common/PeekSupportingTextReader.cs new file mode 100644 index 000000000..e46af6cd4 --- /dev/null +++ b/vendor/Jil/Common/PeekSupportingTextReader.cs @@ -0,0 +1,43 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Common +{ + class PeekSupportingTextReader : TextReader + { + TextReader Inner; + + int? Peeked; + + public PeekSupportingTextReader(TextReader inner) + { + Inner = inner; + } + + public override int Peek() + { + if (Peeked != null) return Peeked.Value; + + Peeked = Inner.Read(); + + return Peeked.Value; + } + + public override int Read() + { + if (Peeked != null) + { + var ret = Peeked.Value; + Peeked = null; + + return ret; + } + + return Inner.Read(); + } + } +} diff --git a/vendor/Jil/Common/UnionCharsetArrays.cs b/vendor/Jil/Common/UnionCharsetArrays.cs new file mode 100644 index 000000000..9090e056f --- /dev/null +++ b/vendor/Jil/Common/UnionCharsetArrays.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Common +{ + static class UnionCharsetArrays + { + public static readonly IEnumerable UnionSignedSet = new[] { '-' }; + public static readonly IEnumerable UnionNumberSet = new[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; + public static readonly IEnumerable UnionStringySet = new[] { '"' }; + public static readonly IEnumerable UnionBoolSet = new[] { 't', 'f' }; + public static readonly IEnumerable UnionObjectSet = new[] { '{' }; + public static readonly IEnumerable UnionListySet = new[] { '[' }; + + /// + /// Special case, this shouldn't be used in conjuction with types like string or int?; only for the exact null value. + /// + public static readonly IEnumerable UnionNull = new[] { 'n' }; + } +} diff --git a/vendor/Jil/Common/UnionCharsets.cs b/vendor/Jil/Common/UnionCharsets.cs new file mode 100644 index 000000000..1fe7a9077 --- /dev/null +++ b/vendor/Jil/Common/UnionCharsets.cs @@ -0,0 +1,23 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Common +{ + [Flags] + internal enum UnionCharsets : byte + { + None = 0, + + Signed = 1, + Number = 2, + Stringy = 4, + Bool = 8, + Object = 16, + Listy = 32, + + Null = 128 + } +} diff --git a/vendor/Jil/Common/Utils.cs b/vendor/Jil/Common/Utils.cs new file mode 100644 index 000000000..1b95c451a --- /dev/null +++ b/vendor/Jil/Common/Utils.cs @@ -0,0 +1,1719 @@ +using Sigil; +using Sigil.NonGeneric; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Runtime.Serialization; +using System.Text; +using System.Threading.Tasks; +using System.Runtime.CompilerServices; + +namespace Jil.Common +{ + class Utils + { +#if DEBUG + public const bool DoVerify = true; +#else + public const bool DoVerify = false; +#endif + public const OptimizationOptions DelegateOptimizationOptions = OptimizationOptions.All & ~OptimizationOptions.EnableBranchPatching; + + public const string ExceptionDataKeyPrefix = "Jil-"; + public const string ExceptionMessageDataKey = ExceptionDataKeyPrefix + nameof(Exception.Message); + + public const int MAX_IL_INSTRUCTION_LIMIT = 20_000; + + private static readonly Dictionary OneByteOps; + private static readonly Dictionary TwoByteOps; + + static Utils() + { + var oneByte = new List(); + var twoByte = new List(); + + foreach (var field in typeof(OpCodes).GetFields(BindingFlags.Public | BindingFlags.Static)) + { + var op = (OpCode)field.GetValue(null); + + if (op.Size == 1) + { + oneByte.Add(op); + continue; + } + + if (op.Size == 2) + { + twoByte.Add(op); + continue; + } + + throw new Exception("Unexpected op size for " + op); + } + + OneByteOps = oneByte.ToDictionary(d => (int)d.Value, d => d); + TwoByteOps = twoByte.ToDictionary(d => (int)(d.Value & 0xFF), d => d); + } + + // The Experiments project was used to find these #s + // Basically, based on some limited testing it appears that this order of + // member access is the "fastest" most often given the buckets I've chosen to use. + // I make no claims that this is absolutely ideal, but it appears to be better than + // declaration order. + internal static int[] MemberOrdering = new int[] { -1, 3, 4, -2 }; + + public static List> IdealMemberOrderForWriting(Type forType, IEnumerable recursiveTypes, IEnumerable> members) + { + var fields = Utils.FieldOffsetsInMemory(forType); + var props = Utils.PropertyFieldUsage(forType); + + var simpleTypes = members.Where(m => m.First().ReturnType().IsValueType() && !m.First().ReturnType().IsNullableType() && m.First().ReturnType().IsPrimitiveType()).ToList(); + var otherPrimitive = members.Where(m => (m.First().ReturnType().IsPrimitiveType() || m.First().ReturnType().IsNullableType()) && !simpleTypes.Contains(m)).ToList(); + var recursive = members.Where(m => recursiveTypes.Contains(m.First().ReturnType()) && !simpleTypes.Contains(m) && !otherPrimitive.Contains(m)).ToList(); + var everythingElse = members.Where(m => !simpleTypes.Contains(m) && !otherPrimitive.Contains(m) && !recursive.Contains(m)).ToList(); + + Func, int> byAccessOrder = + ms => + { + var m = ms.First(); + + var asField = m as FieldInfo; + if (asField != null) + { + int fieldAddr; + if (fields.TryGetValue(asField, out fieldAddr)) + { + return fieldAddr; + } + + return int.MaxValue; + } + + var asProp = m as PropertyInfo; + if (asProp != null) + { + List usesFields; + if (!props.TryGetValue(asProp, out usesFields)) + { + return int.MaxValue; + } + + if (usesFields.Count == 0) return int.MaxValue; + + return + usesFields.Select( + f => + { + int fieldAdd; + if (fields.TryGetValue(f, out fieldAdd)) + { + return fieldAdd; + } + + return int.MaxValue; + } + ).Min(); + } + + return int.MaxValue; + }; + + Func, int> fieldsFirst = + ms => + { + var m = ms.First(); + + return m is FieldInfo ? 0 : 1; + }; + + var ret = new List>(); + + foreach (var ix in MemberOrdering) + { + var asc = ix > 0; + var i = Math.Abs(ix); + + switch (i) + { + case 1: + ret.AddRange( + asc ? + simpleTypes.OrderBy(byAccessOrder).ThenBy(fieldsFirst) : + simpleTypes.OrderByDescending(byAccessOrder).ThenByDescending(fieldsFirst) + ); + break; + + case 2: + ret.AddRange( + asc ? + otherPrimitive.OrderBy(byAccessOrder).ThenBy(fieldsFirst) : + otherPrimitive.OrderByDescending(byAccessOrder).ThenByDescending(fieldsFirst) + ); + break; + + case 3: + ret.AddRange( + asc ? + everythingElse.OrderBy(byAccessOrder).ThenBy(fieldsFirst) : + everythingElse.OrderByDescending(byAccessOrder).ThenByDescending(fieldsFirst) + ); + break; + + case 4: + ret.AddRange( + asc ? + recursive.OrderBy(byAccessOrder).ThenBy(fieldsFirst) : + recursive.OrderByDescending(byAccessOrder).ThenByDescending(fieldsFirst) + ); + break; + + default: throw new Exception(); + } + } + + return ret; + } + + public static Dictionary> PropertyFieldUsage(Type t) + { +#if NETSTANDARD1_6 + return new Dictionary>(); +#else + var ret = new Dictionary>(); + + var props = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic).Where(p => p.GetMethod != null && p.GetMethod.GetParameters().Count() == 0); + + var module = t.Module(); + + foreach (var prop in props) + { + try + { + var getMtd = prop.GetMethod; + + var fieldHandles = _GetFieldHandles(getMtd); + + var fieldInfos = + fieldHandles + .Select( + f => + { + var genArgs = t.GetGenericArguments(); + + return module.ResolveField(f, genArgs, null); + } + ).ToList(); + + ret[prop] = fieldInfos; + } + catch { /* Anything that goes wrong in here, we can't really do anything about; just continue with less knowledge */ } + } + + return ret; +#endif + } + + public static List> Decompile(MethodBase mtd) + { +#if NETSTANDARD1_6 + return null; +#else + var mtdBody = mtd.GetMethodBody(); + if (mtdBody == null) return null; + var cil = mtdBody.GetILAsByteArray(); + if (cil == null) return null; + + var ret = new List>(); + + int i = 0; + while (i < cil.Length) + { + int? fieldHandle; + OpCode opcode; + int? intOperand; + long? longOperand; + double? doubleOperand; + i += _ReadOp(cil, i, out fieldHandle, out opcode, out intOperand, out longOperand, out doubleOperand); + + FieldInfo field = null; + if (fieldHandle.HasValue) + { + var genArguments = mtd.DeclaringType.GetGenericArguments(); + + field = mtd.Module.ResolveField(fieldHandle.Value, genArguments, null); + } + + ret.Add(Tuple.Create(opcode, intOperand, longOperand, doubleOperand, field)); + } + + return ret; +#endif + } + + private static List _GetFieldHandles(MethodInfo mtd) + { +#if NETSTANDARD1_6 + return new List(); +#else + var mtdBody = mtd.GetMethodBody(); + var cil = mtdBody.GetILAsByteArray(); + + var ret = new List(); + + int i = 0; + while (i < cil.Length) + { + int? fieldHandle; + OpCode ignoredOp; + int? ignored1; + long? ignored2; + double? ignored3; + i += _ReadOp(cil, i, out fieldHandle, out ignoredOp, out ignored1, out ignored2, out ignored3); + + if (fieldHandle.HasValue) + { + ret.Add(fieldHandle.Value); + } + } + + return ret; +#endif + } + + private static int _ReadOp(byte[] cil, int ix, out int? fieldHandle, out OpCode opcode, out int? intOperand, out long? longOperand, out double? doubleOperand) + { + const byte ContinueOpcode = 0xFE; + + int advance = 0; + + byte first = cil[ix]; + + if (first == ContinueOpcode) + { + var next = cil[ix + 1]; + + opcode = TwoByteOps[next]; + advance += 2; + } + else + { + opcode = OneByteOps[first]; + advance++; + } + + fieldHandle = _ReadFieldOperands(opcode, cil, ix, ix + advance, ref advance, out intOperand, out longOperand, out doubleOperand); + + return advance; + } + + private static int? _ReadFieldOperands(OpCode op, byte[] cil, int instrStart, int operandStart, ref int advance, out int? constantInt, out long? constantLong, out double? constantDouble) + { + Func readInt = (at) => cil[at] | (cil[at + 1] << 8) | (cil[at + 2] << 16) | (cil[at + 3] << 24); + Func readLong = + (at) => + { + var a = (uint)(cil[at] | (cil[at + 1] << 8) | (cil[at + 2] << 16) | (cil[at + 3] << 24)); + var b = (uint)(cil[at+4] | (cil[at + 5] << 8) | (cil[at + 6] << 16) | (cil[at + 7] << 24)); + + return (((long)b) << 32) | a; + }; + Func readDouble = + (at) => + { + var arr = new byte[8]; + arr[0] = cil[at]; + arr[1] = cil[at + 1]; + arr[2] = cil[at + 2]; + arr[3] = cil[at + 3]; + arr[4] = cil[at + 4]; + arr[5] = cil[at + 5]; + arr[6] = cil[at + 6]; + arr[7] = cil[at + 7]; + + if (!BitConverter.IsLittleEndian) + { + Array.Reverse(arr); + } + + return BitConverter.ToDouble(arr, 0); + }; + Func readFloat = + (at) => + { + var arr = new byte[4]; + arr[0] = cil[at]; + arr[1] = cil[at + 1]; + arr[2] = cil[at + 2]; + arr[3] = cil[at + 3]; + + if (!BitConverter.IsLittleEndian) + { + Array.Reverse(arr); + } + + return BitConverter.ToSingle(arr, 0); + }; + + constantInt = null; + constantLong = null; + constantDouble = null; + + switch (op.OperandType) + { + case OperandType.InlineBrTarget: + advance += 4; + return null; + + case OperandType.InlineSwitch: + advance += 4; + var len = readInt(operandStart); + for (var i = 0; i < len; i++) + { + advance += 4; + } + return null; + + case OperandType.ShortInlineBrTarget: + advance += 1; + return null; + + case OperandType.InlineField: + advance += 4; + var field = readInt(operandStart); + return field; + + case OperandType.InlineTok: + case OperandType.InlineType: + case OperandType.InlineMethod: + advance += 4; + return null; + + case OperandType.InlineI: + advance += 4; + constantInt = readInt(operandStart); + return null; + + case OperandType.InlineI8: + advance += 8; + constantLong = readLong(operandStart); + return null; + + case OperandType.InlineNone: + return null; + + case OperandType.InlineR: + advance += 8; + constantDouble = readDouble(operandStart); + return null; + + case OperandType.InlineSig: + advance += 4; + return null; + + case OperandType.InlineString: + advance += 4; + constantInt = readInt(operandStart); + return null; + + case OperandType.InlineVar: + advance += 2; + constantInt = cil[operandStart]; + return null; + + case OperandType.ShortInlineI: + advance += 1; + constantInt = cil[operandStart]; + return null; + + case OperandType.ShortInlineR: + advance += 4; + constantDouble = readFloat(operandStart); + return null; + + case OperandType.ShortInlineVar: + advance += 1; + constantInt = cil[operandStart]; + return null; + + default: throw new Exception("Unexpected operand type [" + op.OperandType + "]"); + } + } + + public static Dictionary FieldOffsetsInMemory(Type t) + { + try + { + var fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); + + var emit = Emit>.NewDynamicMethod("_GetOffsetsInMemory" + t.FullName); + var retLoc = emit.DeclareLocal("ret"); + + emit.LoadConstant(fields.Length); // ulong + emit.NewArray(typeof(ulong)); // ulong[] + emit.StoreLocal(retLoc); // --empty-- + + for (var i = 0; i < fields.Length; i++) + { + var field = fields[i]; + + emit.LoadLocal(retLoc); // ulong[] + emit.LoadConstant(i); // ulong[] ulong + + emit.LoadArgument(0); // ulong[] ulong param#0 + emit.CastClass(t); // ulong[] ulong param#0 + + emit.LoadFieldAddress(field); // ulong[] ulong field& + emit.Convert(); // ulong[] ulong ulong + + emit.StoreElement(); // --empty-- + } + + emit.LoadLocal(retLoc); // ulong[] + emit.Return(); // --empty-- + + var getAddrs = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + + var cons = t.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).OrderBy(p => p.GetParameters().Count()).FirstOrDefault(); + var consParameters = cons != null ? cons.GetParameters().Select(p => p.ParameterType.DefaultValue()).ToArray() : null; + + object obj; + if (cons != null) + { + obj = cons.Invoke(consParameters); + } + else + { + obj = Activator.CreateInstance(t); + } + + var addrs = getAddrs(obj); + + if (addrs.Length == 0) + { + return new Dictionary(); + } + + var min = addrs.Min(); + + var ret = new Dictionary(); + + for (var i = 0; i < fields.Length; i++) + { + var field = fields[i]; + + var addr = addrs[i]; + var offset = addr - min; + + ret[field] = (int)offset; + } + + return ret; + } + catch + { + // A lot can go wrong during this, and the common response is just to bail + // This catch is much simpler than trying (and probably failing) to enumerate + // all the exceptional cases + return new Dictionary(); + } + } + + /// + /// This returns a map of "name of member" => [Type of member, index of argument to constructor]. + /// We need this for anonymous types because we can't set properties (they're read-only). + /// + public static Dictionary> GetAnonymousNameToConstructorMap(Type objType) + { + var cons = objType.GetConstructors().Single(); + var consInstrs = Utils.Decompile(cons); + + if (consInstrs != null) + { + return GetAnonymousNameToConstructorMap_Decompile(objType, cons, consInstrs); + } + + // If we're in a case where the decompiler isn't available (right now, that means you NETCORE) + // then we fall back to guessing. + // It's possible to fail here, which sucks, but is better than just not deserializing + // anonymous types + + return GetAnonymousNameToConstructorMap_Guess(objType, cons); + } + + /// + /// This returns a map of "name of member" => [Type of member, index of argument to constructor]. + /// We need this for anonymous types because we can't set properties (they're read-only). + /// + /// How this works is kind of fun. + /// + /// By spec, the arguments to the constructor are in declaration order for an anonymous type. + /// So: new { A, B, C } => new SomeType(A a, B b, C c) + /// + /// However there is no way to get declaration order via reflection, it's just not data that's + /// preserved. Furthermore, the names of backing fields for those read-only properties are not + /// defined by the spec. + /// + /// IF we have decompliation facilities, then we can do this "properly" (see GetAnonymousNameToConstructorMap_Decompile). + /// But if we don't, we can still take a decent guess. + /// + /// First, group properties by type. If there are no duplicate types, then there's a one-to-one mapping between + /// each parameter to the constructor and each property. + /// + /// For groups with multiple properties, compare the names of the property and the constructor parameter. Take + /// exact matches, assuming there aren't any collisions (don't think that's possible, but just in case...). + /// + /// This sort of exact matching isn't supported by the spec at all, but works for current implementations so + /// as long as there's a "oh shit, invariant broken"-bail I'm OK with it. + /// + static Dictionary> GetAnonymousNameToConstructorMap_Guess(Type objType, ConstructorInfo cons) + { + var props = objType.GetProperties(); + var conParams = cons.GetParameters(); + + var remainingProps = new List(); + remainingProps.AddRange(props); + + var remainingParams = new List(); + remainingParams.AddRange(conParams); + + var propertyToParam = new Dictionary(); + + foreach (var group in remainingProps.GroupBy(p => p.PropertyType).ToList()) + { + if (group.Count() == 1) + { + var prop = group.ElementAt(0); + var param = conParams.Single(p => p.ParameterType == prop.PropertyType); + + propertyToParam[prop] = param; + + remainingProps.Remove(prop); + } + } + + var keepTrying = remainingProps.Count > 0; + + while (keepTrying) + { + keepTrying = false; + + foreach (var group in remainingProps.GroupBy(p => p.PropertyType).ToList()) + { + var propType = group.Key; + + var candidateParams = remainingParams.Where(p => p.ParameterType == propType).ToList(); + + foreach (var prop in group) + { + var exactMatch = candidateParams.Where(p => p.Name == prop.Name).ToList(); + if (exactMatch.Count == 1) + { + var matchingParam = exactMatch[0]; + propertyToParam[prop] = matchingParam; + + remainingProps.Remove(prop); + + remainingParams.Remove(matchingParam); + candidateParams.Remove(matchingParam); + + keepTrying = true; + } + } + } + } + + if (remainingProps.Count > 0) + { + throw new ConstructionException("Due to a limitation in .netcore - could not guess property <-> parameter mapping necessary to deserialize an anonymous type"); + } + + var ret = new Dictionary>(); + + foreach (var prop in props) + { + var pairedParam = propertyToParam[prop]; + var paramIndex = Array.IndexOf(conParams, pairedParam); + ret[prop.Name] = Tuple.Create(prop.PropertyType, -1); + } + + return ret; + } + + /// + /// This returns a map of "name of member" => [Type of member, index of argument to constructor]. + /// We need this for anonymous types because we can't set properties (they're read-only). + /// + /// How this works is kind of fun. + /// + /// By spec, the arguments to the constructor are in declaration order for an anonymous type. + /// So: new { A, B, C } => new SomeType(A a, B b, C c) + /// + /// However there is no way to get declaration order via reflection, it's just not data that's + /// preserved. Furthermore, the names of backing fields for those read-only properties are not + /// defined by the spec. + /// + /// So I got clever. + /// + /// This method decompiles the constructor to find out which fields are set by which arguments (by index). + /// It then decompiles all properties to find out which fields back which properties. + /// Then it finally works backwards from each property, taking the property's name type and using it's backing + /// field to lookup which index to pass it in as when constructing the anonymous object. + /// + static Dictionary> GetAnonymousNameToConstructorMap_Decompile(Type objType, ConstructorInfo cons, List> consInstrs) + { + var fieldToArgumentIndex = new Dictionary(); + + var fields = objType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic); + + foreach (var field in fields) + { + var storeInstr = consInstrs.FindIndex(d => d.Item1 == OpCodes.Stfld && d.Item5 == field); + var preceedingLdArg = consInstrs.Take(storeInstr).Reverse().First(f => f.Item1.IsLoadArgumentOpCode()); + + int paramIx; + switch (preceedingLdArg.Item1.Value) + { + // Ldarg_0 will be `this`, so we'll never see it + + // Ldarg_1 + case 0x03: paramIx = 1; break; + // Ldarg_2 + case 0x04: paramIx = 2; break; + // Ldarg_3 + case 0x05: paramIx = 3; break; + + // Ldarg, Ldarg_S + default: paramIx = preceedingLdArg.Item2.Value; break; + } + + fieldToArgumentIndex[field] = paramIx; + } + + var propertyToBackingField = new Dictionary(); + foreach (var prop in objType.GetProperties()) + { + var propInstrs = Utils.Decompile(prop.GetMethod); + var backingField = propInstrs.Single(p => p.Item1 == OpCodes.Ldfld); + + propertyToBackingField[prop] = backingField.Item5; + } + + var nameToTypeAndConsIndex = + propertyToBackingField + .ToDictionary( + d => d.Key.Name, + d => Tuple.Create(d.Key.PropertyType, fieldToArgumentIndex[d.Value] - 1) // -1 here because `this` adds 1 in the IL + ); + + return nameToTypeAndConsIndex; + } + + static MethodInfo DynamicProjectTo = typeof(Utils).GetMethod("_DynamicProjectTo", BindingFlags.NonPublic | BindingFlags.Static); + static IEnumerable _DynamicProjectTo(IEnumerable e) + { + return e.Cast(); + } + + static System.Collections.Hashtable DynamicCastCache = new System.Collections.Hashtable(); + public static object DynamicProject(IEnumerable e, Type castElementsTo) + { + var cached = (Func, object>)DynamicCastCache[castElementsTo]; + if (cached == null) + { + var mtd = DynamicProjectTo.MakeGenericMethod(castElementsTo); + var emit = Sigil.Emit, object>>.NewDynamicMethod(); + emit.LoadArgument(0); + emit.Call(mtd); + emit.Return(); + cached = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + + lock (DynamicCastCache) + { + DynamicCastCache[castElementsTo] = cached; + } + } + + return cached(e); + } + + static MethodInfo ProjectToStringDictionary = typeof(Utils).GetMethod("_ProjectToStringDictionary", BindingFlags.Static | BindingFlags.NonPublic); + static object _ProjectToStringDictionary(IDictionary real) + { + var ret = new Dictionary(); + foreach (var kv in real) + { + ret[(string)kv.Key] = (T)kv.Value; + } + + return ret; + } + + static System.Collections.Hashtable StringDictionaryCache = new System.Collections.Hashtable(); + public static object ProjectStringDictionary(IDictionary inner, Type valType) + { + var cached = (Func, object>)StringDictionaryCache[valType]; + if (cached == null) + { + var mtd = ProjectToStringDictionary.MakeGenericMethod(valType); + var emit = Sigil.Emit, object>>.NewDynamicMethod(); + emit.LoadArgument(0); + emit.Call(mtd); + emit.Return(); + + cached = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + lock (StringDictionaryCache) + { + StringDictionaryCache[valType] = cached; + } + } + + return cached(inner); + } + + static MethodInfo ProjectToEnumDictionary = typeof(Utils).GetMethod("_ProjectToEnumDictionary", BindingFlags.Static | BindingFlags.NonPublic); + static object _ProjectToEnumDictionary(IDictionary real) + where TEnum : struct + { + var ret = new Dictionary(); + foreach (var kv in real) + { + ret[(TEnum)kv.Key] = (TValue)kv.Value; + } + + return ret; + } + + static System.Collections.Hashtable EnumDictionaryCache = new System.Collections.Hashtable(); + public static object ProjectEnumDictionary(IDictionary inner, Type keyType, Type valType) + { + var cached = (Func, object>)EnumDictionaryCache[valType]; + if (cached == null) + { + var mtd = ProjectToEnumDictionary.MakeGenericMethod(keyType, valType); + var emit = Sigil.Emit, object>>.NewDynamicMethod(); + emit.LoadArgument(0); + emit.Call(mtd); + emit.Return(); + + cached = emit.CreateDelegate(Utils.DelegateOptimizationOptions); + lock (EnumDictionaryCache) + { + EnumDictionaryCache[valType] = cached; + } + } + + return cached(inner); + } + + class Node + { + public T Value { get; set; } + + List> Childern = new List>(); + + public Node(T value) + { + Value = value; + } + + public void AddChild(Node child) + { + Childern.Add(child); + } + + bool CanReachImpl(T lookingFor, HashSet alreadySeen) + { + if (lookingFor.Equals(Value)) return true; + + foreach (var child in Childern) + { + // loop, but not the one we're looking for... + if (alreadySeen.Contains(child.Value)) continue; + + var copy = new HashSet(alreadySeen); + copy.Add(Value); + + if (child.CanReachImpl(lookingFor, copy)) return true; + } + + return false; + } + + public bool CanReach(Node otherNode) + { + return CanReachImpl(otherNode.Value, new HashSet()); + } + } + + public static HashSet FindRecursiveTypes(Type rootType) + { + var lookup = new Dictionary>(); + + var pending = new Stack>(); + var ret = new HashSet(); + + Action> addIfReachable = + (seenType, curNode) => + { + if (seenType.IsNullableType()) + { + seenType = Nullable.GetUnderlyingType(seenType); + } + else + { + if (seenType.IsListType()) + { + var listI = seenType.GetListInterface(); + seenType = listI.GetGenericArguments()[0]; + } + else + { + if (seenType.IsDictionaryType()) + { + var dictI = seenType.GetDictionaryInterface(); + seenType = dictI.GetGenericArguments()[1]; + } + else + { + if (seenType.IsEnumerableType()) + { + var enumI = seenType.GetEnumerableInterface(); + seenType = enumI.GetGenericArguments()[0]; + } + } + } + } + + Node olderNode; + if (lookup.TryGetValue(seenType, out olderNode)) + { + if (olderNode.CanReach(curNode)) + { + ret.Add(seenType); + } + } + else + { + olderNode = new Node(seenType); + + if (curNode != null) + { + curNode.AddChild(olderNode); + } + + lookup[seenType] = olderNode; + pending.Push(olderNode); + } + }; + + addIfReachable(rootType, null); + + while (pending.Count > 0) + { + var curNode = pending.Pop(); + var curType = curNode.Value; + + // these can't have members, bail + if (curType.IsPrimitiveType() || curType.IsEnum()) continue; + + if (curType.IsNullableType()) + { + var underlyingType = Nullable.GetUnderlyingType(curType); + addIfReachable(underlyingType, curNode); + + continue; + } + + if (curType.IsListType()) + { + var listI = curType.GetListInterface(); + var valType = listI.GetGenericArguments()[0]; + addIfReachable(valType, curNode); + continue; + } + + if (curType.IsDictionaryType()) + { + var dictI = curType.GetDictionaryInterface(); + var valType = dictI.GetGenericArguments()[1]; + addIfReachable(valType, curNode); + continue; + } + + if (curType.IsEnumerableType()) + { + var enumI = curType.GetEnumerableInterface(); + var valType = enumI.GetGenericArguments()[0]; + addIfReachable(valType, curNode); + continue; + } + + foreach (var field in curType.GetFields(BindingFlags.Instance | BindingFlags.Public)) + { + if (field.ShouldUseMember()) + { + addIfReachable(field.FieldType, curNode); + } + } + + foreach (var prop in curType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.GetMethod != null)) + { + if (prop.ShouldUseMember()) + { + addIfReachable(prop.PropertyType, curNode); + } + } + } + + return ret; + } + + public static List FindReusedTypes(Type rootType) + { + var pending = new Stack(); + pending.Push(rootType); + + var counts = new Dictionary(); + + Action pushIfNew = + type => + { + if (!counts.ContainsKey(type) || counts[type] < 2) + { + pending.Push(type); + } + }; + + while (pending.Count > 0) + { + var curType = pending.Pop(); + + // these can't have members, bail + if (curType.IsPrimitiveType() || curType.IsEnum()) continue; + + if (!counts.ContainsKey(curType)) counts[curType] = 0; + counts[curType]++; + + if (curType.IsNullableType()) + { + var underlyingType = Nullable.GetUnderlyingType(curType); + + pushIfNew(underlyingType); + + continue; + } + + if (curType.IsListType()) + { + var listI = curType.GetListInterface(); + var valType = listI.GetGenericArguments()[0]; + pushIfNew(valType); + continue; + } + + if (curType.IsDictionaryType()) + { + var dictI = curType.GetDictionaryInterface(); + var valType = dictI.GetGenericArguments()[1]; + pushIfNew(valType); + continue; + } + + if (curType.IsEnumerableType()) + { + var enumI = curType.GetEnumerableInterface(); + var valType = enumI.GetGenericArguments()[0]; + pushIfNew(valType); + continue; + } + + foreach (var field in curType.GetFields(BindingFlags.Instance | BindingFlags.Public)) + { + if (field.ShouldUseMember()) + { + pushIfNew(field.FieldType); + } + } + + foreach (var prop in curType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(p => p.GetMethod != null)) + { + if (prop.ShouldUseMember()) + { + pushIfNew(prop.PropertyType); + } + } + } + + var reused = counts.Where(kv => kv.Value > 1).Select(kv => kv.Key).ToList(); + + return + reused + .Where( + r => !(r.IsPrimitiveType() || // all the types we handle extra specially + r.IsEnum() || + r.IsNullableType() || + r.IsListType() || + r.IsDictionaryType() || + r.IsReadOnlyListType() || + r.IsReadOnlyDictionaryType() || + r.IsEnumerableType() || + r.IsCollectionType()) + ) + .ToList(); + } + + public static string SafeConvertFromUtf32(int utf32) + { + if (utf32 > 0x10ffff || (utf32 >= 0x00d800 && utf32 <= 0x00dfff)) + { + return ((char)utf32).ToString(); + } + + return char.ConvertFromUtf32(utf32); + } + + public static bool LoadConstantOfType(Emit emit, object val, Type type) + { + if (type == typeof(byte)) + { + try + { + var v = (byte)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (byte?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(sbyte)) + { + try + { + var v = (sbyte)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (sbyte?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(short)) + { + try + { + var v = (short)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (short?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(ushort)) + { + try + { + var v = (ushort)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (ushort?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(int)) + { + try + { + var v = (int)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (int?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(uint)) + { + try + { + var v = (uint)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (uint?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(long)) + { + try + { + var v = (long)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (long?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(ulong)) + { + try + { + var v = (ulong)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (ulong?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + return false; + } + + public static bool LoadConstantOfType(Emit emit, object val, Type type) + { + if (type == typeof(byte)) + { + try + { + var v = (byte)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (byte?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(sbyte)) + { + try + { + var v = (sbyte)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (sbyte?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(short)) + { + try + { + var v = (short)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (short?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(ushort)) + { + try + { + var v = (ushort)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (ushort?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(int)) + { + try + { + var v = (int)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (int?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(uint)) + { + try + { + var v = (uint)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (uint?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(long)) + { + try + { + var v = (long)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (long?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + if (type == typeof(ulong)) + { + try + { + var v = (ulong)val; + emit.LoadConstant(v); + return true; + } + catch { } + + try + { + var v = (ulong?)val; + emit.LoadConstant(v.Value); + return true; + } + catch { } + + return false; + } + + return false; + } + + private static long[] PowersOf10 = new[] + { + 1L, + 10L, + 100L, + 1000L, + 10000L, + 100000L, + 1000000L, + 10000000L, + 100000000L + }; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static long Pow10(int power) + { + if (power < PowersOf10.Length) + return PowersOf10[power]; + return (long)Math.Pow(10, power); + } + + public static bool CheckUnionLegality(DateTimeFormat dateFormat, string memberName, IEnumerable possible, out Dictionary discriminantChars, out MemberInfo destinationType, out Dictionary charsetToMember, out bool allowsNull, out string errorMessage) + { + charsetToMember = new Dictionary(); + allowsNull = false; + destinationType = null; + + var charsToMembers = new Dictionary>(); + + foreach (var member in possible) + { + var attr = member.GetCustomAttribute(); + if (attr == null || !attr.IsUnion) + { + discriminantChars = null; + errorMessage = "Member [" + member.Name + "] isn't marked as part of a union, but other members share the same Name [" + memberName + "]"; + return false; + } + + if (attr.IsUnionType) + { + if (member.ReturnType() != typeof(Type)) + { + discriminantChars = null; + errorMessage = "Member [" + member.Name + "] has IsUnionType set, but is not of type System.Type"; + return false; + } + + var asProp = member as PropertyInfo; + if (asProp != null && asProp.SetMethod == null) + { + discriminantChars = null; + errorMessage = "Member [" + member.Name + "] has IsUnionType set, but has no set method"; + return false; + } + + if (destinationType != null) + { + discriminantChars = null; + errorMessage = "Member [" + member.Name + "] has IsUnionType set, but IsUnionType is also set for [" + destinationType.Name + "]"; + return false; + } + + destinationType = member; + continue; + } + + var memberType = member.ReturnType(); + if (!memberType.IsValueType() || memberType.IsNullableType()) + { + allowsNull = true; + } + + UnionCharsets perMember; + var dis = GetDescriminantCharacters(memberType, dateFormat, out perMember); + foreach (var e in Enum.GetValues(typeof(UnionCharsets)).Cast().Where(x => perMember.HasFlag(x))) + { + charsetToMember[e] = member; + } + + charsetToMember[perMember] = member; + + foreach (var c in dis) + { + List mems; + if (!charsToMembers.TryGetValue(c, out mems)) + { + charsToMembers[c] = mems = new List(); + } + + mems.Add(member); + } + } + + var ambiguousCharsToMembers = charsToMembers.Where(kv => kv.Value.Count > 1).ToDictionary(kv => kv.Key, kv => new MemberGroup(kv.Value)); + if(ambiguousCharsToMembers.Any()) + { + var conflicts = + ambiguousCharsToMembers + .GroupBy(kv => kv.Value) + .Select( + g => + Tuple.Create( + g.Select(kv => kv.Key).Distinct().OrderBy(_ => _).ToList(), + g.Key.Members + ) + ) + .ToList(); + + errorMessage = + string.Join("; ", + conflicts + .Select( + t => + "The members [" + + string.Join(", ", t.Item2.Select(m => m.Name)) + + "] cannot be distiguished in a union because they can each start with these characters [" + + string.Join(", ", t.Item1) + + "]" + ) + .OrderBy(_ => _) + ); + + discriminantChars = null; + return false; + } + + discriminantChars = charsToMembers.ToDictionary(kv => kv.Key, kv => kv.Value.Single()); + errorMessage = null; + return true; + } + + class MemberGroup : IEquatable + { + public List Members {get; private set;} + + public MemberGroup(List members) + { + Members = members; + } + + public void Add(MemberInfo member) + { + Members.Add(member); + } + + public override bool Equals(object other) + { + var asMemberGroup = other as MemberGroup; + if(asMemberGroup == null) return false; + + return Equals(asMemberGroup); + } + + public override int GetHashCode() + { + return Members.Select(m => m.GetHashCode()).OrderBy(_ => _).Aggregate((cur, val) => cur ^ val); + } + + public bool Equals(MemberGroup other) + { + if (other.Members.Count != this.Members.Count) return false; + + return this.Members.All(m => other.Members.Contains(m)); + } + } + + static IEnumerable GetDescriminantCharacters(Type memType, DateTimeFormat dateFormat, out UnionCharsets charsets) + { + charsets = UnionCharsets.None; + + IEnumerable ret = Enumerable.Empty(); + + if (memType.IsNullableType()) + { + memType = Nullable.GetUnderlyingType(memType); + } + + if (memType.IsNumberType()) + { + if (memType.IsSigned() || memType.IsFloatingPointNumberType()) + { + charsets |= UnionCharsets.Signed; + ret = ret.Concat(UnionCharsetArrays.UnionSignedSet); + } + + charsets |= UnionCharsets.Number; + ret = ret.Concat(UnionCharsetArrays.UnionNumberSet); + + return ret; + } + + if (memType.IsStringyType() || memType == typeof(Guid)) + { + charsets |= UnionCharsets.Stringy; + ret = ret.Concat(UnionCharsetArrays.UnionStringySet); + + return ret; + } + + if (memType == typeof(bool)) + { + charsets |= UnionCharsets.Bool; + ret = ret.Concat(UnionCharsetArrays.UnionBoolSet); + + return ret; + } + + if (memType == typeof(DateTime) || memType == typeof(DateTimeOffset) || memType == typeof(TimeSpan)) + { + switch (dateFormat) + { + case DateTimeFormat.RFC1123: + case DateTimeFormat.ISO8601: + case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: + charsets |= UnionCharsets.Stringy; + ret = ret.Concat(UnionCharsetArrays.UnionStringySet); + break; + + case DateTimeFormat.MillisecondsSinceUnixEpoch: + case DateTimeFormat.SecondsSinceUnixEpoch: + charsets |= UnionCharsets.Number; + ret = ret.Concat(UnionCharsetArrays.UnionNumberSet); + break; + + default: throw new Exception("Unexpected DateTimeFormat: " + dateFormat); + } + + return ret; + } + + if (memType.IsEnum()) + { + var attr = memType.GetCustomAttribute(); + if (attr != null && attr.TreatEnumerationAs != null) + { + charsets |= UnionCharsets.Number; + ret = ret.Concat(UnionCharsetArrays.UnionNumberSet); + return ret; + } + + charsets |= UnionCharsets.Stringy; + ret = ret.Concat(UnionCharsetArrays.UnionStringySet); + return ret; + } + + if (memType.IsDictionaryType() || memType.IsGenericReadOnlyDictionary()) + { + charsets |= UnionCharsets.Object; + ret = ret.Concat(UnionCharsetArrays.UnionObjectSet); + return ret; + } + + if (memType.IsListType() || memType.IsGenericEnumerable() || memType.IsGenericReadOnlyList()) + { + charsets |= UnionCharsets.Listy; + ret = ret.Concat(UnionCharsetArrays.UnionListySet); + return ret; + } + + charsets |= UnionCharsets.Object; + ret = ret.Concat(UnionCharsetArrays.UnionObjectSet); + return ret; + } + + /// + /// Functional-style helper method for creating and initializing a new array. + /// + /// The element type of the array. + /// The length of the array to create. + /// + /// The function used to initialize each element of the array. + /// The integer applied to the function represents the index of the element being initialized. + /// + /// An array with element type T and length count. + internal static T[] CreateArray(int count, Func generator) + { + if (count < 0) + { + throw new ArgumentOutOfRangeException("count"); + } + else if (generator == null) + { + throw new ArgumentNullException("generator"); + } + //Contract.EndContractBlock(); + + var arr = new T[count]; + for (var i = 0; i < arr.Length; i++) + { + arr[i] = generator(i); + } + return arr; + } + } +} diff --git a/vendor/Jil/DateTimeFormat.cs b/vendor/Jil/DateTimeFormat.cs new file mode 100644 index 000000000..352e33642 --- /dev/null +++ b/vendor/Jil/DateTimeFormat.cs @@ -0,0 +1,83 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil +{ + /// + /// Specifies the format of DateTimes and TimeSpans produced or expected by Jil. + /// + public enum DateTimeFormat : byte + { + /// + /// Obsolete: Use MicrosoftStyleMillisecondsSinceUnixEpoch instead + /// + /// DateTimes will be formatted as "\/Date(##...##)\/" where ##...## is the + /// number of milliseconds since the unix epoch (January 1st, 1970 UTC). + /// + /// TimeSpans will be formatted as "days.hours:minutes:seconds.fractionalSeconds" + /// + [Obsolete("Use MicrosoftStyleMillisecondsSinceUnixEpoch instead")] + NewtonsoftStyleMillisecondsSinceUnixEpoch = 0, + /// + /// DateTimes will be formatted as ##...##, where ##...## is the number + /// of milliseconds since the unix epoch (January 1st, 1970 UTC). + /// + /// This is format can be passed directly to JavaZcript's Date constructor. + /// + /// TimeSpans will be formatted as ##...##, where ##...## is the TotalMilliseconds + /// property of the TimeSpan. + /// + MillisecondsSinceUnixEpoch = 1, + /// + /// DateTimes will be formatted as ##...##, where ##...## is the number + /// of seconds since the unix epoch (January 1st, 1970 UTC). + /// + /// TimeSpans will be formatted as ##...##, where ##...## is the TotalSeconds + /// property of the TimeSpan. + /// + SecondsSinceUnixEpoch = 2, + /// + /// DateTimes will be formatted as "yyyy-MM-ddThh:mm:ssZ" where + /// yyyy is the year, MM is the month (starting at 01), dd is the day (starting at 01), + /// hh is the hour (starting at 00, continuing to 24), mm is the minute (start at 00), + /// and ss is the second (starting at 00). + /// + /// Examples: + /// 2011-07-14T19:43:37Z + /// 2012-01-02T03:04:05Z + /// + /// TimeSpans will be formatted as ISO8601 durations. + /// + /// Examples: + /// P123DT11H30M2.3S + /// + ISO8601 = 3, + /// + /// DateTimes will be formatted as "ddd, dd MMM yyyy HH:mm:ss GMT" where + /// ddd is the abbreviation of a day, dd is the day (starting at 01), MMM is the abbreviation of a month, + /// yyyy is the year, HH is the hour (starting at 00, continuing to 24), mm is the minute (start at 00), + /// and ss is the second (starting at 00), and GMT is a literal indicating the timezone (always GMT). + /// + /// Examples: + /// Thu, 10 Apr 2008 13:30:00 GMT + /// Tue, 10 Mar 2015 00:14:34 GMT + /// + /// TimeSpans will be formatted as "days.hours:minutes:seconds.fractionalSeconds" + /// + RFC1123 = 4, + /// + /// DateTimes will be formatted as "\/Date(##...##)\/" where ##...## is the + /// number of milliseconds since the unix epoch (January 1st, 1970 UTC). + /// See: https://msdn.microsoft.com/en-us/library/bb299886.aspx + /// + /// Example: + /// "\/Date(628318530718)\/" + /// + /// TimeSpans will be formatted as "days.hours:minutes:seconds.fractionalSeconds" + /// + MicrosoftStyleMillisecondsSinceUnixEpoch = 5 + } +} diff --git a/vendor/Jil/DeserializationException.cs b/vendor/Jil/DeserializationException.cs new file mode 100644 index 000000000..f73288867 --- /dev/null +++ b/vendor/Jil/DeserializationException.cs @@ -0,0 +1,190 @@ +using Jil.Deserialize; +using System; +using System.IO; +using System.Text; +using Jil.Common; + +namespace Jil +{ + /// + /// An exception thrown when Jil encounters an error when deserializing a stream. + /// + public class DeserializationException : Exception + { + long? _Position; + /// + /// The position in the TextReader where an error occurred, if it is available. + /// + /// This is meant for debugging purposes only, as exactly when Jil decides to abandon deserialization + /// and throw an exception is an implementation detail. + /// + public long? Position + { + get { return _Position; } + private set + { + const string dataKey = Utils.ExceptionDataKeyPrefix + nameof(Position); + Data[dataKey] = _Position = value; + } + } + + string _SnippetAfterError; + /// + /// A snippet of text immediately after an error occurred. + /// + /// This is meant for debugging purposes only, as exactly when Jil decides to abandon deserialization + /// and throw an exception is an implementation detail. + /// + public string SnippetAfterError + { + get { return _SnippetAfterError; } + private set + { + const string dataKey = Utils.ExceptionDataKeyPrefix + nameof(SnippetAfterError); + Data[dataKey] = _SnippetAfterError = value; + } + } + + bool _EndedUnexpectedly; + /// + /// Whether or not the TextReader ended sooner than Jil expected. + /// + /// This is meant for debugging purposes only, as exactly when Jil decides to abandon deserialization + /// and throw an exception is an implementation detail. + /// + public bool EndedUnexpectedly + { + get { return _EndedUnexpectedly; } + private set + { + const string dataKey = Utils.ExceptionDataKeyPrefix + nameof(EndedUnexpectedly); + Data[dataKey] = _EndedUnexpectedly = value; + } + } + + /// + /// Gets a message that describes the current exception. + /// + public override string Message + { + // this is overridden just so I can make _really_ damn sure + // that Message is always stashed in Data + get + { + return (string)Data[Utils.ExceptionMessageDataKey]; + } + } + + internal DeserializationException(Exception inner, TextReader reader, bool endedEarly) + : base(inner.Message, inner) + { + SetMessage(inner.Message); + InspectReader(reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(Exception inner, ref ThunkReader reader, bool endedEarly) + : base(inner.Message, inner) + { + SetMessage(inner.Message); + InspectReader(ref reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(string msg, TextReader reader, bool endedEarly) + : base(msg) + { + SetMessage(msg); + InspectReader(reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(string msg, ref ThunkReader reader, bool endedEarly) + : base(msg) + { + SetMessage(msg); + InspectReader(ref reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(string msg, TextReader reader, Exception inner, bool endedEarly) + : base(msg, inner) + { + SetMessage(msg); + InspectReader(reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(string msg, ref ThunkReader reader, Exception inner, bool endedEarly) + : base(msg, inner) + { + SetMessage(msg); + InspectReader(ref reader); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(string msg, Exception inner, bool endedEarly) + : base(msg + ": " + inner.Message, inner) + { + SetMessage(msg + ": " + inner.Message); + EndedUnexpectedly = endedEarly; + } + + internal DeserializationException(Exception inner, bool endedEarly) + : base(inner.Message, inner) + { + SetMessage(inner.Message); + EndedUnexpectedly = endedEarly; + } + + void SetMessage(string msg) + { + Data[Utils.ExceptionMessageDataKey] = msg; + } + + void InspectReader(ref ThunkReader reader) + { + try + { + Position = reader.Position; + + var sb = new StringBuilder(); + + int c; + while ((c = reader.Read()) != -1 && sb.Length < 50) + { + sb.Append((char)c); + } + + SnippetAfterError = sb.ToString(); + } + catch (Exception) { /* best effort here, things are already jacked */ } + } + + void InspectReader(TextReader reader) + { + try + { + var asStreamReader = reader as StreamReader; + if (asStreamReader != null) + { + if (asStreamReader.BaseStream.CanSeek) + { + Position = asStreamReader.BaseStream.Position; + } + } + + var sb = new StringBuilder(); + + int c; + while((c = reader.Read()) != -1 && sb.Length < 50) + { + sb.Append((char)c); + } + + SnippetAfterError = sb.ToString(); + } + catch (Exception) { /* best effort here, things are already jacked */ } + } + } +} diff --git a/vendor/Jil/Deserialize/AnonymousTypeLookup.cs b/vendor/Jil/Deserialize/AnonymousTypeLookup.cs new file mode 100644 index 000000000..af146224a --- /dev/null +++ b/vendor/Jil/Deserialize/AnonymousTypeLookup.cs @@ -0,0 +1,71 @@ +using Jil.Common; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Deserialize +{ + delegate int AnonymousTypeLookupThunkReaderDelegate(ref ThunkReader reader); + + class AnonymousTypeLookup + { + public static Dictionary> ParametersToTypeAndIndex; + private static Func _findConstructorParameterIndex; + private static AnonymousTypeLookupThunkReaderDelegate _findConstructorParameterIndexThunkReader; + + // Still used in ReadAnonymousObjectDictionaryLookup (can be removed if NameAutomata method is always used) + public static Dictionary Lookup; + + static AnonymousTypeLookup() + { + ParametersToTypeAndIndex = Utils.GetAnonymousNameToConstructorMap(typeof(ForType)); + + var orderedNames = + ParametersToTypeAndIndex + .OrderBy(kv => kv.Value.Item2) + .Select(kv => kv.Key); + + _findConstructorParameterIndex = CreateFindMember(orderedNames); + _findConstructorParameterIndexThunkReader = CreateFindMemberThunkReader(orderedNames); + + // Still used in ReadAnonymousObjectDictionaryLookup (can be removed if NameAutomata method is always used) + Lookup = ParametersToTypeAndIndex.ToDictionary(d => d.Key, d => d.Value.Item2); + } + + private static Func CreateFindMember(IEnumerable names) + { + var nameToResults = + names + .Select((name, index) => NameAutomata.CreateName(typeof(TextReader), name, emit => emit.LoadConstant(index))) + .ToList(); + + var ret = NameAutomata.Create>(typeof(TextReader), nameToResults, true, defaultValue: -1); + return (Func)ret; + } + + private static AnonymousTypeLookupThunkReaderDelegate CreateFindMemberThunkReader(IEnumerable names) + { + var nameToResults = + names + .Select((name, index) => NameAutomata.CreateName(typeof(ThunkReader).MakeByRefType(), name, emit => emit.LoadConstant(index))) + .ToList(); + + var ret = NameAutomata.Create(typeof(ThunkReader).MakeByRefType(), nameToResults, true, defaultValue: -1); + return (AnonymousTypeLookupThunkReaderDelegate)ret; + } + + // probably not the best place for this; but sufficent I guess... + public static int FindConstructorParameterIndex(TextReader reader) + { + return _findConstructorParameterIndex(reader); + } + + public static int FindConstructorParameterIndexThunkReader(ref ThunkReader reader) + { + return _findConstructorParameterIndexThunkReader(ref reader); + } + } +} diff --git a/vendor/Jil/Deserialize/DeserializeIndirect.cs b/vendor/Jil/Deserialize/DeserializeIndirect.cs new file mode 100644 index 000000000..5eac2ff8f --- /dev/null +++ b/vendor/Jil/Deserialize/DeserializeIndirect.cs @@ -0,0 +1,84 @@ +using Jil.Common; +using Sigil.NonGeneric; +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Deserialize +{ + static class DeserializeIndirect + { + static Hashtable DeserializeFromStreamIndirectCache = new Hashtable(); + static Hashtable DeserializeFromStringIndirectCache = new Hashtable(); + + static MethodInfo JSONDeserializeFromStream = typeof(JSON).GetMethod("Deserialize", new[] { typeof(TextReader), typeof(Options) }); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object DeserializeFromStream(TextReader reader, Type type, Options options) + { + var cached = (Func)DeserializeFromStreamIndirectCache[type]; + if (cached == null) + { + lock(DeserializeFromStreamIndirectCache) + { + cached = (Func)DeserializeFromStreamIndirectCache[type]; + if (cached == null) + { + var emit = Emit.NewDynamicMethod(typeof(object), new[] { typeof(TextReader), typeof(Options) }, doVerify: Utils.DoVerify); + var mtd = JSONDeserializeFromStream.MakeGenericMethod(type); + + emit.LoadArgument(0); // TextReader + emit.LoadArgument(1); // TextReader Options + emit.Call(mtd); // type + if (type.IsValueType()) + { + emit.Box(type); // object + } + emit.Return(); + + DeserializeFromStreamIndirectCache[type] = cached = emit.CreateDelegate>(Utils.DelegateOptimizationOptions); + } + } + } + + return cached(reader, options); + } + + static MethodInfo JSONDeserializeFromString = typeof(JSON).GetMethod("Deserialize", new[] { typeof(string), typeof(Options) }); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static object DeserializeFromString(string reader, Type type, Options options) + { + var cached = (Func)DeserializeFromStringIndirectCache[type]; + if (cached == null) + { + lock (DeserializeFromStringIndirectCache) + { + cached = (Func)DeserializeFromStringIndirectCache[type]; + if (cached == null) + { + var emit = Emit.NewDynamicMethod(typeof(object), new[] { typeof(string), typeof(Options) }, doVerify: Utils.DoVerify); + var mtd = JSONDeserializeFromString.MakeGenericMethod(type); + + emit.LoadArgument(0); // TextReader + emit.LoadArgument(1); // TextReader Options + emit.Call(mtd); // type + if (type.IsValueType()) + { + emit.Box(type); // object + } + emit.Return(); + + DeserializeFromStringIndirectCache[type] = cached = emit.CreateDelegate>(Utils.DelegateOptimizationOptions); + } + } + } + + return cached(reader, options); + } + } +} diff --git a/vendor/Jil/Deserialize/EnumLookup.cs b/vendor/Jil/Deserialize/EnumLookup.cs new file mode 100644 index 000000000..5179fad60 --- /dev/null +++ b/vendor/Jil/Deserialize/EnumLookup.cs @@ -0,0 +1,248 @@ +using Jil.Common; +using Sigil.NonGeneric; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Deserialize +{ + delegate EnumType EnumThunkReaderDelegate(ref ThunkReader reader) + where EnumType : struct; + + class EnumLookup + where EnumType : struct + { + private static Func _getEnumValue; + private static EnumThunkReaderDelegate _getEnumValueThunkReader; + + static EnumLookup() + { + var enumValues = GetEnumValues(); + + _getEnumValue = + typeof(EnumType).IsFlagsEnum() + ? CreateFindFlagsEnum(enumValues) + : CreateFindEnum(enumValues); + + _getEnumValueThunkReader = + typeof(EnumType).IsFlagsEnum() + ? CreateFindFlagsEnumThunkReader(enumValues) + : CreateFindEnumThunkReader(enumValues); + } + + private static IReadOnlyList> GetEnumValues() + { + var names = Enum.GetNames(typeof(EnumType)); + var ret = new List>(); + + foreach(var name in names) + { + object val = Enum.Parse(typeof(EnumType), name); + + var field = typeof(EnumType).GetField(name); + var enumMember = field.GetCustomAttribute(); + if(enumMember?.Value != null) + { + ret.Add(Tuple.Create(enumMember.Value, val)); + } + else + { + ret.Add(Tuple.Create(name, val)); + } + } + + return ret.AsReadOnly(); + } + + private static Func CreateFindEnum(IEnumerable> names) + { + var underlyingType = Enum.GetUnderlyingType(typeof(EnumType)); + + var nameToResults = + names + .Select(name => NameAutomata.CreateName(typeof(TextReader), name.Item1, emit => LoadConstantOfType(emit, name.Item2, underlyingType))) + .ToList(); + + var ret = + NameAutomata.Create>( + typeof(TextReader), + nameToResults, + false, + defaultValue: null + ); + + return (Func)ret; + } + + private static EnumThunkReaderDelegate CreateFindEnumThunkReader(IEnumerable> names) + { + var thunkReaderRef = typeof(ThunkReader).MakeByRefType(); + + var underlyingType = Enum.GetUnderlyingType(typeof(EnumType)); + + var nameToResults = + names + .Select(name => NameAutomata.CreateName(thunkReaderRef, name.Item1, emit => LoadConstantOfType(emit, name.Item2, underlyingType))) + .ToList(); + + var ret = + NameAutomata.Create>( + thunkReaderRef, + nameToResults, + false, + defaultValue: null + ); + + return (EnumThunkReaderDelegate)ret; + } + + private static Func CreateFindFlagsEnum(IReadOnlyList> names) + { + var underlyingType = Enum.GetUnderlyingType(typeof(EnumType)); + + var resultValue = "result_value"; + + var nameToResults = + names + .Select(name => + NameAutomata.CreateName( + typeof(TextReader), + name.Item1, + emit => + { + LoadConstantOfType(emit, name.Item2, underlyingType); + emit.LoadLocal(resultValue); + emit.Or(); + emit.StoreLocal(resultValue); + })) + .ToList(); + + + var ret = + NameAutomata.CreateFold>( + typeof(TextReader), + nameToResults, + emit => + { + emit.DeclareLocal(underlyingType, resultValue); + LoadConstantOfType(emit, Convert.ChangeType(0, underlyingType), underlyingType); + emit.StoreLocal(resultValue); + }, + emit => + { + emit.LoadLocal(resultValue); + emit.Return(); + }, + true, + true, + false, + defaultValue: null + ); + + return (Func)ret; + } + + private static EnumThunkReaderDelegate CreateFindFlagsEnumThunkReader(IReadOnlyList> names) + { + var thunkReaderRef = typeof(ThunkReader).MakeByRefType(); + + var underlyingType = Enum.GetUnderlyingType(typeof(EnumType)); + + var resultValue = "result_value"; + + var nameToResults = + names + .Select(name => + NameAutomata.CreateName( + thunkReaderRef, + name.Item1, + emit => + { + LoadConstantOfType(emit, name.Item2, underlyingType); + emit.LoadLocal(resultValue); + emit.Or(); + emit.StoreLocal(resultValue); + })) + .ToList(); + + var underlyingDefault = underlyingType.DefaultValue(); + + var ret = + NameAutomata.CreateFold>( + thunkReaderRef, + nameToResults, + emit => + { + emit.DeclareLocal(underlyingType, resultValue); + LoadConstantOfType(emit, Convert.ChangeType(0, underlyingType), underlyingType); + emit.StoreLocal(resultValue); + }, + emit => + { + emit.LoadLocal(resultValue); + emit.Return(); + }, + true, + true, + false, + defaultValue: underlyingDefault + ); + + return (EnumThunkReaderDelegate)ret; + } + + static void LoadConstantOfType(Emit Emit, object val, Type type) + { + if (type == typeof(byte)) + { + Emit.LoadConstant((byte)val); + } + else if (type == typeof(sbyte)) + { + Emit.LoadConstant((sbyte)val); + } + else if (type == typeof(short)) + { + Emit.LoadConstant((short)val); + } + else if (type == typeof(ushort)) + { + Emit.LoadConstant((ushort)val); + } + else if (type == typeof(int)) + { + Emit.LoadConstant((int)val); + } + else if (type == typeof(uint)) + { + Emit.LoadConstant((uint)val); + } + else if (type == typeof(long)) + { + Emit.LoadConstant((long)val); + } + else if (type == typeof(ulong)) + { + Emit.LoadConstant((ulong)val); + } + else + { + throw new ConstructionException("Unexpected type: " + type); + } + } + + public static EnumType GetEnumValue(TextReader reader) + { + return _getEnumValue(reader); + } + + public static EnumType GetEnumValueThunkReader(ref ThunkReader reader) + { + return _getEnumValueThunkReader(ref reader); + } + } +} diff --git a/vendor/Jil/Deserialize/InlineDeserializer.cs b/vendor/Jil/Deserialize/InlineDeserializer.cs new file mode 100644 index 000000000..5b0a19de2 --- /dev/null +++ b/vendor/Jil/Deserialize/InlineDeserializer.cs @@ -0,0 +1,2878 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Jil.Common; +using Sigil.NonGeneric; +using System.Reflection; +using System.Globalization; + +namespace Jil.Deserialize +{ + class InlineDeserializer + { + public static bool UseFastFloatingPointMethods = true; + public static bool UseCharArrayOverStringBuilder = true; + public static bool UseNameAutomata = true; + public static bool UseNameAutomataForEnums = true; + public static bool UseNameAutomataSwitches = true; + public static bool UseNameAutomataBinarySearch = true; + public static bool UseFastRFC1123Method = true; + public static bool UseFastUnionLookup = true; + + const string CharBufferName = "char_buffer"; + const string StringBuilderName = "string_builder"; + + readonly Type OptionsType; + readonly DateTimeFormat DateFormat; + readonly SerializationNameFormat SerializationNameFormat; + readonly bool ReadingFromString; + readonly bool PreferIndirectSerialization; + readonly bool AllPrimitivesThroughHelpers; + + bool UsingCharBuffer; + HashSet IndirectTypes; + + Emit Emit; + + int NextName; + + public InlineDeserializer( + Type optionsType, + DateTimeFormat dateFormat, + SerializationNameFormat serializationNameFormat, + bool readingFromString, + bool preferIndirectSerialization, + bool allPrimitivesThroughHelpers + ) + { + OptionsType = optionsType; + DateFormat = dateFormat; + SerializationNameFormat = serializationNameFormat; + ReadingFromString = readingFromString; + + PreferIndirectSerialization = preferIndirectSerialization; + AllPrimitivesThroughHelpers = allPrimitivesThroughHelpers; + + NextName = 1; + } + + string GetNextName() + { + var ret = "id_n" + NextName; + NextName++; + + return ret; + } + + void SetProperty(PropertyInfo prop) + { + // Top of stack + // value + // object(*?) + + var setMtd = prop.SetMethod; + + if (setMtd.IsVirtual) + { + Emit.CallVirtual(setMtd); + } + else + { + Emit.Call(setMtd); + } + } + + void AddGlobalVariables() + { + var involvedTypes = typeof(ForType).InvolvedTypes(); + + var hasStringyTypes = + involvedTypes.Contains(typeof(string)) || + involvedTypes.Any(t => t.IsUserDefinedType()); // for member names + + var needsCharBuffer = + hasStringyTypes || + involvedTypes.Any(t => t.IsNumberType()) || // we use `ref char[]` for these, so they're kind of stringy + (involvedTypes.Contains(typeof(DateTime)) && DateFormat == DateTimeFormat.ISO8601) || + (involvedTypes.Contains(typeof(TimeSpan)) && (DateFormat == DateTimeFormat.ISO8601 || DateFormat == DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch)); + + if (needsCharBuffer) + { + UsingCharBuffer = true; + + Emit.DeclareLocal(CharBufferName); + + Emit.LoadConstant(Methods.CharBufferSize); // int + Emit.NewArray(); // char[] + Emit.StoreLocal(CharBufferName); // --empty-- + } + + // we can't know, for sure, that a StringBuilder will be needed w/o seeing the data + // but we can save the slot on the stack in rare cases + var mayNeedStringBuilder = + involvedTypes.Contains(typeof(string)) || + involvedTypes.Contains(typeof(float)) || + involvedTypes.Contains(typeof(double)) || + involvedTypes.Contains(typeof(decimal)) || + involvedTypes.Any(t => t.IsEnum()) || + involvedTypes.Any(t => t.IsUserDefinedType()) || + (!UseNameAutomataForEnums && involvedTypes.Any(t => t.IsEnum())); + + if (mayNeedStringBuilder) + { + var gonnaUseAStringBuilderAnyway = (!UseNameAutomataForEnums && involvedTypes.Any(t => t.IsEnum())); + + if (!UseCharArrayOverStringBuilder || gonnaUseAStringBuilderAnyway) + { + Emit.DeclareLocal(StringBuilderName); + } + } + } + + void LoadCharBufferAddress() + { + Emit.LoadLocalAddress(CharBufferName); + } + + void LoadCharBuffer() + { + Emit.LoadLocal(CharBufferName); + } + + void LoadStringBuilder() + { + Emit.LoadLocalAddress(StringBuilderName); + } + + static MethodInfo TextReader_Read = typeof(TextReader).GetMethod("Read", Type.EmptyTypes); + static MethodInfo ThunkReader_Read = typeof(ThunkReader).GetMethod("Read", Type.EmptyTypes); + void ReadCharFromStream() + { + Emit.LoadArgument(0); // (TextReader|ref ThunkReader) + if (ReadingFromString) + { + Emit.Call(ThunkReader_Read); // int + } + else + { + Emit.CallVirtual(TextReader_Read); // int + } + } + + + void RawReadChar(Action endOfStream) + { + var haveChar = Emit.DefineLabel(GetNextName()); + + ReadCharFromStream(); // int + Emit.Duplicate(); // int int + Emit.LoadConstant(-1); // int int -1 + Emit.UnsignedBranchIfNotEqual(haveChar); // int + Emit.Pop(); // --empty-- + endOfStream(); // --empty-- + + Emit.MarkLabel(haveChar); // int + } + + void ThrowExpectedButEnded(char c) + { + ThrowExpectedButEnded("" + c); + } + + static readonly ConstructorInfo DeserializationException_Cons_string_ThunkWriter_bool = typeof(DeserializationException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(string), typeof(ThunkReader).MakeByRefType(), typeof(bool) }); + static readonly ConstructorInfo DeserializationException_Cons_string_TextReader_bool = typeof(DeserializationException).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, new[] { typeof(string), typeof(TextReader), typeof(bool) }); + void ThrowStringStreamBool() + { + // top of stack is: + // string + // (TextReader|ref ThunkReader) + // bool + + if (ReadingFromString) + { + Emit.NewObject(DeserializationException_Cons_string_ThunkWriter_bool); // DeserializationException + } + else + { + Emit.NewObject(DeserializationException_Cons_string_TextReader_bool); // DeserializationException + } + } + + void ThrowExpectedButEnded(params object[] ps) + { + Emit.LoadConstant("Expected: " + string.Join(", ", ps) + "; but the reader ended"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(true); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + } + + void ThrowExpectedButEnded(string s) + { + Emit.LoadConstant("Expected character: '" + s + "', but the reader ended"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(true); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + } + + void ThrowExpected(char c) + { + Emit.LoadConstant("Expected character: '" + c + "'"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(false); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + } + + void ThrowIfEmptyAndWasExpecting(params object[] ps) + { + // top of stack: + // int + + var notEmpty = Emit.DefineLabel(GetNextName()); + + Emit.Duplicate(); // int int + Emit.LoadConstant(-1); // int int -1 + Emit.UnsignedBranchIfNotEqual(notEmpty); // int + + Emit.Pop(); // --empty-- + Emit.LoadConstant("Expected: " + string.Join(", ", ps) + "; but the reader ended"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(true); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + + Emit.MarkLabel(notEmpty); // int + } + + void ThrowExpected(params object[] ps) + { + Emit.LoadConstant("Expected: " + string.Join(", ", ps)); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(false); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + } + + void ThrowExpected(char[] cs) + { + var ps = cs.Cast().ToArray(); + ThrowExpected(ps); + } + + void ExpectChar(char c) + { + var gotRightChar = Emit.DefineLabel(GetNextName()); + var gotAChar = Emit.DefineLabel(GetNextName()); + + ReadCharFromStream(); // int + Emit.LoadConstant((int)c); // int int + Emit.Duplicate(); // int int int + Emit.LoadConstant(-1); // int int int -1 + Emit.UnsignedBranchIfNotEqual(gotAChar); // int int + ThrowExpectedButEnded(c); // int int + + Emit.MarkLabel(gotAChar); // --empty-- + Emit.BranchIfEqual(gotRightChar); // --empty-- + ThrowExpected(c); // --empty-- + + Emit.MarkLabel(gotRightChar); // --empty-- + } + + void CheckChar(char c) + { + var gotRightChar = Emit.DefineLabel(GetNextName()); + var gotAChar = Emit.DefineLabel(GetNextName()); + + Emit.Duplicate(); // int int + Emit.LoadConstant(-1); // int int -1 + Emit.UnsignedBranchIfNotEqual(gotAChar); // int + ThrowExpectedButEnded(c); // --empty-- + + Emit.MarkLabel(gotAChar); // int + Emit.LoadConstant((int)c); // int int + Emit.BranchIfEqual(gotRightChar); // --empty-- + ThrowExpected(c); // --empty-- + + Emit.MarkLabel(gotRightChar); // --empty-- + } + + void ExpectQuote() + { + ExpectChar('"'); + } + + void CheckQuote() + { + CheckChar('"'); + } + + void ExpectRawCharOrNull(char c, Action ifChar, Action ifNull) + { + var gotChar = Emit.DefineLabel(GetNextName()); + var gotN = Emit.DefineLabel(GetNextName()); + var done = Emit.DefineLabel(GetNextName()); + + RawReadChar(() => ThrowExpectedButEnded(c, "null")); // int + Emit.Duplicate(); // int int + Emit.LoadConstant((int)c); // int int int + Emit.BranchIfEqual(gotChar); // int + Emit.LoadConstant((int)'n'); // int n + Emit.BranchIfEqual(gotN); // --empty-- + ThrowExpected(c, "null"); // --empty-- + + Emit.MarkLabel(gotChar); // int + Emit.Pop(); // --empty-- + ifChar(); // ??? + Emit.Branch(done); // ??? + + Emit.MarkLabel(gotN); // --empty-- + ExpectChar('u'); // --empty-- + ExpectChar('l'); // --empty-- + ExpectChar('l'); // --empty-- + ifNull(); // ??? + + Emit.MarkLabel(done); // --empty-- + } + + void ExpectQuoteOrNull(Action ifQuote, Action ifNull) + { + ExpectRawCharOrNull('"', ifQuote, ifNull); + } + + void ReadChar() + { + ExpectQuote(); // --empty-- + ReadEncodedChar(); // char + ExpectQuote(); // char + } + + void ReadEncodedChar() + { + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetReadEncodedChar(ReadingFromString)); // char + } + + void CallReadEncodedString() + { + // Stack starts + // TextReader + + if (UseCharArrayOverStringBuilder) + { + LoadCharBufferAddress(); // TextReader char[] + Emit.Call(Methods.GetReadEncodedStringWithCharArray(ReadingFromString)); // string + } + else + { + if (UsingCharBuffer) + { + LoadCharBuffer(); // TextReader char[] + LoadStringBuilder(); // TextReader char[] StringBuilder + Emit.Call(Methods.GetReadEncodedStringWithBuffer(ReadingFromString)); // string + } + else + { + LoadStringBuilder(); // TextReader StringBuilder + Emit.Call(Methods.GetReadEncodedString(ReadingFromString)); // string + } + } + } + + void ReadString() + { + ExpectQuoteOrNull( + delegate + { + // --empty-- + Emit.LoadArgument(0); // TextReader + CallReadEncodedString(); // string + }, + delegate + { + Emit.LoadNull(); // null + } + ); + } + + void ReadNumber(Type numberType) + { + Emit.LoadArgument(0); // TextReader + + if (numberType == typeof(byte)) + { + Emit.Call(Methods.GetReadUInt8(ReadingFromString)); // byte + return; + } + + if (numberType == typeof(sbyte)) + { + Emit.Call(Methods.GetReadInt8(ReadingFromString)); // sbyte + return; + } + + if (numberType == typeof(short)) + { + Emit.Call(Methods.GetReadInt16(ReadingFromString)); // short + return; + } + + if (numberType == typeof(ushort)) + { + Emit.Call(Methods.GetReadUInt16(ReadingFromString)); // ushort + return; + } + + if (numberType == typeof(int)) + { + Emit.Call(Methods.GetReadInt32(ReadingFromString)); // int + return; + } + + if (numberType == typeof(uint)) + { + Emit.Call(Methods.GetReadUInt32(ReadingFromString)); // uint + return; + } + + if (numberType == typeof(long)) + { + Emit.Call(Methods.GetReadInt64(ReadingFromString)); // long + return; + } + + if (numberType == typeof(ulong)) + { + Emit.Call(Methods.GetReadUInt64(ReadingFromString)); // ulong + return; + } + + if (UseFastFloatingPointMethods) + { + LoadCharBufferAddress(); // TextReader char[] + + if (numberType == typeof(double)) + { + Emit.Call(Methods.GetReadDoubleFast(ReadingFromString)); // double + return; + } + + if (numberType == typeof(float)) + { + Emit.Call(Methods.GetReadSingleFast(ReadingFromString)); // float + return; + } + + if (numberType == typeof(decimal)) + { + Emit.Call(Methods.GetReadDecimalFast(ReadingFromString)); // decimal + return; + } + } + else + { + if (UseCharArrayOverStringBuilder) + { + LoadCharBufferAddress(); // TextReader char[] + + if (numberType == typeof(double)) + { + Emit.Call(Methods.GetReadDoubleCharArray(ReadingFromString)); // double + return; + } + + if (numberType == typeof(float)) + { + Emit.Call(Methods.GetReadSingleCharArray(ReadingFromString)); // float + return; + } + + if (numberType == typeof(decimal)) + { + Emit.Call(Methods.GetReadDecimalCharArray(ReadingFromString)); // decimal + return; + } + } + else + { + LoadStringBuilder(); // TextReader StringBuilder + + if (numberType == typeof(double)) + { + Emit.Call(Methods.GetReadDouble(ReadingFromString)); // double + return; + } + + if (numberType == typeof(float)) + { + Emit.Call(Methods.GetReadSingle(ReadingFromString)); // float + return; + } + + if (numberType == typeof(decimal)) + { + Emit.Call(Methods.GetReadDecimal(ReadingFromString)); // decimal + return; + } + } + } + + throw new ConstructionException("Unexpected number type: " + numberType); + } + + void ReadBool() + { + if(AllPrimitivesThroughHelpers) + { + Emit.LoadArgument(0); + Emit.Call(Methods.GetReadBool(ReadingFromString)); // bool + return; + } + + var endOfStream = Emit.DefineLabel(GetNextName()); + var mayBeTrue = Emit.DefineLabel(GetNextName()); + var mayBeFalse = Emit.DefineLabel(GetNextName()); + var done = Emit.DefineLabel(GetNextName()); + + RawReadChar(() => Emit.Branch(endOfStream)); // int + Emit.Duplicate(); // int int + Emit.LoadConstant('t'); // int int 't' + Emit.BranchIfEqual(mayBeTrue); // int + Emit.LoadConstant('f'); // int 'f' + Emit.BranchIfEqual(mayBeFalse); // --empty-- + + // end of stream **AND** not true or false case + Emit.MarkLabel(endOfStream); // --empty-- + ThrowExpectedButEnded("true or false"); // --empty-- + + Emit.MarkLabel(mayBeTrue); // int + Emit.Pop(); // --empty-- + ExpectChar('r'); // --empty-- + ExpectChar('u'); // --empty-- + ExpectChar('e'); // --empty-- + + Emit.LoadConstant(true); // bool + Emit.Branch(done); // bool + + Emit.MarkLabel(mayBeFalse); // --empty-- + ExpectChar('a'); // --empty-- + ExpectChar('l'); // --empty-- + ExpectChar('s'); // --empty-- + ExpectChar('e'); // --empty-- + + Emit.LoadConstant(false); // bool + + Emit.MarkLabel(done); // bool + } + + void ReadGuid() + { + ExpectQuote(); + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetReadGuid(ReadingFromString)); // Guid + ExpectQuote(); // Guid + } + + static readonly ConstructorInfo DateTimeOffsetConst = typeof(DateTimeOffset).GetConstructor(new[] { typeof(DateTime) }); + void ReadDateTimeOffset() + { + if (DateFormat == DateTimeFormat.MillisecondsSinceUnixEpoch || + DateFormat == DateTimeFormat.SecondsSinceUnixEpoch) + { + // All of these formats lack a timezone offset + // So let's just reuse the DateTime reader + ReadDate(); // DateTime + Emit.NewObject(DateTimeOffsetConst); // DateTimeOffset + return; + } + + if (DateFormat == DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch) + { + ReadMicrosoftDateTimeOffset(); // DateTimeOffset; + return; + } + + ExpectQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + if (UseCharArrayOverStringBuilder) + { + LoadCharBufferAddress(); + Emit.Call(Methods.GetReadISO8601DateWithOffsetWithCharArray(ReadingFromString)); // DateTimeOffset + ExpectQuote(); // DateTimeOffset + } + else + { + LoadCharBuffer(); + Emit.Call(Methods.GetReadISO8601DateWithOffset(ReadingFromString)); // DateTimeOffset + ExpectQuote(); // DateTimeOffset + } + } + + void ReadTimeSpan() + { + switch (DateFormat) + { + case DateTimeFormat.SecondsSinceUnixEpoch: ReadSecondsTimeSpan(); break; + case DateTimeFormat.MillisecondsSinceUnixEpoch: ReadMillisecondsTimeSpan(); break; + case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: ReadMicrosoftStyleTimeSpan(); break; + case DateTimeFormat.ISO8601: ReadISO8601TimeSpan(); break; + default: throw new Exception("Unexpected DateTimeFormat: " + DateFormat); + } + } + + static readonly MethodInfo TimeSpan_FromSeconds = typeof(TimeSpan).GetMethod("FromSeconds", new[] { typeof(double) }); + void ReadSecondsTimeSpan() + { + const double TicksPerSecond = 10000000; + + var maxSecs = TimeSpan.MaxValue.TotalSeconds; + var minSecs = TimeSpan.MinValue.TotalSeconds; + + var maxTicks = TimeSpan.MaxValue.Ticks; + var minTicks = TimeSpan.MinValue.Ticks; + + var isMax = Emit.DefineLabel(GetNextName()); + var isMin = Emit.DefineLabel(GetNextName()); + var done = Emit.DefineLabel(GetNextName()); + + ReadPrimitive(typeof(double)); // double + Emit.Duplicate(); // double double + Emit.LoadConstant(maxSecs); // double double double + Emit.BranchIfGreaterOrEqual(isMax); // double + + Emit.Duplicate(); // double double + Emit.LoadConstant(minSecs); // double double double + Emit.BranchIfLessOrEqual(isMin); // double + + Emit.LoadConstant(TicksPerSecond); // double double + Emit.Multiply(); // double + Emit.Convert(); // long + Emit.NewObject(); // TimeSpan + Emit.Branch(done); // TimeSpan + + Emit.MarkLabel(isMax); // double + Emit.Pop(); // --empty-- + Emit.LoadConstant(maxTicks); // long + Emit.NewObject(); // TimeSpan + Emit.Branch(done); // TimeSpan + + Emit.MarkLabel(isMin); // double + Emit.Pop(); // --empty-- + Emit.LoadConstant(minTicks); // long + Emit.NewObject(); // TimeSpan + + Emit.MarkLabel(done); // TimeSpan + } + + void ReadMillisecondsTimeSpan() + { + const double TicksPerMillisecond = 10000; + + var maxMs = TimeSpan.MaxValue.TotalMilliseconds; + var minMs = TimeSpan.MinValue.TotalMilliseconds; + + var maxTicks = TimeSpan.MaxValue.Ticks; + var minTicks = TimeSpan.MinValue.Ticks; + + var isMax = Emit.DefineLabel(GetNextName()); + var isMin = Emit.DefineLabel(GetNextName()); + var done = Emit.DefineLabel(GetNextName()); + + ReadPrimitive(typeof(double)); // double + Emit.Duplicate(); // double double + Emit.LoadConstant(maxMs); // double double double + Emit.BranchIfGreaterOrEqual(isMax); // double + + Emit.Duplicate(); // double double + Emit.LoadConstant(minMs); // double double double + Emit.BranchIfLessOrEqual(isMin); // double + + Emit.LoadConstant(TicksPerMillisecond); // double double + Emit.Multiply(); // double + Emit.Convert(); // long + Emit.NewObject(); // TimeSpan + Emit.Branch(done); // TimeSpan + + Emit.MarkLabel(isMax); // double + Emit.Pop(); // --empty-- + Emit.LoadConstant(maxTicks); // long + Emit.NewObject(); // TimeSpan + Emit.Branch(done); // TimeSpan + + Emit.MarkLabel(isMin); // double + Emit.Pop(); // --empty-- + Emit.LoadConstant(minTicks); // long + Emit.NewObject(); // TimeSpan + + Emit.MarkLabel(done); // TimeSpan + } + + void ReadMicrosoftStyleTimeSpan() + { + Emit.LoadArgument(0); // TextReader + LoadCharBuffer(); // TextReader char[] + Emit.Call(Methods.GetReadMicrosoftTimeSpan(ReadingFromString)); // TimeSpan + } + + void ReadISO8601TimeSpan() + { + Emit.LoadArgument(0); // TextReader + LoadCharBuffer(); // TextReader char[] + Emit.Call(Methods.GetReadISO8601TimeSpan(ReadingFromString)); // TimeSpan + } + + void ReadDate() + { + switch (DateFormat) + { + case DateTimeFormat.MicrosoftStyleMillisecondsSinceUnixEpoch: ReadMicrosoftDateTime(); break; + case DateTimeFormat.MillisecondsSinceUnixEpoch: ReadMillisecondsDateTime(); break; + case DateTimeFormat.SecondsSinceUnixEpoch: ReadSecondsDateTime(); break; + case DateTimeFormat.ISO8601: ReadISO8601DateTime(); break; + case DateTimeFormat.RFC1123: ReadRFC1123DateTime(); break; + default: throw new ConstructionException("Unexpected DateTimeFormat: " + DateFormat); + } + + } + + void ReadMicrosoftDateTimeOffset() + { + ExpectQuote(); // --empty-- + ExpectChar('\\'); // --empty-- + ExpectChar('/'); // --empty-- + ExpectChar('D'); // --empty-- + ExpectChar('a'); // --empty-- + ExpectChar('t'); // --empty-- + ExpectChar('e'); // --empty-- + ExpectChar('('); // --empty-- + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetReadMicrosoftDateTimeOffset(ReadingFromString)); // DateTimeOffset + ExpectChar(')'); // DateTimeOffset + ExpectChar('\\'); // DateTimeOffset + ExpectChar('/'); // DateTimeOffset + + ExpectQuote(); // DateTimeOffset + } + + void ReadMicrosoftDateTime() + { + ExpectQuote(); // --empty-- + ExpectChar('\\'); // --empty-- + ExpectChar('/'); // --empty-- + ExpectChar('D'); // --empty-- + ExpectChar('a'); // --empty-- + ExpectChar('t'); // --empty-- + ExpectChar('e'); // --empty-- + ExpectChar('('); // --empty-- + ReadPrimitive(typeof(long)); // long + Emit.LoadArgument(0); // long TextReader + Emit.Call(Methods.GetDiscardMicrosoftTimeZoneOffset(ReadingFromString)); // long + ExpectChar(')'); // long + ExpectChar('\\'); // long + ExpectChar('/'); // long + + // convert MS into ticks + Emit.LoadConstant(10000L); // long long + Emit.Multiply(); // long + Emit.LoadConstant(621355968000000000L); // long long + Emit.Add(); // long + + Emit.LoadConstant((int)DateTimeKind.Utc); // long DateTimeKind + Emit.NewObject(); // DateTime + + ExpectQuote(); // DateTime + } + + void ReadMillisecondsDateTime() + { + ReadPrimitive(typeof(long)); // long + Emit.LoadConstant(10000L); // long long + Emit.Multiply(); // long + Emit.LoadConstant(621355968000000000L); // long long + Emit.Add(); // long + + Emit.LoadConstant((int)DateTimeKind.Utc); // long DateTimeKind + Emit.NewObject(); // DateTime + } + + void ReadSecondsDateTime() + { + ReadPrimitive(typeof(long)); // long + Emit.LoadConstant(10000000L); // long long + Emit.Multiply(); // long + Emit.LoadConstant(621355968000000000L); // long long + Emit.Add(); // long + + Emit.LoadConstant((int)DateTimeKind.Utc); // long DateTimeKind + Emit.NewObject(); // DateTime + } + + void ReadISO8601DateTime() + { + ExpectQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + if (UseCharArrayOverStringBuilder) + { + LoadCharBufferAddress(); + Emit.Call(Methods.GetReadISO8601DateWithCharArray(ReadingFromString)); // DateTime + ExpectQuote(); // DateTime + } + else + { + LoadCharBuffer(); + Emit.Call(Methods.GetReadISO8601Date(ReadingFromString)); // DateTime + ExpectQuote(); // DateTime + } + } + + static readonly MethodInfo DateTime_TryParseExact = typeof(DateTime).GetMethod("TryParseExact", new[] { typeof(string), typeof(string), typeof(IFormatProvider), typeof(DateTimeStyles), typeof(DateTime).MakeByRefType() }); + static readonly MethodInfo CultureInfo_InvariantCulture = typeof(CultureInfo).GetProperty("InvariantCulture").GetMethod; + void ReadRFC1123DateTime() + { + if (!UseFastRFC1123Method) + { + var universal = (int)DateTimeStyles.AdjustToUniversal; + + ReadPrimitive(typeof(string)); // string + Emit.LoadConstant("R"); // string string + Emit.Call(CultureInfo_InvariantCulture); // string string CultureInfo + Emit.LoadConstant(universal); // string string CultureInfo int + + using (var loc = Emit.DeclareLocal(GetNextName())) + { + var success = Emit.DefineLabel(GetNextName()); + + Emit.LoadLocalAddress(loc); // string string CultureInfo int DateTime& + Emit.Call(DateTime_TryParseExact); // bool + Emit.BranchIfTrue(success); // --empty-- + + Emit.LoadConstant("Couldn't parse RFC1123 DateTime"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(false); // string TextReader bool + ThrowStringStreamBool(); + Emit.Throw(); + + Emit.MarkLabel(success); // --empty-- + Emit.LoadLocal(loc); // DateTime + } + + return; + } + + ExpectQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetReadRFC1123Date(ReadingFromString)); // DateTime + ExpectQuote(); // DateTime + } + + void ReadPrimitive(Type primitiveType) + { + if (primitiveType == typeof(bool)) + { + ReadBool(); + return; + } + + if (primitiveType == typeof(char)) + { + ReadChar(); + return; + } + + if (primitiveType == typeof(string)) + { + ReadString(); + return; + } + + if (primitiveType == typeof(Guid)) + { + ReadGuid(); + return; + } + + if (primitiveType == typeof(TimeSpan)) + { + ReadTimeSpan(); + return; + } + + if (primitiveType == typeof(DateTime)) + { + ReadDate(); + return; + } + + if (primitiveType == typeof(DateTimeOffset)) + { + ReadDateTimeOffset(); + return; + } + + ReadNumber(primitiveType); + } + + void ReadPrimitiveTypeWrapper(Type primitiveTypeWrapper) + { + var primitiveMember = primitiveTypeWrapper.GetPrimitiveWrapperPropertyOrField(); + Type wrappedType; + if (primitiveMember is FieldInfo) + { + wrappedType = ((FieldInfo)primitiveMember).FieldType; + } + else + { + wrappedType = ((PropertyInfo)primitiveMember).PropertyType; + } + + var wrapperConst = primitiveTypeWrapper.GetConstructor(new[] { wrappedType }); + if (wrapperConst != null) + { + // use ctor + ReadPrimitive(wrappedType); // value + Emit.NewObject(wrapperConst); // object + } + else + { + var defaultConst = primitiveTypeWrapper.GetConstructor(Type.EmptyTypes); + if (defaultConst == null) + { + throw + new ConstructionException( + string.Format("Primitive wrapper {0} needs a default constructor, or a constructor taking a single {1} parameter", + primitiveTypeWrapper.FullName, + wrappedType.FullName + ) + ); + } + Emit.NewObject(defaultConst); + using (var loc = Emit.DeclareLocal(primitiveTypeWrapper, GetNextName())) + { + // wrapper + Emit.StoreLocal(loc); // --empty-- + Emit.LoadLocal(loc); // wrapper + ReadPrimitive(wrappedType); // wrapper value + + if (primitiveMember is FieldInfo) + { + Emit.StoreField((FieldInfo)primitiveMember); // --empty-- + } + else + { + SetProperty((PropertyInfo)primitiveMember); // --empty-- + } + Emit.LoadLocal(loc); // wrapper + } + } + } + + void ConsumeWhiteSpace() + { + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetConsumeWhiteSpace(ReadingFromString)); // --empty-- + } + + void ReadSkipWhitespace() + { + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetReadSkipWhitespace(ReadingFromString)); // int + } + + void ExpectEndOfStream() + { + var success = Emit.DefineLabel(GetNextName()); + + Emit.LoadArgument(1); // int + Emit.LoadConstant(0); // int + Emit.UnsignedBranchIfNotEqual(success); // --empty -- + ReadCharFromStream(); // int + Emit.LoadConstant(-1); // int -1 + Emit.BranchIfEqual(success); // --empty-- + + Emit.LoadConstant("Expected end of stream"); // string + Emit.LoadArgument(0); // string TextReader + Emit.LoadConstant(false); // string TextReader bool + ThrowStringStreamBool(); // DeserializationException + Emit.Throw(); // --empty-- + + Emit.MarkLabel(success); // --empty-- + } + + static readonly MethodInfo TextReader_Peek = typeof(TextReader).GetMethod("Peek", BindingFlags.Public | BindingFlags.Instance); + static readonly MethodInfo ThunkReader_Peek = typeof(ThunkReader).GetMethod("Peek", BindingFlags.Public | BindingFlags.Instance); + void RawPeekChar() + { + Emit.LoadArgument(0); // TextReader + + if (!ReadingFromString) + { + Emit.CallVirtual(TextReader_Peek); // int + } + else + { + Emit.Call(ThunkReader_Peek); // int + } + } + + void ReadFlagsEnum(Type enumType) + { + ExpectQuote(); // --empty-- + + var specific = Methods.GetReadFlagsEnum(ReadingFromString).MakeGenericMethod(enumType); + + Emit.LoadArgument(0); // TextReader + LoadStringBuilder(); // TextReader StringBuilder& + Emit.Call(specific); // enum + } + + void ReadEnum(Type enumType, bool cameFromNullable) + { + if (Enum.GetNames(enumType).Count() == 0) + { + if (cameFromNullable) + { + var message = enumType.FullName + " has no defined values and thus cannot be deserialized"; + var constr = ReadingFromString ? + DeserializationException_Cons_string_ThunkWriter_bool : + DeserializationException_Cons_string_TextReader_bool; + + // need to proxy this through a different method, just so Sigil can't tell + // it's unreachable code + var mtd = Methods.GetThrowNoDefinedValueInEnum(ReadingFromString); + + Emit.LoadConstant(message); // string + Emit.LoadArgument(0); // TextReader + Emit.Call(mtd); // --empty-- + + // fall through + } + else + { + throw new ConstructionException(enumType.FullName + " has no values, and cannot be deserialized; add a value, make nullable, or configure to treat as integer"); + } + } + + if (UseNameAutomataForEnums) + { + var setterLookup = typeof(EnumLookup<>).MakeGenericType(enumType); + + MethodInfo getVal; + if (ReadingFromString) + { + getVal = setterLookup.GetMethod("GetEnumValueThunkReader", new[] { typeof(ThunkReader).MakeByRefType() }); + } + else + { + getVal = setterLookup.GetMethod("GetEnumValue", new[] { typeof(TextReader) }); + } + + ExpectQuote(); + Emit.LoadArgument(0); // TextReader + Emit.Call(getVal); // emum + + return; + } + + if (enumType.IsFlagsEnum()) + { + ReadFlagsEnum(enumType); + return; + } + + var specific = Methods.GetParseEnum(ReadingFromString).MakeGenericMethod(enumType); + + ExpectQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + CallReadEncodedString(); // string + Emit.LoadArgument(0); // TextReader + Emit.Call(specific); // enum + } + + void LoadConstantOfType(object val, Type type) + { + if (type == typeof(byte)) + { + Emit.LoadConstant((byte)val); + return; + } + + if (type == typeof(sbyte)) + { + Emit.LoadConstant((sbyte)val); + return; + } + + if (type == typeof(short)) + { + Emit.LoadConstant((short)val); + return; + } + + if (type == typeof(ushort)) + { + Emit.LoadConstant((ushort)val); + return; + } + + if (type == typeof(int)) + { + Emit.LoadConstant((int)val); + return; + } + + if (type == typeof(uint)) + { + Emit.LoadConstant((uint)val); + return; + } + + if (type == typeof(long)) + { + Emit.LoadConstant((long)val); + return; + } + + if (type == typeof(ulong)) + { + Emit.LoadConstant((ulong)val); + return; + } + + throw new ConstructionException("Unexpected type: " + type); + } + + void ReadNullable(MemberInfo nullableMember, Type nullableType) + { + var underlying = Nullable.GetUnderlyingType(nullableType); + var nullableConst = nullableType.GetConstructor(new[] { underlying }); + var done = Emit.DefineLabel(GetNextName()); + + if (AllPrimitivesThroughHelpers) + { + var isNull = Emit.DefineLabel(GetNextName()); + + using (var loc = Emit.DeclareLocal(nullableType, GetNextName())) + { + + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetIsNull(ReadingFromString)); // bool + Emit.BranchIfTrue(isNull); // --empty-- + + Build(nullableMember, underlying, fromNullable: true); // underlying + Emit.NewObject(nullableConst); // nullableType + Emit.Branch(done); // nullableType + + Emit.MarkLabel(isNull); // --empty-- + Emit.LoadLocalAddress(loc); // nullableType* + Emit.InitializeObject(nullableType); // --empty-- + Emit.LoadLocal(loc); // nullableType + } + + Emit.MarkLabel(done); // nullableType + + return; + } + + var maybeNull = Emit.DefineLabel(GetNextName()); + + + using (var loc = Emit.DeclareLocal(nullableType, GetNextName())) + { + RawPeekChar(); // int + Emit.LoadConstant('n'); // int n + Emit.BranchIfEqual(maybeNull); // --empty-- + + Build(nullableMember, underlying, fromNullable: true); // underlying + Emit.NewObject(nullableConst); // nullableType + Emit.Branch(done); // nullableType + + Emit.MarkLabel(maybeNull); // --empty-- + ExpectChar('n'); // --empty-- + ExpectChar('u'); // --empty-- + ExpectChar('l'); // --empty-- + ExpectChar('l'); // --empty-- + + Emit.LoadLocalAddress(loc); // nullableType* + Emit.InitializeObject(nullableType); // --empty-- + Emit.LoadLocal(loc); // nullableType + + Emit.MarkLabel(done); // nullableType + } + } + + void ReadList(MemberInfo listMember, Type listType, bool isSet) + { + var elementType = isSet + ? listType.GetSetInterface().GetGenericArguments()[0] + : listType.GetListInterface().GetGenericArguments()[0]; + + if (listType.IsGenericType()) + { + if (!isSet && listType.GetGenericTypeDefinition() == typeof(IList<>)) + { + listType = typeof(List<>).MakeGenericType(elementType); + } + else + { + if (isSet && listType.GetGenericTypeDefinition() == typeof(ISet<>)) + { + listType = typeof(HashSet<>).MakeGenericType(elementType); + } + } + } + + var addMtd = listType.GetMethod("Add"); + + var doRead = Emit.DefineLabel(GetNextName()); + var done = Emit.DefineLabel(GetNextName()); + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + var isArray = listType.IsArray; + + Sigil.Label doneSkipCharNull = null; + + if (isArray) + { + listType = typeof(List<>).MakeGenericType(elementType); + addMtd = listType.GetMethod("Add"); + doneSkipCharNull = Emit.DefineLabel(GetNextName()); + } + + using (var loc = Emit.DeclareLocal(listType, GetNextName())) + { + Action loadList; + + if (!listType.IsValueType()) + { + loadList = () => Emit.LoadLocal(loc); + + ExpectRawCharOrNull( + '[', + () => { }, + () => + { + Emit.LoadNull(); + + if (isArray) + { + Emit.Branch(doneSkipCharNull); + } + else + { + Emit.Branch(doneSkipChar); + } + } + ); + Emit.Branch(doRead); + } + else + { + loadList = () => Emit.LoadLocalAddress(loc); + + ExpectChar('['); + } + + Emit.MarkLabel(doRead); // --empty-- + if (listType.IsValueType()) + { + Emit.LoadLocalAddress(loc); // listType* + Emit.InitializeObject(listType); // --empty-- + } + else + { + var listCons = listType.GetPublicOrPrivateConstructor(); + if (listCons == null) throw new ConstructionException("Expected a parameterless constructor for " + listType); + + Emit.NewObject(listCons); // listType + Emit.StoreLocal(loc); // --empty-- + } + + // first step unrolled, cause ',' isn't legal + ConsumeWhiteSpace(); // --empty-- + loadList(); // listType + RawPeekChar(); // listType int + Emit.LoadConstant(']'); // listType int ']' + Emit.BranchIfEqual(done); // listType(*?) + Build(listMember, elementType); // listType(*?) elementType + Emit.CallVirtual(addMtd); // --empty-- + if (isSet) Emit.Pop(); // if it's a set, Add() returns a bool which we need to pop off the stack + + var startLoop = Emit.DefineLabel(GetNextName()); + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(startLoop); // --empty-- + loadList(); // listType(*?) + ReadSkipWhitespace(); // listType(*?) int + ThrowIfEmptyAndWasExpecting(",", "]"); // listType(*?) int + + Emit.Duplicate(); // listType(*?) int int + Emit.LoadConstant(','); // listType(*?) int int ',' + Emit.BranchIfEqual(nextItem); // listType(*?) int + Emit.LoadConstant(']'); // listType(*?) int ']' + Emit.BranchIfEqual(doneSkipChar); // listType(*?) + + // didn't get what we expected + ThrowExpected(",", "]"); + + Emit.MarkLabel(nextItem); // listType(*?) int + Emit.Pop(); // listType(*?) + ConsumeWhiteSpace(); // listType(*?) + Build(listMember, elementType); // listType(*?) elementType + Emit.CallVirtual(addMtd); // --empty-- + if (isSet) Emit.Pop(); // if it's a set, Add() returns a bool which we need to pop off the stack + Emit.Branch(startLoop); // --empty-- + + Emit.MarkLabel(done); // listType(*?) + ReadCharFromStream(); // listType(*?) int + Emit.Pop(); // listType(*?) + + Emit.MarkLabel(doneSkipChar); // listType(*?) + + if (isArray) + { + var toArray = listType.GetMethod("ToArray"); + Emit.Call(toArray); // elementType[] + + Emit.MarkLabel(doneSkipCharNull); + } + } + } + + void ReadDictionary(MemberInfo dictionaryMember, Type dictType) + { + var keyType = dictType.GetDictionaryInterface().GetGenericArguments()[0]; + + var keyIsString = keyType == typeof(string); + var keyIsInteger = keyType.IsIntegerNumberType(); + var keyIsEnum = keyType.IsEnum(); + + if (!(keyIsString || keyIsInteger || keyIsEnum)) throw new ConstructionException("Only dictionaries with strings, integers, or enums for keys can be deserialized"); + var valType = dictType.GetDictionaryInterface().GetGenericArguments()[1]; + + if (dictType.IsGenericType() && dictType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) + { + dictType = typeof(Dictionary<,>).MakeGenericType(keyType, valType); + } + + var addMtd = dictType.GetDictionaryInterface().GetMethod("Add", new[] { keyType, valType }); + + var done = Emit.DefineLabel(GetNextName()); + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + if (!dictType.IsValueType()) + { + ExpectRawCharOrNull( + '{', + () => { }, + () => + { + Emit.LoadNull(); + Emit.Branch(doneSkipChar); + } + ); + } + else + { + ExpectChar('{'); + } + + using (var loc = Emit.DeclareLocal(dictType, GetNextName())) + { + Action loadDict; + if (dictType.IsValueType()) + { + Emit.LoadLocalAddress(loc); // dictType* + Emit.InitializeObject(dictType); // --empty-- + + loadDict = () => Emit.LoadLocalAddress(loc); + } + else + { + var dictCons = dictType.GetPublicOrPrivateConstructor(); + if (dictCons == null) throw new ConstructionException("Expected a parameterless constructor for " + dictType); + + Emit.NewObject(dictCons); // dictType + Emit.StoreLocal(loc); // --empty-- + + loadDict = () => Emit.LoadLocal(loc); + } + + var loopStart = Emit.DefineLabel(GetNextName()); + + ConsumeWhiteSpace(); // --empty-- + loadDict(); // dictType(*?) + RawPeekChar(); // dictType(*?) int + Emit.LoadConstant('}'); // dictType(*?) int '}' + Emit.BranchIfEqual(done); // dictType(*?) + if (keyType == typeof(string)) + { + Build(dictionaryMember, typeof(string)); // dictType(*?) string + } + else + { + if (keyIsInteger || (keyIsEnum && dictionaryMember != null && dictionaryMember.ShouldConvertEnum(keyType))) + { + ExpectQuote(); // dictType(*?) + Build(dictionaryMember, keyType); // dictType(*?) integer + ExpectQuote(); // dictType(*?) integer + } + else + { + Build(dictionaryMember, keyType); // dictType(*?) enum + } + } + ReadSkipWhitespace(); // dictType(*?) (integer|string|enum) + CheckChar(':'); // dictType(*?) (integer|string|enum) + ConsumeWhiteSpace(); // dictType(*?) (integer|string|enum) + Build(dictionaryMember, valType); // dictType(*?) (integer|string|enum) valType + Emit.CallVirtual(addMtd); // --empty-- + + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(loopStart); // --empty-- + loadDict(); // dictType(*?) + ReadSkipWhitespace(); // dictType(*?) int + ThrowIfEmptyAndWasExpecting(",", "}"); // dictType(*?) int + + Emit.Duplicate(); // dictType(*?) int int + Emit.LoadConstant(','); // dictType(*?) int int ',' + Emit.BranchIfEqual(nextItem); // dictType(*?) int + Emit.LoadConstant('}'); // dictType(*?) int '}' + Emit.BranchIfEqual(doneSkipChar); // dictType(*?) + + // didn't get what we expected + ThrowExpected(",", "}"); + + Emit.MarkLabel(nextItem); // dictType(*?) int + Emit.Pop(); // dictType(*?) + ConsumeWhiteSpace(); // dictType(*?) + if (keyType == typeof(string)) + { + Build(dictionaryMember, typeof(string)); // dictType(*?) string + } + else + { + if (keyIsInteger || (keyIsEnum && dictionaryMember != null && dictionaryMember.ShouldConvertEnum(keyType))) + { + ExpectQuote(); // dictType(*?) + Build(dictionaryMember, keyType); // dictType(*?) integer + ExpectQuote(); // dictType(*?) integer + } + else + { + Build(dictionaryMember, keyType); // dictType(*?) enum + } + } + ReadSkipWhitespace(); // dictType(*?) (integer|string|enum) + CheckChar(':'); // dictType(*?) (integer|string|enum) + ConsumeWhiteSpace(); // dictType(*?) (integer|string|enum) + Build(dictionaryMember, valType); // dictType(*?) (integer|string|enum) valType + Emit.CallVirtual(addMtd); // --empty-- + Emit.Branch(loopStart); // --empty-- + } + + Emit.MarkLabel(done); // dictType(*?) + ReadCharFromStream(); // dictType(*?) int + Emit.Pop(); // dictType(*?) + + Emit.MarkLabel(doneSkipChar); // dictType(*?) + } + + void SkipObjectMember() + { + Emit.LoadArgument(0); // TextReader + Emit.Call(Methods.GetSkip(ReadingFromString)); // --empty-- + } + + void LoadRecursiveTypeDelegate(Type recursiveType) + { + var typeCache = typeof(TypeCache<,>).MakeGenericType(OptionsType, recursiveType); + + FieldInfo thunk; + if (ReadingFromString) + { + thunk = typeCache.GetField("StringThunk", BindingFlags.Public | BindingFlags.Static); + } + else + { + thunk = typeCache.GetField("Thunk", BindingFlags.Public | BindingFlags.Static); + } + + Emit.LoadField(thunk); + } + + void ReadObject(Type objType) + { + var isAnonymous = objType.IsAnonymouseClass(); + + if (isAnonymous) + { + if (UseNameAutomata) + { + ReadAnonymousObjectAutomata(objType); + return; + } + + ReadAnonymousObjectDictionaryLookup(objType); + return; + } + + if (UseNameAutomata) + { + ReadObjectAutomata(objType); + return; + } + + ReadObjectDictionaryLookup(objType); + } + + void SkipAllMembers(Sigil.Label done, Sigil.Label doneSkipChar) + { + var continueSkipping = Emit.DefineLabel(GetNextName()); + + var skipEncodedString = Methods.GetSkipEncodedString(ReadingFromString); + + // first pass, doesn't check for , + ConsumeWhiteSpace(); // objType + RawPeekChar(); // objType char + Emit.LoadConstant('}'); // objType char '}' + Emit.BranchIfEqual(done); // objType + + Emit.LoadArgument(0); // objType TextReader + Emit.Call(skipEncodedString); // objType + ReadSkipWhitespace(); // objType + CheckChar(':'); // objType + ConsumeWhiteSpace(); // objType + SkipObjectMember(); // objType + Emit.Branch(continueSkipping); // objType + + // second (and third, and fourth, and ...) does check for , + Emit.MarkLabel(continueSkipping); // objType + ConsumeWhiteSpace(); // objType + RawPeekChar(); // objType char + Emit.LoadConstant('}'); // objType char '}' + Emit.BranchIfEqual(done); // objType + + // we Peek'd the }, we can just read for ',' + ExpectChar(','); // objType + + ConsumeWhiteSpace(); // objType + Emit.LoadArgument(0); // objType TextReader + Emit.Call(skipEncodedString); // objType + ReadSkipWhitespace(); // objType + CheckChar(':'); // objType + ConsumeWhiteSpace(); // objType + SkipObjectMember(); // objType + Emit.Branch(continueSkipping); // objType + + Emit.MarkLabel(done); // objType + ReadCharFromStream(); // objType int + Emit.Pop(); // objType + + Emit.MarkLabel(doneSkipChar); // objType(*?) + } + + void ReadObjectAutomata(Type objType) + { + var done = Emit.DefineLabel(GetNextName()); + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + if (!objType.IsValueType()) + { + ExpectRawCharOrNull( + '{', + () => { }, + () => + { + Emit.LoadNull(); + Emit.Branch(doneSkipChar); + } + ); + } + else + { + ExpectChar('{'); + } + + using (var loc = Emit.DeclareLocal(objType, GetNextName())) + { + Action loadObj; + if (objType.IsValueType()) + { + Emit.LoadLocalAddress(loc); // objType* + Emit.InitializeObject(objType); // --empty-- + + loadObj = () => Emit.LoadLocalAddress(loc); + } + else + { + var cons = objType.GetPublicOrPrivateConstructor(); + if (cons == null) throw new ConstructionException("Expected a parameterless constructor for " + objType); + + Emit.NewObject(cons); // objType + Emit.StoreLocal(loc); // --empty-- + + loadObj = () => Emit.LoadLocal(loc); + } + + var loopStart = Emit.DefineLabel(GetNextName()); + var serializationType = SerializationNameFormat.GetGenericTypeArgument(); + + var setterLookup = typeof(SetterLookup<,>).MakeGenericType(objType, serializationType); + var setterGetSetters = setterLookup.GetMethod("GetSetters", BindingFlags.Public | BindingFlags.Static); + + var setters = (Dictionary)setterGetSetters.Invoke(null, new object[0]); + + // special case object w/ no deserializable properties + if (setters.Count == 0) + { + loadObj(); // objType(*?) + + if (objType.IsValueType()) + { + Emit.LoadObject(objType); // objType + } + + SkipAllMembers(done, doneSkipChar); // objType + + return; + } + + var orderedSetters = + setters + .OrderBy(kv => kv.Key) + .Select((kv, i) => new { Index = i, Name = kv.Key, Setters = kv.Value, Label = Emit.DefineLabel(GetNextName()) }) + .ToList(); + + MethodInfo findSetterIdx; + if (ReadingFromString) + { + findSetterIdx = setterLookup.GetMethod("FindSetterIndexThunkReader", new[] { typeof(ThunkReader).MakeByRefType() }); + } + else + { + findSetterIdx = setterLookup.GetMethod("FindSetterIndex", new[] { typeof(TextReader) }); + } + + var inOrderLabels = + orderedSetters + .Select(o => o.Label) + .ToArray(); + + ConsumeWhiteSpace(); // --empty-- + loadObj(); // objType(*?) + RawPeekChar(); // objType(*?) int + Emit.LoadConstant('}'); // objType(*?) int '}' + Emit.BranchIfEqual(done); // objType(*?) + ReadSkipWhitespace(); // objType(*?) + + CheckQuote(); // objType(*?) + Emit.LoadArgument(0); // objType(*?) TextReader + Emit.Call(findSetterIdx); // objType(*?) int + + ReadSkipWhitespace(); // objType(*?) int + CheckChar(':'); // objType(*?) int + ConsumeWhiteSpace(); // objType(*?) int + + var readingMember = Emit.DefineLabel(GetNextName()); + Emit.MarkLabel(readingMember); // objType(*?) int + + using (var oLoc = Emit.DeclareLocal(GetNextName())) + { + var isMember = Emit.DefineLabel(GetNextName()); + + Emit.Duplicate(); // objType(*?) int int + Emit.StoreLocal(oLoc); // objType(*?) int + Emit.LoadConstant(0); // objType(*?) int int + Emit.BranchIfGreaterOrEqual(isMember); // objType(*?) + + Emit.Pop(); // --empty-- + SkipObjectMember(); // --empty-- + Emit.Branch(loopStart); // --empty-- + + Emit.MarkLabel(isMember); // objType(*?) + Emit.LoadLocal(oLoc); // objType(*?) int + Emit.Switch(inOrderLabels); // objType(*?) + + // fallthrough case + ThrowExpected("a member name"); // --empty-- + } + + foreach (var kv in orderedSetters) + { + var memberName = kv.Name; + var label = kv.Label; + var members = kv.Setters; + + if (members.Length == 1) + { + var member = members[0]; + + Emit.MarkLabel(label); // objType(*?) + ReadAndSetMember(member); // --empty-- + Emit.Branch(loopStart); // --empty-- + } + else + { + Emit.MarkLabel(label); // objType(*?) + ReadAndSetDiscriminantUnion(memberName, members); // --empty-- + Emit.Branch(loopStart); // --empty-- + } + } + + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(loopStart); // --empty-- + loadObj(); // objType(*?) + ReadSkipWhitespace(); // objType(*?) int + ThrowIfEmptyAndWasExpecting(",", "}"); // objType(*?) int + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant(','); // objType(*?) int int ',' + Emit.BranchIfEqual(nextItem); // objType(*?) int + Emit.LoadConstant('}'); // objType(*?) int '}' + Emit.BranchIfEqual(doneSkipChar); // objType(*?) + + // didn't get what we expected + ThrowExpected(",", "}"); + + Emit.MarkLabel(nextItem); // objType(*?) int + Emit.Pop(); // objType(*?) + ReadSkipWhitespace(); + + CheckQuote(); + Emit.LoadArgument(0); // TextReader + Emit.Call(findSetterIdx); // int + + ReadSkipWhitespace(); // objType(*?) int + CheckChar(':'); // objType(*?) int + ConsumeWhiteSpace(); // objType(*?) int + Emit.Branch(readingMember); // objType(*?) int + } + + Emit.MarkLabel(done); // objType(*?) + ReadCharFromStream(); // objType(*?) int + Emit.Pop(); // objType(*?) + + Emit.MarkLabel(doneSkipChar); // objType(*?) + + if (objType.IsValueType()) + { + Emit.LoadObject(objType); // objType + } + } + + void ReadAndSetMember(MemberInfo member) + { + // Stack starts + // objType(*?) + + var memberType = member.ReturnType(); + + var memberAttr = member.GetCustomAttribute(); + if (memberType.IsEnum() && memberAttr != null && memberAttr.TreatEnumerationAs != null) + { + var underlyingEnumType = Enum.GetUnderlyingType(memberType); + + Build(member, memberAttr.TreatEnumerationAs); // objType(*?) SerializeEnumerationAsType + Emit.Convert(underlyingEnumType); // objType(*?) memberType + } + else + { + Build(member, memberType); // objType(*?) memberType + } + + if (member is FieldInfo) + { + Emit.StoreField((FieldInfo)member); // --empty-- + } + else + { + SetProperty((PropertyInfo)member); // --empty-- + } + } + + static readonly MethodInfo Type_GetTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Public | BindingFlags.Static); + void ReadAndSetDiscriminantUnion(string memberName, MemberInfo[] union) + { + Dictionary discriminants; + MemberInfo unionTypeIndicator; + Dictionary charsets; + bool allowsNull; + + string errorMessage; + if (!Utils.CheckUnionLegality(DateFormat, memberName, union, out discriminants, out unionTypeIndicator, out charsets, out allowsNull, out errorMessage)) + { + throw new ConstructionException(errorMessage); + } + + var refMembers = discriminants.Where(kv => !kv.Value.ReturnType().IsValueType()).Select(kv => kv.Value).ToList(); + var nullableMembers = discriminants.Where(kv => kv.Value.ReturnType().IsNullableType()).Select(kv => kv.Value).ToList(); + var expected = discriminants.Keys.ToArray(); + + var streamNotEmpty = Emit.DefineLabel(GetNextName()); + var end = Emit.DefineLabel(GetNextName()); + + RawPeekChar(); // objType(*?) int + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant(-1); // objType(*?) int int -1 + Emit.UnsignedBranchIfNotEqual(streamNotEmpty); // objType(*?) int + + ThrowExpectedButEnded(expected); // --empty-- + + Emit.MarkLabel(streamNotEmpty); // objType(*?) int + + // _sigh_ strong names fuck with dynamic linking the UnionConfigLookup ASM + // just have to live with it for now +#if !STRONG_NAME + var canUseFastUnionLookup = true; +#else + var canUseFastUnionLookup = false; +#endif + + if (UseFastUnionLookup && canUseFastUnionLookup) + { + var allCharsets = UnionCharsets.None; + foreach (var kv in charsets) + { + allCharsets |= kv.Key; + } + + var config = UnionConfigLookup.Get(allCharsets, allowsNull); + var lookup = typeof(UnionLookup<>).MakeGenericType(config); + + var min = (int)lookup.GetField("MinimumChar").GetValue(null); + var lookupArr = lookup.GetField("Lookup"); + var lookupArrLen = ((int[])lookupArr.GetValue(null)).Length; + var charsetsInOrder = (UnionCharsets[])lookup.GetField("CharsetOrder").GetValue(null); + + var miss = Emit.DefineLabel(GetNextName()); + var labels = + charsetsInOrder + .Select( + c => + { + MemberInfo member; + + if (!charsets.TryGetValue(c, out member)) member = null; + + return Tuple.Create(Emit.DefineLabel(GetNextName()), member, c); + } + ) + .ToArray(); + var labelsArr = labels.Select(t => t.Item1).ToArray(); + + Emit.LoadConstant(min); // objType(*?) int int + Emit.Subtract(); // objType(*?) int + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant(lookupArrLen); // objType(*?) int int int + Emit.BranchIfGreaterOrEqual(miss); // objType(*?) int + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant(0); // objType(*?) int int int + Emit.BranchIfLess(miss); // objType(*?) int + using (var loc = Emit.DeclareLocal(GetNextName())) + { + Emit.StoreLocal(loc); // objType(*?) + Emit.LoadField(lookupArr); // objType(*?) int[] + Emit.LoadLocal(loc); // objType(*?) int[] int + } + Emit.LoadElement(); // objType(*?) int + Emit.Switch(labelsArr); // objType(*?) + + // fall through + ThrowExpected(expected); // --empty-- + + foreach (var t in labels) + { + var label = t.Item1; + var member = t.Item2; + var charset = t.Item3; + + Emit.MarkLabel(label); // objType(*?) + + if (charset == UnionCharsets.Null) + { + // have to special case null, since it can mean clearning multiple members + // as there isn't a 1-to-1 type-to-member map for the null value + + ExpectNullSetMembersToDefaultAndClearUnionTypeIndicator(refMembers, nullableMembers, unionTypeIndicator); + + Emit.Pop(); // --empty-- + Emit.Branch(end); // --empty-- + } + else + { + // set the indicator, __if__ one has actually be registered + // we don't want to do any work if they don't care to + if (unionTypeIndicator != null) + { + Emit.Duplicate(); // objType(*?) objType(*?) + Emit.LoadConstant(member.ReturnType()); // objType(*?) objType(*?) RuntimeTypeHandle + Emit.Call(Type_GetTypeFromHandle); // objType(*?) objType(*?) Type + + if (unionTypeIndicator is FieldInfo) + { + var asField = (FieldInfo)unionTypeIndicator; + Emit.StoreField(asField); // objType(*?) + } + else + { + var asProp = (PropertyInfo)unionTypeIndicator; + SetProperty(asProp); // objType(*?) + } + } + + ReadAndSetMember(member); // --empty-- + Emit.Branch(end); // --empty-- + } + } + + Emit.MarkLabel(miss); // objType(*?) int + ThrowExpected(expected); // --empty-- + + Emit.MarkLabel(end); // --empty-- + } + else + { + if (allowsNull) + { + var notNull = Emit.DefineLabel(GetNextName()); + + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant('n'); // objType(*?) int int 'n' + Emit.UnsignedBranchIfNotEqual(notNull); // objType(*?) int + + Emit.Pop(); + ExpectNullSetMembersToDefaultAndClearUnionTypeIndicator(refMembers, nullableMembers, unionTypeIndicator); + + Emit.Pop(); // --empty-- + Emit.Branch(end); // --empty-- + + Emit.MarkLabel(notNull); // objType(*?) int + } + + foreach (var charToMember in discriminants) + { + var c = charToMember.Key; + var member = charToMember.Value; + var nextChar = Emit.DefineLabel(GetNextName()); + + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant((int)c); // objType(*?) int int int + Emit.UnsignedBranchIfNotEqual(nextChar); // objType(*?) int + + Emit.Pop(); // objType(*?) + + // set the indicator, __if__ one has actually be registered + // we don't want to do any work if they don't care to + if (unionTypeIndicator != null) + { + Emit.Duplicate(); // objType(*?) objType(*?) + Emit.LoadConstant(member.ReturnType()); // objType(*?) objType(*?) RuntimeTypeHandle + Emit.Call(Type_GetTypeFromHandle); // objType(*?) objType(*?) Type + + if (unionTypeIndicator is FieldInfo) + { + var asField = (FieldInfo)unionTypeIndicator; + Emit.StoreField(asField); // objType(*?) + } + else + { + var asProp = (PropertyInfo)unionTypeIndicator; + SetProperty(asProp); // objType(*?) + } + } + + ReadAndSetMember(member); // --empty-- + Emit.Branch(end); // --empty-- + + Emit.MarkLabel(nextChar); // objType(*?) int + } + + ThrowExpected(expected); // --empty-- + + Emit.MarkLabel(end); // --empty-- + } + } + + void ExpectNullSetMembersToDefaultAndClearUnionTypeIndicator(List refMembers, List nullableMembers, MemberInfo unionTypeIndicator) + { + // top of stack + // ------------ + // objType(*?) + + ExpectChar('n'); // objType(*?) + ExpectChar('u'); // objType(*?) + ExpectChar('l'); // objType(*?) + ExpectChar('l'); // objType(*?) + + foreach (var r in refMembers) + { + Emit.Duplicate(); // objType(*?) objType(*?) + Emit.LoadNull(); // objType(*?) objType(*?) null + var asProp = r as PropertyInfo; + if (asProp != null) + { + SetProperty(asProp); // objType(*?) + } + else + { + Emit.StoreField((FieldInfo)r); // objType(*?) + } + } + + foreach (var n in nullableMembers) + { + Emit.Duplicate(); // objType(*?) objType(*?) + using (var nLoc = Emit.DeclareLocal(n.ReturnType(), GetNextName())) + { + Emit.LoadLocalAddress(nLoc); // objType(*?) objType(*?) Nullable* + Emit.InitializeObject(n.ReturnType()); // objType(*?) objType(*?) + Emit.LoadLocal(nLoc); // objType(*?) objType(*?) Nullable + } + var asProp = n as PropertyInfo; + if (asProp != null) + { + SetProperty(asProp); // objType(*?) + } + else + { + Emit.StoreField((FieldInfo)n); // objType(*?) + } + } + + if (unionTypeIndicator != null) + { + Emit.Duplicate(); // objType(*?) objType(*?) + Emit.LoadNull(); // objType(*?) objType(*?) null + var asProp = unionTypeIndicator as PropertyInfo; + if (asProp != null) + { + SetProperty(asProp); // objType(*?) + } + else + { + var asField = (FieldInfo)unionTypeIndicator; + Emit.StoreField(asField); // objType(*?) + } + } + } + + void ReadObjectDictionaryLookup(Type objType) + { + var done = Emit.DefineLabel(GetNextName()); + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + if (!objType.IsValueType()) + { + ExpectRawCharOrNull( + '{', + () => { }, + () => + { + Emit.LoadNull(); + Emit.Branch(doneSkipChar); + } + ); + } + else + { + ExpectChar('{'); + } + + using (var loc = Emit.DeclareLocal(objType, GetNextName())) + { + Action loadObj; + if (objType.IsValueType()) + { + Emit.LoadLocalAddress(loc); // objType* + Emit.InitializeObject(objType); // --empty-- + + loadObj = () => Emit.LoadLocalAddress(loc); + } + else + { + var cons = objType.GetPublicOrPrivateConstructor(); + if (cons == null) throw new ConstructionException("Expected a parameterless constructor for " + objType); + + Emit.NewObject(cons); // objType + Emit.StoreLocal(loc); // --empty-- + + loadObj = () => Emit.LoadLocal(loc); + } + + var loopStart = Emit.DefineLabel(GetNextName()); + var serializationType = SerializationNameFormat.GetGenericTypeArgument(); + + var setterLookup = typeof(SetterLookup<,>).MakeGenericType(objType, serializationType); + + var setters = (Dictionary)setterLookup.GetMethod("GetSetters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[0]); + + // special case object w/ no deserializable properties + if (setters.Count == 0) + { + loadObj(); // objType(*?) + + if (objType.IsValueType()) + { + Emit.LoadObject(objType); // objType + } + + SkipAllMembers(done, doneSkipChar); // objType + + return; + } + + var tryGetValue = typeof(Dictionary).GetMethod("TryGetValue"); + + var order = setterLookup.GetField("Lookup", BindingFlags.Public | BindingFlags.Static); + var orderInst = (Dictionary)order.GetValue(null); + var labels = setters.ToDictionary(d => d.Key, d => Emit.DefineLabel(GetNextName())); + + var inOrderLabels = labels.OrderBy(l => orderInst[l.Key]).Select(l => l.Value).ToArray(); + + ConsumeWhiteSpace(); // --empty-- + loadObj(); // objType(*?) + RawPeekChar(); // objType(*?) int + Emit.LoadConstant('}'); // objType(*?) int '}' + Emit.BranchIfEqual(done); // objType(*?) + Emit.LoadField(order); // objType(*?) Dictionary string + Build(null, typeof(string)); // obType(*?) Dictionary string + ReadSkipWhitespace(); // objType(*?) Dictionary string + CheckChar(':'); // objType(*?) Dictionary string + ConsumeWhiteSpace(); // objType(*?) Dictionary string + + var readingMember = Emit.DefineLabel(GetNextName()); + Emit.MarkLabel(readingMember); // objType(*?) Dictionary string + + using (var oLoc = Emit.DeclareLocal(GetNextName())) + { + var isMember = Emit.DefineLabel(GetNextName()); + + Emit.LoadLocalAddress(oLoc); // objType(*?) Dictionary string int* + Emit.Call(tryGetValue); // objType(*?) bool + Emit.BranchIfTrue(isMember); // objType(*?) + + Emit.Pop(); // --empty-- + SkipObjectMember(); // --empty-- + Emit.Branch(loopStart); // --empty-- + + Emit.MarkLabel(isMember); // objType(*?) + Emit.LoadLocal(oLoc); // objType(*?) int + Emit.Switch(inOrderLabels); // objType(*?) + + // fallthrough case + ThrowExpected("a member name"); // --empty-- + } + + foreach (var kv in labels) + { + var memberName = kv.Key; + var label = kv.Value; + var members = setters[kv.Key]; + + if (members.Length == 1) + { + var member = members[0]; + + Emit.MarkLabel(label); // objType(*?) + ReadAndSetMember(member); // --empty-- + Emit.Branch(loopStart); // --empty-- + } + else + { + Emit.MarkLabel(label); // objType(*?) + ReadAndSetDiscriminantUnion(memberName, members); // --empty-- + Emit.Branch(loopStart); // --empty-- + } + } + + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(loopStart); // --empty-- + loadObj(); // objType(*?) + ReadSkipWhitespace(); // objType(*?) int + ThrowIfEmptyAndWasExpecting(",", "}"); // objType(*?) int + + Emit.Duplicate(); // objType(*?) int int + Emit.LoadConstant(','); // objType(*?) int int ',' + Emit.BranchIfEqual(nextItem); // objType(*?) int + Emit.LoadConstant('}'); // objType(*?) int '}' + Emit.BranchIfEqual(doneSkipChar); // objType(*?) + + // didn't get what we expected + ThrowExpected(",", "}"); + + Emit.MarkLabel(nextItem); // objType(*?) int + Emit.Pop(); // objType(*?) + ConsumeWhiteSpace(); + Emit.LoadField(order); // objType(*?) Dictionary string + Build(null, typeof(string)); // objType(*?) Dictionary string + ReadSkipWhitespace(); // objType(*?) Dictionary string + CheckChar(':'); // objType(*?) Dictionary string + ConsumeWhiteSpace(); // objType(*?) Dictionary string + Emit.Branch(readingMember); // objType(*?) Dictionary string + } + + Emit.MarkLabel(done); // objType(*?) + ReadCharFromStream(); // objType(*?) int + Emit.Pop(); // objType(*?) + + Emit.MarkLabel(doneSkipChar); // objType(*?) + + if (objType.IsValueType()) + { + Emit.LoadObject(objType); // objType + } + } + + void ReadAnonymousObjectDictionaryLookup(Type objType) + { + var doneNotNull = Emit.DefineLabel(GetNextName()); + var doneNull = Emit.DefineLabel(GetNextName()); + + ExpectRawCharOrNull( + '{', + () => { }, + () => + { + Emit.Branch(doneNull); + } + ); + + var cons = objType.GetConstructors().Single(); + + var setterLookup = typeof(AnonymousTypeLookup<>).MakeGenericType(objType); + var propertyMap = (Dictionary>)setterLookup.GetField("ParametersToTypeAndIndex").GetValue(null); + + if (propertyMap.Count == 0) + { + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + Emit.NewObject(cons); // objType + Emit.Branch(doneNotNull); // objType + + Emit.MarkLabel(doneNull); // null + Emit.LoadNull(); // null + Emit.Branch(doneSkipChar); + + Emit.MarkLabel(doneNotNull); // objType + + var doneSkipping = Emit.DefineLabel(GetNextName()); + + SkipAllMembers(doneSkipping, doneSkipChar); // objType + + return; + } + + var order = setterLookup.GetField("Lookup", BindingFlags.Public | BindingFlags.Static); + var tryGetValue = typeof(Dictionary).GetMethod("TryGetValue"); + var orderInst = (Dictionary)order.GetValue(null); + + var localMap = new Dictionary(); + foreach (var kv in propertyMap) + { + localMap[kv.Key] = Emit.DeclareLocal(kv.Value.Item1, GetNextName()); + } + + var labels = orderInst.ToDictionary(d => d.Key, d => Emit.DefineLabel(GetNextName())); + var inOrderLabels = labels.OrderBy(l => orderInst[l.Key]).Select(l => l.Value).ToArray(); + + var loopStart = Emit.DefineLabel(GetNextName()); + + ConsumeWhiteSpace(); // --empty-- + RawPeekChar(); // int + Emit.LoadConstant('}'); // int '}' + Emit.BranchIfEqual(doneNotNull); // --empty-- + Emit.LoadField(order); // Dictionary string + Build(null, typeof(string)); // Dictionary string + ReadSkipWhitespace(); // Dictionary string + CheckChar(':'); // Dictionary string + ConsumeWhiteSpace(); // Dictionary string + + var readingMember = Emit.DefineLabel(GetNextName()); + Emit.MarkLabel(readingMember); // Dictionary string + + using (var oLoc = Emit.DeclareLocal(GetNextName())) + { + var isMember = Emit.DefineLabel(GetNextName()); + + Emit.LoadLocalAddress(oLoc); // Dictionary string int* + Emit.Call(tryGetValue); // bool + Emit.BranchIfTrue(isMember); // --empty-- + + SkipObjectMember(); // --empty-- + Emit.Branch(loopStart); // --empty-- + + Emit.MarkLabel(isMember); // --empty-- + Emit.LoadLocal(oLoc); // int + Emit.Switch(inOrderLabels); // --empty-- + + // fallthrough case + ThrowExpected("a member name"); // --empty-- + } + + foreach (var kv in labels) + { + var label = kv.Value; + var local = localMap[kv.Key]; + + Emit.MarkLabel(label); // --empty-- + Build(null, local.LocalType); // localType + + Emit.StoreLocal(local); // --empty-- + + Emit.Branch(loopStart); // --empty-- + } + + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(loopStart); // --empty-- + ConsumeWhiteSpace(); // --empty-- + RawPeekChar(); // int + ThrowIfEmptyAndWasExpecting(",", "}"); // int + + Emit.Duplicate(); // int int + Emit.LoadConstant(','); // int int ',' + Emit.BranchIfEqual(nextItem); // int + Emit.LoadConstant('}'); // int '}' + Emit.BranchIfEqual(doneNotNull); // --empty-- + + // didn't get what we expected + ThrowExpected(",", "}"); + + Emit.MarkLabel(nextItem); // int + Emit.Pop(); // --empty-- + ReadCharFromStream(); // int + Emit.Pop(); // --empty-- + ConsumeWhiteSpace(); // --empty-- + Emit.LoadField(order); // Dictionary string + Build(null, typeof(string)); // Dictionary string + ReadSkipWhitespace(); // Dictionary string + CheckChar(':'); // Dictionary string + ConsumeWhiteSpace(); // Dictionary string + Emit.Branch(readingMember); // Dictionary string + + Emit.MarkLabel(doneNotNull); // --empty-- + ReadCharFromStream(); // int + Emit.Pop(); // --empty-- + + var done = Emit.DefineLabel(GetNextName()); + + foreach (var kv in propertyMap.OrderBy(o => o.Value.Item2)) + { + var local = localMap[kv.Key]; + Emit.LoadLocal(local); + } + + Emit.NewObject(cons); // objType + Emit.Branch(done); // objType + + Emit.MarkLabel(doneNull); // --empty-- + Emit.LoadNull(); // null + + Emit.MarkLabel(done); // objType + + // free up all those locals for use again + foreach (var kv in localMap) + { + kv.Value.Dispose(); + } + } + + void ReadAnonymousObjectAutomata(Type objType) + { + var doneNotNull = Emit.DefineLabel(GetNextName()); + var doneNotNullPopSkipChar = Emit.DefineLabel(GetNextName()); + var doneNotNullSkipChar = Emit.DefineLabel(GetNextName()); + var doneNull = Emit.DefineLabel(GetNextName()); + + ExpectRawCharOrNull( + '{', + () => { }, + () => + { + Emit.Branch(doneNull); + } + ); + + var cons = objType.GetConstructors().Single(); + + var setterLookup = typeof(AnonymousTypeLookup<>).MakeGenericType(objType); + + MethodInfo findConstructorParameterIndex; + if (ReadingFromString) + { + findConstructorParameterIndex = setterLookup.GetMethod("FindConstructorParameterIndexThunkReader", new[] { typeof(ThunkReader).MakeByRefType() }); + } + else + { + findConstructorParameterIndex = setterLookup.GetMethod("FindConstructorParameterIndex", new[] { typeof(TextReader) }); + } + + var propertyMap = (Dictionary>)setterLookup.GetField("ParametersToTypeAndIndex").GetValue(null); + + if (propertyMap.Count == 0) + { + var doneSkipChar = Emit.DefineLabel(GetNextName()); + + Emit.NewObject(cons); // objType + Emit.Branch(doneNotNull); // objType + + Emit.MarkLabel(doneNull); // null + Emit.LoadNull(); // null + Emit.Branch(doneSkipChar); + + Emit.MarkLabel(doneNotNull); // objType + + var doneSkipping = Emit.DefineLabel(GetNextName()); + + SkipAllMembers(doneSkipping, doneSkipChar); // objType + + return; + } + + var localMap = new Dictionary(); + foreach (var kv in propertyMap) + { + localMap[kv.Key] = Emit.DeclareLocal(kv.Value.Item1, GetNextName()); + } + + var labels = + propertyMap + .ToDictionary(d => d.Key, d => Emit.DefineLabel(GetNextName())); + + var inOrderLabels = + propertyMap + .OrderBy(l => l.Value.Item2) + .Select(l => labels[l.Key]) + .ToArray(); + + var loopStart = Emit.DefineLabel(GetNextName()); + + ReadSkipWhitespace(); // int + Emit.Duplicate(); + Emit.LoadConstant('}'); // int '}' + Emit.BranchIfEqual(doneNotNullPopSkipChar); // --empty-- + + CheckQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + Emit.Call(findConstructorParameterIndex); // int + + ReadSkipWhitespace(); // int + CheckChar(':'); // int + ConsumeWhiteSpace(); // int + + var readingMember = Emit.DefineLabel(GetNextName()); + Emit.MarkLabel(readingMember); // int + + Emit.Switch(inOrderLabels); // --empty-- + SkipObjectMember(); // --empty-- + + foreach (var kv in labels) + { + var label = kv.Value; + var local = localMap[kv.Key]; + + Emit.MarkLabel(label); // --empty-- + Build(null, local.LocalType); // localType + + Emit.StoreLocal(local); // --empty-- + + Emit.Branch(loopStart); // --empty-- + } + + var nextItem = Emit.DefineLabel(GetNextName()); + + Emit.MarkLabel(loopStart); // --empty-- + ReadSkipWhitespace(); // int + ThrowIfEmptyAndWasExpecting(",", "}"); // int + + Emit.Duplicate(); // int int + Emit.LoadConstant(','); // int int ',' + Emit.BranchIfEqual(nextItem); // int + Emit.LoadConstant('}'); // int '}' + Emit.BranchIfEqual(doneNotNullSkipChar); // --empty-- + + // didn't get what we expected + ThrowExpected(",", "}"); + + Emit.MarkLabel(nextItem); // int + Emit.Pop(); // --empty-- + ReadSkipWhitespace(); // --empty-- + + CheckQuote(); // --empty-- + Emit.LoadArgument(0); // TextReader + Emit.Call(findConstructorParameterIndex); // int + + ReadSkipWhitespace(); // int + CheckChar(':'); // int + ConsumeWhiteSpace(); // int + Emit.Branch(readingMember); // int + + Emit.MarkLabel(doneNotNull); // --empty-- + ReadCharFromStream(); // int + + Emit.MarkLabel(doneNotNullPopSkipChar); + Emit.Pop(); // --empty-- + + Emit.MarkLabel(doneNotNullSkipChar);// --empty-- + + var done = Emit.DefineLabel(GetNextName()); + + foreach (var kv in propertyMap.OrderBy(o => o.Value.Item2)) + { + var local = localMap[kv.Key]; + Emit.LoadLocal(local); + } + + Emit.NewObject(cons); // objType + Emit.Branch(done); // objType + + Emit.MarkLabel(doneNull); // --empty-- + Emit.LoadNull(); // null + + Emit.MarkLabel(done); // objType + + // free up all those locals for use again + foreach (var kv in localMap) + { + kv.Value.Dispose(); + } + } + + static ConstructorInfo OptionsCons = typeof(Options).GetConstructor(new[] { typeof(bool), typeof(bool), typeof(bool), typeof(DateTimeFormat), typeof(bool), typeof(UnspecifiedDateTimeKindBehavior), typeof(SerializationNameFormat) }); + static ConstructorInfo ObjectBuilderCons = typeof(Jil.DeserializeDynamic.ObjectBuilder).GetConstructor(new[] { typeof(Options) }); + void ReadDynamic() + { + using (var dyn = Emit.DeclareLocal(GetNextName())) + { + Emit.LoadArgument(0); // TextReader + Emit.LoadConstant(false); // TextReader bool + Emit.LoadConstant(false); // TextReader bool bool + Emit.LoadConstant(false); // TextReader bool bool bool + Emit.LoadConstant((byte)DateFormat); // TextReader bool bool bool byte + Emit.LoadConstant(false); // TextReader bool bool bool byte bool + Emit.LoadConstant((byte)UnspecifiedDateTimeKindBehavior.IsLocal); // TextReader bool bool bool byte bool byte + Emit.LoadConstant((byte)SerializationNameFormat.Verbatim); // TextReader bool bool bool byte bool byte byte + Emit.NewObject(OptionsCons); // TextReader Options + Emit.NewObject(ObjectBuilderCons); // TextReader ObjectBuilder + Emit.StoreLocal(dyn); // TextReader + Emit.LoadLocal(dyn); // TextReader ObjectBuilder + + var deserializeDyn = Jil.DeserializeDynamic.DynamicDeserializer.GetDeserializeMember(ReadingFromString); + + Emit.Call(deserializeDyn); // --empty-- + Emit.LoadLocal(dyn); // ObjectBuilder + Emit.LoadField(Jil.DeserializeDynamic.ObjectBuilder._BeingBuilt); // JsonObject + } + } + + void Build(MemberInfo forMember, Type forType, bool allowRecursion = true, bool fromNullable = false) + { + // EXACT MATCH, this is the best way to detect `dynamic` + if (forType == typeof(object)) + { + ReadDynamic(); + return; + } + + if (forType.IsNullableType()) + { + ReadNullable(forMember, forType); + return; + } + + if (forType.IsPrimitiveType()) + { + ReadPrimitive(forType); + return; + } + + if (forType.IsPrimitiveWrapper()) + { + ReadPrimitiveTypeWrapper(forType); + return; + } + + if (forType.IsDictionaryType()) + { + ReadDictionary(forMember, forType); + return; + } + + if (forType.IsGenericReadOnlyDictionary()) + { + var keyType = forType.GetGenericArguments()[0]; + var valueType = forType.GetGenericArguments()[1]; + var fakeDictionary = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); + ReadDictionary(forMember, fakeDictionary); + return; + } + + if (forType.IsListType()) + { + ReadList(forMember, forType, false); + return; + } + + if (forType.IsSetType()) + { + ReadList(forMember, forType, true); + return; + } + + // Final, special, case for ICollection, IEnumerable, and IReadOnlyList if *not* a List or an ISet + // We can make this work by just acting like it *is* a List + if (forType.IsConstructedGenericType) + { + var genTypeDef = forType.GetGenericTypeDefinition(); + if (genTypeDef == typeof(ICollection<>) || genTypeDef == typeof(IEnumerable<>) || genTypeDef == typeof(IReadOnlyList<>)) + { + var elementType = forType.GetGenericArguments()[0]; + var fakeList = typeof(List<>).MakeGenericType(elementType); + ReadList(forMember, fakeList, false); + return; + } + } + + if (forType.IsEnum()) + { + Type convertEnumTo; + if (forMember != null && forMember.ShouldConvertEnum(forType, out convertEnumTo)) + { + var underlyingEnumType = Enum.GetUnderlyingType(forType); + + Build(forMember, convertEnumTo); + Emit.Convert(underlyingEnumType); + return; + } + + ReadEnum(forType, fromNullable); + return; + } + + if (allowRecursion && IndirectTypes.Contains(forType)) + { + Type funcType; + + if (ReadingFromString) + { + funcType = typeof(StringThunkDelegate<>).MakeGenericType(forType); + } + else + { + funcType = typeof(Func<,,>).MakeGenericType(typeof(TextReader), typeof(int), forType); + } + var funcInvoke = funcType.GetMethod("Invoke"); + + LoadRecursiveTypeDelegate(forType); // Func + Emit.LoadArgument(0); // Func TextReader + Emit.LoadArgument(1); // Func TextReader int + Emit.LoadConstant(1); // Func TextReader int int + Emit.Add(); // Func TextReader int + Emit.Call(funcInvoke); // memberType + return; + } + + if (forType.IsSimpleInterface()) + { + var interfaceImpl = typeof(InterfaceImplementation<>).MakeGenericType(forType); + var interfaceImplType = (Type)interfaceImpl.GetField("Proxy").GetValue(null); + + ReadObject(interfaceImplType); + return; + } + + ReadObject(forType); + } + + HashSet FindAndPrimeIndirectTypes(Type forType) + { + var ret = forType.FindRecursiveOrReusedTypes(); + + if(PreferIndirectSerialization) + { + var subTypes = forType.FindChildTypes(); + foreach(var t in subTypes) + { + ret.Add(t); + } + } + + + foreach (var primeType in ret) + { + MethodInfo loadMtd; + if (ReadingFromString) + { + loadMtd = typeof(TypeCache<,>).MakeGenericType(OptionsType, primeType).GetMethod("LoadFromString", BindingFlags.Public | BindingFlags.Static); + } + else + { + loadMtd = typeof(TypeCache<,>).MakeGenericType(OptionsType, primeType).GetMethod("Load", BindingFlags.Public | BindingFlags.Static); + } + + loadMtd.Invoke(null, new object[0]); + } + + return ret; + } + + void BuildWithNew(Type forType) + { + AddGlobalVariables(); + + ConsumeWhiteSpace(); + + Build(null, forType, allowRecursion: false); + + // we have to consume this, otherwise we might succeed with invalid JSON + ConsumeWhiteSpace(); + + // We also must confirm that we read everything, again otherwise we might accept garbage as valid + ExpectEndOfStream(); + + Emit.Return(); + } + + public Func BuildWithNewDelegate(out int approximateILCount) + { + var forType = typeof(ForType); + + IndirectTypes = FindAndPrimeIndirectTypes(forType); + + Emit = Emit.NewDynamicMethod(forType, new[] { typeof(TextReader), typeof(int) }, doVerify: Utils.DoVerify); + + BuildWithNew(forType); + + var ret = Emit.CreateDelegate>(out var il, Utils.DelegateOptimizationOptions); + + approximateILCount = il.Count(c => c == '\n'); // VERY approximate + + return ret; + } + + public StringThunkDelegate BuildFromStringWithNewDelegate(out int approximateILCount) + { + var forType = typeof(ForType); + + IndirectTypes = FindAndPrimeIndirectTypes(forType); + + Emit = Emit.NewDynamicMethod(forType, new[] { typeof(ThunkReader).MakeByRefType(), typeof(int) }, doVerify: Utils.DoVerify); + + BuildWithNew(forType); + + var ret = Emit.CreateDelegate>(out var il, Utils.DelegateOptimizationOptions); + + approximateILCount = il.Count(c => c == '\n'); // VERY approximate + + return ret; + } + } + + static class InlineDeserializerHelper + { + static Func BuildAlwaysFailsWithFromStream(Type optionsType) + { + var specificTypeCache = typeof(TypeCache<,>).MakeGenericType(optionsType, typeof(ReturnType)); + var stashField = specificTypeCache.GetField("ExceptionDuringBuildFromStream", BindingFlags.Static | BindingFlags.Public); + + var emit = Emit.NewDynamicMethod(typeof(ReturnType), new[] { typeof(TextReader), typeof(int) }); + emit.LoadConstant("Error occurred building a deserializer for " + typeof(ReturnType)); + emit.LoadField(stashField); + emit.LoadConstant(false); + emit.NewObject(); + emit.Throw(); + + return emit.CreateDelegate>(Utils.DelegateOptimizationOptions); + } + + static StringThunkDelegate BuildAlwaysFailsWithFromString(Type optionsType) + { + var specificTypeCache = typeof(TypeCache<,>).MakeGenericType(optionsType, typeof(ReturnType)); + var stashField = specificTypeCache.GetField("ExceptionDuringBuildFromString", BindingFlags.Static | BindingFlags.Public); + + var emit = Emit.NewDynamicMethod(typeof(ReturnType), new[] { typeof(ThunkReader).MakeByRefType(), typeof(int) }); + emit.LoadConstant("Error occurred building a deserializer for " + typeof(ReturnType)); + emit.LoadField(stashField); + emit.LoadConstant(false); + emit.NewObject(); + emit.Throw(); + + return emit.CreateDelegate>(Utils.DelegateOptimizationOptions); + } + + public static Func BuildFromStream(Type optionsType, DateTimeFormat dateFormat, SerializationNameFormat serializationNameFormat, out Exception exceptionDuringBuild) + { + var obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: false, preferIndirectSerialization: false, allPrimitivesThroughHelpers: false); + + Func ret; + try + { + ret = obj.BuildWithNewDelegate(out var size); + + if(size > Utils.MAX_IL_INSTRUCTION_LIMIT) + { + if (typeof(ReturnType).FindChildTypes().Any()) + { + obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: false, preferIndirectSerialization: true, allPrimitivesThroughHelpers: false); + ret = obj.BuildWithNewDelegate(out size); + } + + if(size > Utils.MAX_IL_INSTRUCTION_LIMIT) + { + obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: false, preferIndirectSerialization: true, allPrimitivesThroughHelpers: true); + ret = obj.BuildWithNewDelegate(out size); + } + } + + exceptionDuringBuild = null; + } + catch (ConstructionException e) + { + exceptionDuringBuild = e; + ret = BuildAlwaysFailsWithFromStream(optionsType); + } + + return ret; + } + + public static StringThunkDelegate BuildFromString(Type optionsType, DateTimeFormat dateFormat, SerializationNameFormat serializationNameFormat, out Exception exceptionDuringBuild) + { + var obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: true, preferIndirectSerialization: false, allPrimitivesThroughHelpers: false); + + StringThunkDelegate ret; + try + { + ret = obj.BuildFromStringWithNewDelegate(out var size); + + if (size > Utils.MAX_IL_INSTRUCTION_LIMIT) + { + if (typeof(ReturnType).FindChildTypes().Any()) + { + obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: true, preferIndirectSerialization: true, allPrimitivesThroughHelpers: false); + ret = obj.BuildFromStringWithNewDelegate(out size); + } + + if (size > Utils.MAX_IL_INSTRUCTION_LIMIT) + { + obj = new InlineDeserializer(optionsType, dateFormat, serializationNameFormat, readingFromString: true, preferIndirectSerialization: true, allPrimitivesThroughHelpers: true); + ret = obj.BuildFromStringWithNewDelegate(out size); + } + } + + exceptionDuringBuild = null; + } + catch (ConstructionException e) + { + exceptionDuringBuild = e; + ret = BuildAlwaysFailsWithFromString(optionsType); + } + + return ret; + } + } +} diff --git a/vendor/Jil/Deserialize/InterfaceImplementation.cs b/vendor/Jil/Deserialize/InterfaceImplementation.cs new file mode 100644 index 000000000..4ad3e2472 --- /dev/null +++ b/vendor/Jil/Deserialize/InterfaceImplementation.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Reflection.Emit; +using System.Text; +using System.Threading.Tasks; +using Jil.Common; +using Sigil.NonGeneric; + +namespace Jil.Deserialize +{ + static class InterfaceImplementation + { + public static readonly Type Proxy; + + static InterfaceImplementation() + { + var iType = typeof(Interface); + + var typeBuilder = + AssemblyBuilderContainer.ModBuilder.DefineType( + iType.Name + "Impl", + TypeAttributes.Class | TypeAttributes.Sealed, + typeof(object), + new[] { iType } + ); + + var allMembers = iType.GetAllInterfaceMembers(); + + foreach (var prop in allMembers.OfType()) + { + var propType = prop.ReturnType(); + + var propBuilder = typeBuilder.DefineProperty(prop.Name, prop.Attributes, propType, Type.EmptyTypes); + + var iGetter = prop.GetMethod; + var iSetter = prop.SetMethod; + + Func getBackingField; + { + FieldInfo backingField = null; + getBackingField = + () => + { + if (backingField == null) + { + backingField = typeBuilder.DefineField("_" + prop.Name + "_" + Guid.NewGuid(), prop.ReturnType(), FieldAttributes.Private); + } + + return backingField; + }; + } + + if (iGetter != null) + { + var accessor = iGetter.Attributes; + var name = iGetter.Name; + + accessor &= ~MethodAttributes.Abstract; + + var emit = Sigil.NonGeneric.Emit.BuildInstanceMethod(propType, Type.EmptyTypes, typeBuilder, name, accessor); + + // property could be populated, so we need a real implementation + emit.LoadArgument(0); + emit.LoadField(getBackingField()); + emit.Return(); + + var getter = emit.CreateMethod(); + propBuilder.SetGetMethod(getter); + } + + // If there's a getter we want to *add* a setter + // and, of course, if there's a setter in the interface + // we have to define one anyway + if (iGetter != null || iSetter != null) + { + var accessor = iSetter != null ? iSetter.Attributes : MethodAttributes.Private; + var name = iSetter != null ? iSetter.Name : "set_" + prop.Name; + + accessor &= ~MethodAttributes.Abstract; + + var emit = Sigil.NonGeneric.Emit.BuildInstanceMethod(typeof(void), new[] { propType }, typeBuilder, name, accessor); + + if (iGetter != null) + { + // property can be read, so setter needs a real impl + emit.LoadArgument(0); + emit.LoadArgument(1); + emit.StoreField(getBackingField()); + emit.Return(); + } + else + { + // property can never be read (no getter), so this is a no-op + emit.Return(); + } + + var setter = emit.CreateMethod(); + propBuilder.SetSetMethod(setter); + } + } + + var proxyInfo = typeBuilder.CreateTypeInfo(); + + Proxy = proxyInfo.AsType(); + } + } + + static class AssemblyBuilderContainer + { + public static readonly ModuleBuilder ModBuilder; + + static readonly AssemblyBuilder AsmBuilder; + + static AssemblyBuilderContainer() + { + AsmBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("JilInterfaceTypeProxies"), AssemblyBuilderAccess.Run); + ModBuilder = AsmBuilder.DefineDynamicModule("InterfaceProxies"); + } + } +} diff --git a/vendor/Jil/Deserialize/Methods.Get.cs b/vendor/Jil/Deserialize/Methods.Get.cs new file mode 100644 index 000000000..57d70aec5 --- /dev/null +++ b/vendor/Jil/Deserialize/Methods.Get.cs @@ -0,0 +1,332 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace Jil.Deserialize +{ + static partial class Methods + { + public static MethodInfo GetConsumeWhiteSpace(bool readingFromString) + { + return + !readingFromString ? + ConsumeWhiteSpace : + ConsumeWhiteSpaceThunkReader; + } + + public static MethodInfo GetIsNull(bool readingFromString) + { + return + !readingFromString ? + IsNull : + IsNullThunkReader; + } + + public static MethodInfo GetReadBool(bool readingFromString) + { + return + !readingFromString ? + ReadBool : + ReadBoolThunkReader; + } + + public static MethodInfo GetReadUInt8(bool readingFromString) + { + return + !readingFromString ? + ReadUInt8 : + ReadUInt8ThunkReader; + } + + public static MethodInfo GetReadInt8(bool readingFromString) + { + return + !readingFromString ? + ReadInt8 : + ReadInt8ThunkReader; + } + + public static MethodInfo GetReadInt16(bool readingFromString) + { + return + !readingFromString ? + ReadInt16 : + ReadInt16ThunkReader; + } + + public static MethodInfo GetReadUInt16(bool readingFromString) + { + return + !readingFromString ? + ReadUInt16 : + ReadUInt16ThunkReader; + } + + public static MethodInfo GetReadInt32(bool readingFromString) + { + return + !readingFromString ? + ReadInt32 : + ReadInt32ThunkReader; + } + + public static MethodInfo GetReadUInt32(bool readingFromString) + { + return + !readingFromString ? + ReadUInt32 : + ReadUInt32ThunkReader; + } + + public static MethodInfo GetReadInt64(bool readingFromString) + { + return + !readingFromString ? + ReadInt64 : + ReadInt64ThunkReader; + } + + public static MethodInfo GetReadUInt64(bool readingFromString) + { + return + !readingFromString ? + ReadUInt64 : + ReadUInt64ThunkReader; + } + + public static MethodInfo GetReadDoubleFast(bool readingFromString) + { + return + !readingFromString ? + ReadDoubleFast : + ReadDoubleFastThunkReader; + } + + public static MethodInfo GetReadDoubleCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadDoubleCharArray : + ReadDoubleCharArrayThunkReader; + } + + public static MethodInfo GetReadDouble(bool readingFromString) + { + return + !readingFromString ? + ReadDouble : + ReadDoubleThunkReader; + } + + public static MethodInfo GetReadSingleFast(bool readingFromString) + { + return + !readingFromString ? + ReadSingleFast : + ReadSingleFastThunkReader; + } + + public static MethodInfo GetReadSingleCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadSingleCharArray : + ReadSingleCharArrayThunkReader; + } + + public static MethodInfo GetReadSingle(bool readingFromString) + { + return + !readingFromString ? + ReadSingle : + ReadSingleThunkReader; + } + + public static MethodInfo GetReadDecimalFast(bool readingFromString) + { + return + !readingFromString ? + ReadDecimalFast : + ReadDecimalFastThunkReader; + } + + public static MethodInfo GetReadDecimalCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadDecimalCharArray : + ReadDecimalCharArrayThunkReader; + } + + public static MethodInfo GetReadDecimal(bool readingFromString) + { + return + !readingFromString ? + ReadDecimal : + ReadDecimalThunkReader; + } + + public static MethodInfo GetReadEncodedChar(bool readingFromString) + { + return + !readingFromString ? + ReadEncodedChar : + ReadEncodedCharThunkReader; + } + + public static MethodInfo GetReadEncodedStringWithCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadEncodedStringWithCharArray : + ReadEncodedStringWithCharArrayThunkReader; + } + + public static MethodInfo GetReadEncodedStringWithBuffer(bool readingFromString) + { + return + !readingFromString ? + ReadEncodedStringWithBuffer : + ReadEncodedStringWithBufferThunkReader; + } + + public static MethodInfo GetReadEncodedString(bool readingFromString) + { + return + !readingFromString ? + ReadEncodedString : + ReadEncodedStringThunkReader; + } + + public static MethodInfo GetReadGuid(bool readingFromString) + { + return + !readingFromString ? + ReadGuid : + ReadGuidThunkReader; + } + + public static MethodInfo GetParseEnum(bool readingFromString) + { + return + !readingFromString ? + ParseEnum : + ParseEnumThunkReader; + } + + public static MethodInfo GetReadFlagsEnum(bool readingFromString) + { + return + !readingFromString ? + ReadFlagsEnum : + ReadFlagsEnumThunkReader; + } + + public static MethodInfo GetReadSkipWhitespace(bool readingFromString) + { + return + !readingFromString ? + ReadSkipWhitespace : + ReadSkipWhitespaceThunkReader; + } + + public static MethodInfo GetSkip(bool readingFromString) + { + return + !readingFromString ? + Skip : + SkipThunkReader; + } + + public static MethodInfo GetSkipEncodedString(bool readingFromString) + { + return + !readingFromString ? + SkipEncodedString : + SkipEncodedStringThunkReader; + } + + public static MethodInfo GetDiscardMicrosoftTimeZoneOffset(bool readingFromString) + { + return + !readingFromString ? + DiscardMicrosoftTimeZoneOffset : + DiscardMicrosoftTimeZoneOffsetThunkReader; + } + + public static MethodInfo GetReadISO8601DateWithCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadISO8601DateWithCharArray : + ReadISO8601DateWithCharArrayThunkReader; + } + + public static MethodInfo GetReadISO8601Date(bool readingFromString) + { + return + !readingFromString ? + ReadISO8601Date : + ReadISO8601DateThunkReader; + } + + public static MethodInfo GetReadRFC1123Date(bool readingFromString) + { + return + !readingFromString ? + ReadRFC1123Date : + ReadRFC1123DateThunkReader; + } + + public static MethodInfo GetReadISO8601DateWithOffsetWithCharArray(bool readingFromString) + { + return + !readingFromString ? + ReadISO8601DateWithOffsetWithCharArray : + ReadISO8601DateWithOffsetWithCharArrayThunkReader; + } + + public static MethodInfo GetReadISO8601DateWithOffset(bool readingFromString) + { + return + !readingFromString ? + ReadISO8601DateWithOffset : + ReadISO8601DateWithOffsetThunkReader; + } + + public static MethodInfo GetReadMicrosoftTimeSpan(bool readingFromString) + { + return + !readingFromString ? + ReadMicrosoftTimeSpan : + ReadMicrosoftTimeSpanThunkReader; + } + + public static MethodInfo GetReadISO8601TimeSpan(bool readingFromString) + { + return + !readingFromString ? + ReadISO8601TimeSpan : + ReadISO8601TimeSpanThunkReader; + } + + public static MethodInfo GetReadMicrosoftDateTimeOffset(bool readingFromString) + { + return + !readingFromString ? + ReadMicrosoftDateTimeOffset : + ReadMicrosoftDateTimeOffsetThunkReader; + } + + public static MethodInfo GetThrowNoDefinedValueInEnum(bool readingFromString) + { + return + !readingFromString ? + ThrowNoDefinedValueInEnum : + ThrowNoDefinedValueInEnumThunkReader; + } + } +} diff --git a/vendor/Jil/Deserialize/Methods.ISO8601DateTime.cs b/vendor/Jil/Deserialize/Methods.ISO8601DateTime.cs new file mode 100644 index 000000000..41c4f5a26 --- /dev/null +++ b/vendor/Jil/Deserialize/Methods.ISO8601DateTime.cs @@ -0,0 +1,1066 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using Jil.Common; + +namespace Jil.Deserialize +{ + static partial class Methods + { + static readonly MethodInfo ReadISO8601DateWithCharArray = typeof(Methods).GetMethod("_ReadISO8601DateWithCharArray", BindingFlags.Static | BindingFlags.NonPublic); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static DateTime _ReadISO8601DateWithCharArray(TextReader reader, ref char[] buffer) + { + InitDynamicBuffer(ref buffer); + return _ReadISO8601Date(reader, buffer); + } + + static readonly MethodInfo ReadISO8601Date = typeof(Methods).GetMethod("_ReadISO8601Date", BindingFlags.Static | BindingFlags.NonPublic); + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static DateTime _ReadISO8601Date(TextReader reader, char[] buffer) + { + // ISO8601 / RFC3339 (the internet "profile"* of ISO8601) is a plague + // See: http://en.wikipedia.org/wiki/ISO_8601 & + // http://tools.ietf.org/html/rfc3339 + // *is bullshit + + // Here are the possible formats for dates + // YYYY-MM-DD + // YYYY-MM + // YYYY-DDD (ordinal date) + // YYYY-Www (week date, the W is a literal) + // YYYY-Www-D + // YYYYMMDD + // YYYYWww + // YYYYWwwD + // YYYYDDD + + // Here are the possible formats for times + // hh + // hh:mm + // hhmm + // hh:mm:ss + // hhmmss + // hh,fff* + // hh:mm,fff* + // hhmm,fff* + // hh:mm:ss,fff* + // hhmmss,fff* + // hh.fff* + // hh:mm.fff* + // hhmm.fff* + // hh:mm:ss.fff* + // hhmmss.fff* + // * arbitrarily many (technically an "agreed upon" number, I'm agreeing on 7 because that's out to a Tick) + + // Here are the possible formats for timezones + // Z + // +hh + // +hh:mm + // +hhmm + // -hh + // -hh:mm + // -hhmm + + // they are concatenated to form a full instant, with T as a separator between date & time + // i.e. T