diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index f6b98955e..91fcfb34c 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.404 + - uses: actions/checkout@v4 - name: Build with dotnet run: dotnet build diff --git a/Dockerfile b/Dockerfile index d37788531..18dd7d0fa 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.404 AS build WORKDIR /app # Global -COPY ./*.sln ./nuget.config ./ +COPY ./*.slnx ./nuget.config ./global.json ./ # 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.15 AS web WORKDIR /app COPY --from=web-publish /app/src/Opserver.Web/publish ./ -ENTRYPOINT ["dotnet", "Opserver.Web.dll"] \ No newline at end of file +ENTRYPOINT ["dotnet", "Opserver.Web.dll"] 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..fb73375de 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.404 skip_branch_with_pr: true skip_tags: true @@ -17,4 +17,4 @@ environment: build_script: - cmd: dotnet build -test: off \ No newline at end of file +test: off 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/docs/articles/Opserver-Deep-Dive.html b/docs/articles/Opserver-Deep-Dive.html new file mode 100644 index 000000000..fd253c515 --- /dev/null +++ b/docs/articles/Opserver-Deep-Dive.html @@ -0,0 +1,342 @@ + + + + + +Opserver 全景解读:Stack Overflow 的「一屏看全栈」运维面板 + + + +
+
+
+
Engineering · Architecture Notes
+

Opserver 全景解读
Stack Overflow 的「一屏看全栈」运维面板

+

从一张黄色的报错页开始,拆开它的五层架构、逐个讲清八个模块分别管什么,以及把它升级到 .NET 10 之后踩过的坑。基于实际代码与一次完整的本地运行验证写成。

+
ASP.NET Core.NET 10监控与可观测性源码解读Stack Exchange
+
基于 feature/upgrade-net10 分支本文含 4 张原创配图阅读约 12 分钟
+
+
+ +
+ + +
一句话定位:Opserver 是 Stack Exchange(Stack Overflow 母公司)开源的「统一运维监控 + 轻量处置面板」。把 SQL Server、Redis、Elasticsearch、主机、负载均衡、异常日志、值班告警的状态聚到一套 Web UI 里,还能直接在页面上做切主从、停 Job、清执行计划这类操作。它不是 Prometheus / Grafana 那种长期时序监控。
+ +
+
8
可插拔监控模块
+
5
单向数据链路层级
+
0
自建数据库 / 历史存储
+
4
可选安全 Provider
+
+ +
+
01

从一张报错页说起

The Configuration Problem
+

第一次把 Opserver 跑起来,浏览器里大概率是这个页面。很多人第一反应是「装坏了」,其实恰恰相反——这是它刻意设计的安全默认值。

+
首次启动 Opserver 看到的默认页面
图 1 未配置任何安全提供者时,根路径被重定向到 /login 并渲染 NoConfiguration 视图
+

opserverSettings.json 里没有 Security 配置节,SecurityManager.GetProvider() 就会落到 UnconfiguredProvider(IsConfigured = false),AuthController.Login 直接渲染 Views/Shared/NoConfiguration.cshtml;同时 HomeController 带着 [OnlyAllow(Roles.Authenticated)],访问根路径一律 302 跳到 /login。

+
默认拒绝访问,是有意为之
源码里那句注释写得很直白:"If people want read-all access...it should be explicit. Default is no access." 因为页面上的按钮是真的会改生产状态的,所以在没配鉴权、没配监控对象时,它拒绝给任何人看任何东西。截图里 TODO: Fix after merge 是上游模板的占位死链,跟配置错误无关。
+
+ +
+
02

它到底是什么

What It Is
+

Opserver 是 Stack Exchange 开源的监控系统,MIT 许可,仓库 StackExchange/Opserver。官方 readme 只有一句话定位:"Opserver is a monitoring system originally from the team at Stack Exchange, home of Stack Overflow."

+

更准确的说法是统一运维监控 + 轻量处置面板。它把各类中间件的当前健康状态聚到一套 ASP.NET Core Web UI 里,供值班工程师快速判断现状、顺手处理。它没有时序数据库、不存历史曲线、不让你写查询语句——更像叠在现有组件上方的一块实时控制台。

+
+
它回答的问题
「现在哪个实例不健康?」「这条慢查询的执行计划长什么样?」「把这个 Redis 节点提成主库。」
+
它不回答的问题
「过去 30 天 CPU 的趋势如何?」「下个季度该扩容多少?」「帮我配一条 Prometheus 告警规则。」
+
+
+ +
+
03

五层架构与三个取舍

Architecture
+
Opserver 数据流架构
图 2 从 JSON 配置到浏览器的五层单向数据链路
+
    +
  • 配置层:Program.cs 依次加载 appSettings.json、一批 Config/*Settings.json 兼容文件、opserverSettings.json,最后加载被 gitignore 的 localSettings.json(专门用于本地覆盖)。
  • +
  • 采集层:PollingService 是一个 IHostedService,起一条低优先级后台线程,按 PollNode 树周期性拉取状态,结果写入 IMemoryCache。
  • +
  • 组织层:StatusModule 子类各管一类系统。StatusModule.cs 的 AddStatusModules() 用反射扫描程序集、注册全部非抽象子类——加新模块不用改注册代码。
  • +
  • 呈现层:Razor 视图 + 大量 JSON 端点 + /hub 聚合页,配合模块级角色鉴权。
  • +
  • 使用层:NavTab.ConfigureAll() 反射找控制器上的 [DefaultRoute],只为已启用的模块生成顶部 Tab。
  • +
+
+
取舍一 · 没有自己的数据库
轮询结果只留在进程内存里,重启即重新拉取。部署极轻,代价是没有历史趋势可查。
+
取舍二 · 一切由配置驱动
Modules:* 下配了数据源,模块才算 Enabled;仓库自带配置把各模块示例全注释了,默认一个都不开。
+
取舍三 · 权限颗粒度到模块
EveryonesReadOnly / EveryonesAnAdmin 是两种极端 Provider,生产可用 AD 或 OIDC,再叠加每个模块的 ViewGroups / AdminGroups。
+
附带效果 · 导航自动生成
配置里少一个模块,界面上就少一个 Tab。这也是为什么只配 Redis 时,顶部只有孤零零一个入口。
+
+
+ +
+
04

八大模块逐个拆解

The Eight Modules
+

下面按控制器的 [DefaultRoute] 顺序,逐个说明每个模块管什么、看什么、数据从哪来、能不能动手。所有模块默认关闭,配置后自动出现在导航里。

+
Opserver 八大模块能力地图
图 3 八大模块能力地图(橙色为本次本地已启用的 Redis)
+ +
+
1

Dashboard

/dashboard
+

基础设施总览:所有主机与服务的健康状态、资源曲线与硬件明细。

+
+
看什么CPU、内存、磁盘、卷、网卡流量、接口、服务状态、VM 宿主、节点分类与状态曲线
+
数据源WMI、Bosun、Orion、SignalFx 四种 Provider,按 Providers 配置启用
+
能动手dashboard/node/service/action 服务启停
+
+
Dashboard.cshtmlNode.StatsNode.NetworkNode.VolumesNode.Servicesgraph/*/spark
+
+ +
+
2

SQL

/sql
+

功能最深的模块,基本把 DBA 日常排障要看的 DMV 都做成了页面。

+
+
看什么Top 查询与执行计划、活跃会话、连接、内存、错误日志、Agent Job、AlwaysOn 可用组、库表索引、缺失/未使用索引、分区、存储过程、备份与还原
+
数据源SQL Server DMV / 系统视图,经 Microsoft.Data.SqlClient + Dapper 查询
+
能动手移除执行计划、启停 / 开关 Agent Job
+
+
Operations.TopOperations.ActiveAllJobsConnectionsInstance.MemoryDatabases.Modal.*Servers.AvailabilityGroup
+
+ +
+
3

Redis

/redis
+

实例拓扑与运行时状态,也是本次本地实际启用并跑出真实数据的模块。

+
+
看什么实例、主从与副本、Ops/sec、内存、客户端、配置、INFO、SlowLog、按正则做 Key 内存分析
+
数据源Redis INFO / CONFIG,经 StackExchange.Redis 直连
+
能动手kill 客户端、提升主库、改复制源、清 Key、设置 tiebreaker、批量服务端动作
+
+
Dashboard.InstancesInstance.ClientsInstance.ConfigInstance.SlowLogInstance.Analysis.Memoryget-config/*.zip
+
+ +
+
4

Elastic

/elastic
+

Elasticsearch 集群、节点、索引与分片的健康视图。

+
+
看什么集群列表与统计、节点设置、索引列表、分片分布、各类 modal 详情
+
数据源Elasticsearch REST API,按 Clusters 配置节点
+
能动手elastic/reroute/{type} 分片重路由入口
+
+
AllClustersCluster.ShardsCluster.IndexesNode.Settings
+
+ +
+
5

Exceptions

/exceptions
+

应用异常日志的聚合、检索与处置台。

+
+
看什么异常列表、详情与堆栈、筛选器、计数、预览、堆栈链接替换(可跳 GitHub 源码行)
+
数据源StackExchange.Exceptional 写入的 SQL 存储
+
能动手保护 / 删除 / 批量删除异常,联动 Jira 建单
+
+
Exceptions.DetailExceptions.FiltersExceptions.Jiraexceptions/delete-list
+
+ +
+
6

HAProxy

/haproxy
+

负载均衡后端、分组与流量的实时状态。

+
+
看什么分组、后端实例、流量与健康状态、整体 Dashboard
+
数据源HAProxy stats 页(Instances / Groups 配置)
+
能动手haproxy/admin/action 后端启停与状态切换
+
+
HAProxy.DashboardHAProxy.cshtml
+
+ +
+
7

PagerDuty

/pagerduty
+

值班表与告警事件的响应入口,把「谁在值班」和「现在有什么事」放到同一页。

+
+
看什么OnCall 值班行、事件详情、完整升级链、事件状态
+
数据源PagerDuty API(APIKey)
+
能动手更新事件状态、设置值班覆盖(override)
+
+
PagerDuty.OnCallRowPagerDuty.IncidentPagerDuty.EscFull
+
+ +
+
8

Cloudflare

/cloudflare
+

边缘网络侧:DNS 记录与流量概览。

+
+
看什么DNS 记录列表、边缘流量与整体 Dashboard
+
数据源Cloudflare API(Email + APIKey)
+
能动手DNS 记录变更(视图侧入口)
+
+
DNS.cshtmlDashboard.cshtml
+
+ +
别漏了横切能力
/hub(别名 /headsup)把各模块的告警汇总成一页,是真正的「值班首页」;另有 /issues、/about、/about/caches、/ping、/debug、/poll、api/node/enable|disable(维护摘挂)。项目还内置 MiniProfiler,可在 /mini-profiler-resources/results-index 查看每次请求耗时。
+
+ +
+
05

能动手,不只是能看

Read And Act
+

绝大多数监控面板是只读的,Opserver 不是。每个模块都有 *.Admin.cs,端点带 [OnlyAllow(...Roles.Admin)]:Redis 能 kill 客户端、切主从、清 Key;SQL 能移除执行计划、启停 Agent Job;HAProxy 能启停后端;PagerDuty 能改事件状态;Exceptions 能删除异常并联 Jira。

+

这些动作统一受 SecurityManager + Roles(Anonymous / Authenticated / LocalRequest / InternalRequest / ApiRequest / GlobalAdmin / GlobalViewer)+ 模块级 ViewGroups / AdminGroups 约束,把「能看」和「能动手」分开。这也解释了为什么默认拒绝访问是合理的设计:一旦放开,页面上的按钮是真会改生产状态的。

+
+ +
+
06

和 Grafana 怎么分工

Positioning
+ + + + + + + + + + +
维度OpserverPrometheus + Grafana
定位实时状态 + 运维操作台长期时序 + 图表 + 告警规则
数据存储无独立库,轮询结果在进程内存时序数据库,保留历史
面板来源代码内置,配置即启用自己写 PromQL / 配面板
取数方式主动轮询各系统原生接口exporter 暴露指标后被拉取
能否处置能,切主从 / 停 Job / 清计划基本只读
适合场景值班排障、常见操作固化趋势分析、容量规划、告警体系
+

结论不是「谁替代谁」,而是层次不同:Opserver 是给工程师当场处理问题用的,Grafana 是给团队长期观察系统用的。

+
+ +
+
07

本地跑起来

Run It Locally
+
cd src/Opserver.Web
+dotnet run --launch-profile "Opserver.Web"
+

默认监听 http://localhost:56058/(Properties/launchSettings.json,Development 环境)。只跑这一条命令,看到的就是图 1 那张报错页。想看到真实界面,新建一个本地专属的 localSettings.json(已被 .gitignore 忽略):

+
{
+  "Security": { "Provider": "EveryonesAnAdmin" },
+  "Modules": {
+    "Redis": {
+      "Servers": [
+        { "Name": "localhost", "Instances": [ { "Name": "Default", "Port": 6379 } ] }
+      ]
+    }
+  }
+}
+

重启后登录页变成只填用户名(EveryonesAnAdmin 的 FlowType 是 Username,无密码),首页自动跳到 /redis。

+
配置完成后的 Redis 实例列表
图 4 本机 WSL2 的 Redis 6.2.21 单机实例:绿点代表轮询判定健康,表格给出角色、Ops/sec、内存、客户端数与缓存新鲜度
+

1 Chained Instance 前的绿点代表 MonitorStatus: Good;表中 Default 是实例名,主机 localhost:6379,角色 Master,0 副本,436 Ops/sec,7.75MB 内存,2 个客户端,9s ago 是轮询缓存的新鲜度。下半部分留白只是因为只配了一个实例。

+
安全提醒
EveryonesAnAdmin 意味着任意用户名都能拿到全站管理员权限,仅限本地开发。这个文件不能进版本库,更不能出现在生产或公网;生产请改用 ActiveDirectory 或 OIDC。删掉它就恢复默认拒绝访问。
+
+ +
+
08

升级到 .NET 10 的记录

The Upgrade
+

上游 Opserver 长期停留在 .NET 8。当前这个 fork 在 feature/upgrade-net10 分支完成了一轮「功能不变、只换运行时和依赖」的升级:

+
+
运行时与工程文件
net8.0 → net10.0;.sln → .slnx 并删除旧解决方案;Dockerfile、GitHub Actions、AppVeyor 同步升级。
+
两处废弃 API
Program.cs 改用 Host.CreateDefaultBuilder + ConfigureWebHostDefaults(ASPDEPR008);Startup.cs 改用 KnownIPNetworks + System.Net.IPNetwork(ASPDEPR005),但保留 KnownNetworks 配置键兼容既有部署。两者都在 TreatWarningsAsErrors=true 下直接变编译错误。
+
Jil 反序列化必崩
.NET 9+ 新增 TimeSpan.FromSeconds(long) 重载,Jil 2.17.0 反射取方法时抛 AmbiguousMatchException。把源码内置到 vendor/Jil,按精确签名 FromSeconds(double) 改一行,业务代码零改动。
+
SQL 驱动迁移
System.Data.SqlClient → Microsoft.Data.SqlClient 6.1.8(支持到 2028-08 的 LTS)。新驱动 4.0+ 默认 Encrypt=true,用 Connection.WithLegacyEncryptionDefault() 补回 Encrypt=False 保持旧连接语义;连带把 StackExchange.Exceptional 从 2.2.35 升到 3.0.1,去掉运行时对旧驱动的硬引用。
+
Redis 3.x 的两个破坏点
SocketManager 被移除(删字段);随包 analyzer 报 SER308 sync-over-async(在 server.Wait(last) 单点豁免并记录原因)。3.x 默认 RESP3,已在 Redis 6.2 上实测握手与轮询正常。
+
测试与可观测性
xunit 2.9.3 → xunit.v3.mtp-off 4.0.2(迁移 v3 但保留 VSTest)、coverlet.collector 10.1.0、MiniProfiler 4.5.8、Dapper 2.1.89、SourceLink 10.0.403。
+
验收
dotnet build 零警告零错误、dotnet test 97/97 通过、Release 发布成功,再辅以启动 / HTTP / Jil 序列化 / SQL 连接四处冒烟。
+
+
+ +
+
09

适合谁,不适合谁

Fit And Non-Fit
+
+
适合
已经在用 SQL Server + Redis + Elastic + HAProxy 这类自建中间件;值班时需要快速判断并处置;不想为每个系统单独开后台;希望「查看」和「操作」收在同一套权限体系下。
+
不适合
需要长期历史趋势、容量规划、自定义告警规则、多租户或大规模指标量。这些应该交给 Prometheus / Grafana / OpenTelemetry 体系——Opserver 不存历史,也不做告警计算。
+
+
+ +
+
10

结语

Closing
+

Opserver 是个很有 Stack Overflow 气质的项目:不追求通用,不堆抽象,直接把自己机房里每天要用的排障动作做成了页面;默认拒绝一切访问、权限分到模块、轮询只放内存——每一处取舍都透着「给自己运维同事用」的实用主义。

+

它也不是一个可以照搬的现代项目:Razor + jQuery 的老前端、部分 TODO 占位、对 .NET 8 的长期停留都还在。但正因如此,把它升级到 .NET 10 的过程反而成了很好的一次架构阅读——你能清楚看到哪些是设计、哪些是历史包袱,以及升级一个真实项目时,编译错误往往只是最容易的那一层。

+
+
+ + +↑ + + + diff --git a/docs/articles/Opserver-Introduction.html b/docs/articles/Opserver-Introduction.html new file mode 100644 index 000000000..e9f8976c4 --- /dev/null +++ b/docs/articles/Opserver-Introduction.html @@ -0,0 +1,11 @@ +Opserver 深度解析:Stack Overflow 开源的「一屏看全栈」运维面板

Opserver 深度解析:Stack Overflow 开源的「一屏看全栈」运维面板

从一个黄色的报错页说起,聊清楚这个项目的出身、架构、八大模块,以及把它升级到 .NET 10 之后踩过的坑。本文基于 Opserver 实际代码与一次完整的本地运行验证写成。

一、从一张「Configuration Problem」说起

第一次把 Opserver 跑起来,浏览器里大概率是这个页面:

首次启动 Opserver 看到的默认页面

首次启动 Opserver 看到的默认页面

很多人第一反应是「装坏了」。其实恰恰相反——这是 Opserver 刻意设计的安全默认值:opserverSettings.json 里没有 Security 配置节,SecurityManager.GetProvider() 就会落到 UnconfiguredProvider(IsConfigured = false),AuthController.Login 直接渲染 Views/Shared/NoConfiguration.cshtml;同时 HomeController 带着 [OnlyAllow(Roles.Authenticated)],访问根路径一律 302 跳到 /login。

换句话说:没配鉴权、没配监控对象,它就拒绝给任何人看任何东西。代码注释写得很直白——"If people want read-all access...it should be explicit. Default is no access."。页面里那句 See the configuration docs here: TODO: Fix after merge 是上游模板留下的占位死链,跟配置错误无关。

二、它到底是什么

Opserver 是 Stack Exchange(Stack Overflow 母公司)开源的监控系统,MIT 许可,仓库 StackExchange/Opserver。官方 readme 只有一句话定位:"Opserver is a monitoring system originally from the team at Stack Exchange, home of Stack Overflow."

更准确的说法是:统一运维监控 + 轻量处置面板。它把 SQL Server、Redis、Elasticsearch、主机、HAProxy、异常日志、PagerDuty 值班、Cloudflare DNS 这些系统的当前健康状态,聚到一套 ASP.NET Core Web UI 里;而且不只是"看",还能直接在页面上切主从、启停 SQL Agent Job、清执行计划。

它不是 Prometheus / Grafana 那种长期时序监控:没有时序数据库、不存历史曲线、不让你写查询语句。它更像叠在现有组件上方的一块实时控制台——值班时打开一屏,判断现状,顺手处理。

三、整体架构:五层,一次轮询

Opserver 数据流架构

Opserver 数据流架构

从配置到浏览器,数据链路是单向的五层:

  1. 配置层:Program.cs 按顺序加载 appSettings.json、一批 Config/*Settings.json 兼容文件、opserverSettings.json、以及最后加载的 localSettings.json(后者被 .gitignore 忽略,专门给本地覆盖用)。
  2. 采集层:PollingService 是一个 IHostedService,起一条低优先级后台线程,按 PollNode 树周期性拉取各系统状态,结果写入 IMemoryCache。
  3. 组织层:StatusModule 子类各自负责一类系统。StatusModule.cs 里 AddStatusModules() 用反射扫描程序集,把所有非抽象子类注册成单例——加新模块不需要改注册代码。
  4. 呈现层:Razor 视图 + 大量 JSON 端点 + /hub 聚合页,配合模块级角色鉴权。
  5. 使用层:NavTab.ConfigureAll() 通过反射找控制器上的 [DefaultRoute],只为已启用的模块生成顶部 Tab。

三个值得记住的设计取舍:

四、八大模块:它到底能看什么

Opserver 八大模块能力地图

Opserver 八大模块能力地图

模块路由主要看什么数据来源
Dashboard/dashboard主机 CPU / 内存 / 磁盘 / 网卡 / 卷 / 服务状态与曲线WMI、Bosun、Orion、SignalFx
SQL/sqlTop 查询、执行计划、活跃会话、连接、Agent Job、内存、错误日志、库表索引、备份还原、AlwaysOn 可用组SQL Server DMV / 系统视图
Redis/redis实例、主从、副本、客户端、SlowLog、配置、内存 Key 分析Redis INFO / CONFIG
Elastic/elastic集群、节点、索引、分片健康、集群设置Elasticsearch REST
Exceptions/exceptions异常聚合、详情、堆栈、筛选、保护与删除、Jira 联动StackExchange.Exceptional 的 SQL 存储
HAProxy/haproxy后端、流量、健康状态、分组HAProxy stats 页
PagerDuty/pagerduty值班表、事件、升级链PagerDuty API
Cloudflare/cloudflareDNS 记录、边缘流量Cloudflare API

其中 SQL 和 Redis 是功能最深的两个。Views/SQL 目录下有二十多个视图,从 Operations.Top(按 CPU / 读写的 Top 查询)、Instance.Memory、Connections,到 Databases.Modal.MissingIndexes、UnusedIndexes、Backups、Restores,基本把 DBA 日常排障要看的 DMV 都做成了页面。Views/Redis 则覆盖 Clients、Config、Info、SlowLog、Analysis.Memory,并能导出实例配置 zip。

/hub(别名 /headsup)是另一个有意思的入口:它把各模块的当前问题和告警汇总到一页,是真正意义上的「值班首页」。配套的还有 /issues(问题聚合)、/about(认证信息与模块状态)、/about/caches(缓存)、/ping(健康检查)、/debug(请求头与轮询线程状态)、/poll(轮询控制)以及 api/node/enable|disable(维护摘挂)。项目还内置了 MiniProfiler,可以在 /mini-profiler-resources/results-index 查看每次请求的耗时明细。

五、真正的特色:能动手,不只是能看

绝大多数监控面板是只读的,Opserver 不是。每个模块都有一份 *.Admin.cs,端点带 [OnlyAllow(...Roles.Admin)]:

这些动作统一受 SecurityManager + Roles(Anonymous / Authenticated / LocalRequest / InternalRequest / ApiRequest / GlobalAdmin / GlobalViewer)+ 模块级 ViewGroups / AdminGroups 约束。也正因如此,默认不给任何访问权限才显得合理:一旦放开,页面上的按钮是真的会改生产状态的。

六、横向对比:Opserver vs Prometheus + Grafana

维度OpserverPrometheus + Grafana
定位实时状态 + 运维操作台长期时序 + 图表 + 告警规则
数据存储无独立库,轮询结果在进程内存时序数据库,保留历史
面板来源代码内置,配置即启用自己写 PromQL / 配面板
数据获取主动轮询各系统原生接口各 exporter 暴露指标后被拉取
能否处置能,切主从 / 停 Job / 清计划基本只读
适合场景值班排障、常见操作固化趋势分析、容量规划、告警体系

结论不是「谁替代谁」,而是层次不同:Opserver 是给工程师当场处理问题用的,Grafana 是给团队长期观察系统用的。

七、本地跑起来

cd src/Opserver.Web
+dotnet run --launch-profile "Opserver.Web"

默认监听 http://localhost:56058/(Properties/launchSettings.json,Development 环境)。只跑这一条命令,看到的就是开头那张报错页。想看到真实界面,按 Program.cs 的加载顺序,新建一个本地专属的 localSettings.json(该文件已被 .gitignore 忽略):

{
+  "Security": { "Provider": "EveryonesAnAdmin" },
+  "Modules": {
+    "Redis": {
+      "Servers": [
+        { "Name": "localhost", "Instances": [ { "Name": "Default", "Port": 6379 } ] }
+      ]
+    }
+  }
+}

重启后登录页变成只填用户名(EveryonesAnAdmin 的 FlowType 是 Username,无密码),首页自动跳到 /redis。

配置完成后的 Redis 实例列表

配置完成后的 Redis 实例列表

这张图上是本机 WSL2 里一个 Redis 6.2.21 单机实例:1 Chained Instance 前的绿点代表轮询判定健康(MonitorStatus: Good),表格里 Default 是实例名,主机 localhost:6379,角色 Master,0 副本,436 Ops/sec,7.75MB 内存,2 个客户端,9s ago 是轮询缓存的新鲜度。右上角的 dashboard / instance 是视图切换。下半部分留白只是因为只配了一个实例。

⚠️ EveryonesAnAdmin 意味着任意用户名都能拿到全站管理员权限,仅限本地开发。这个文件不能进版本库,更不能出现在生产或公网环境;生产请改用 ActiveDirectory 或 OIDC。删掉它就恢复默认拒绝访问。

八、这个 fork:从 .NET 8 升级到 .NET 10 的记录

上游 Opserver 长期停留在 .NET 8。当前这个 fork 在 feature/upgrade-net10 分支上完成了一轮「功能不变、只换运行时和依赖」的升级,几个有代表性的改动:

改动原因
net8.0 → net10.0;.sln → .slnx 并删除旧解决方案统一到 .NET 10 LTS 与新解决方案格式;Dockerfile、GitHub Actions、AppVeyor 同步升级
Program.cs 改用 Host.CreateDefaultBuilder + ConfigureWebHostDefaults.NET 10 把 WebHost 标记为过时(ASPDEPR008),在 TreatWarningsAsErrors=true 下直接变编译错误
Startup.cs 改用 KnownIPNetworks + System.Net.IPNetworkForwardedHeadersOptions.KnownNetworks 过时(ASPDEPR005);保留 "KnownNetworks" 配置键以兼容既有部署
内置 Jil 2.17.0 源码到 vendor/Jil.NET 9+ 新增 TimeSpan.FromSeconds(long) 重载,Jil 反射取方法时抛 AmbiguousMatchException,反序列化必崩;按精确签名 FromSeconds(double) 修一行,业务代码零改动
System.Data.SqlClient → Microsoft.Data.SqlClient 6.1.8旧驱动已弃用;6.1 是支持到 2028-08 的 LTS。新驱动 4.0+ 默认 Encrypt=true,用 Connection.WithLegacyEncryptionDefault() 显式补回 Encrypt=False,保持旧连接语义不变
StackExchange.Exceptional 2.2.35 → 3.0.12.x 的 netstandard2.0 资产在运行时硬引用旧 System.Data.SqlClient,直接删包会导致 Web 启动 FileNotFoundException
StackExchange.Redis 2.8.16 → 3.4.313.x 移除了 SocketManager,且随包 analyzer 会报 SER308(sync-over-async);前者删字段,后者在 server.Wait(last) 处做单点豁免并记录原因。3.x 默认 RESP3,本次在 Redis 6.2 上实测握手与轮询正常
MiniProfiler 4.3.13 → 4.5.8、Dapper 2.1.89、SourceLink 10.0.403常规依赖升级,构建与 HTTP 冒烟验证通过
xunit 2.9.3 → xunit.v3.mtp-off 4.0.2迁移到 xUnit v3 但保留 VSTest / dotnet test;默认的 xunit.v3 会切到 Microsoft.Testing.Platform,mtp-off 变体不会
新增 coverlet.collector 10.1.0用 --collect:"XPlat Code Coverage" 采 VSTest 覆盖率,输出 coverage.cobertura.xml

整轮改造的验收标准是 dotnet build 零警告零错误、dotnet test 97/97 通过、Release 发布成功,再辅以启动 / HTTP / Jil 序列化 / SQL 连接四处冒烟。功能逻辑保持原样,变的只是运行时和依赖。

九、适合谁,不适合谁

适合:已经在用 SQL Server + Redis + Elastic + HAProxy 这类自建中间件、值班时需要快速判断并处置、且不想为每个系统单独开后台的团队;尤其适合希望「查看」和「操作」都收在同一套权限体系下的场景。

不适合:需要长期历史趋势、容量规划、自定义告警规则、多租户或大规模指标量的场景——这些应该交给 Prometheus / Grafana / OpenTelemetry 体系。Opserver 不存历史,也不做告警计算,它只回答「现在怎么样」和「我现在能做什么」。

十、结语

Opserver 是个很有 Stack Overflow 气质的项目:不追求通用,不堆抽象,直接把自己机房里每天要用的排障动作做成了页面;默认拒绝一切访问、权限分到模块、轮询只放内存——每一处取舍都透着「给自己运维同事用」的实用主义。

它也不是一个可以直接照搬的现代项目:Razor + jQuery 的老前端、部分 TODO 占位、对 .NET 8 的长期停留都还在。但正因如此,把它升级到 .NET 10 的过程反而成了很好的一次架构阅读——你能清楚看到哪些是设计、哪些是历史包袱,以及升级一个真实生产项目时,编译错误往往只是最容易的那一层。


本文基于 feature/upgrade-net10 分支的实际代码与本地运行截图整理;项目主页:<https://github.com/StackExchange/Opserver>。

\ No newline at end of file diff --git a/docs/articles/Opserver-Introduction.md b/docs/articles/Opserver-Introduction.md new file mode 100644 index 000000000..7b8b7e0eb --- /dev/null +++ b/docs/articles/Opserver-Introduction.md @@ -0,0 +1,146 @@ +# Opserver 深度解析:Stack Overflow 开源的「一屏看全栈」运维面板 + +> 从一个黄色的报错页说起,聊清楚这个项目的出身、架构、八大模块,以及把它升级到 .NET 10 之后踩过的坑。本文基于 Opserver 实际代码与一次完整的本地运行验证写成。 + +## 一、从一张「Configuration Problem」说起 + +第一次把 Opserver 跑起来,浏览器里大概率是这个页面: + +![首次启动 Opserver 看到的默认页面](images/configuration-problem.png) + +很多人第一反应是「装坏了」。其实恰恰相反——这是 Opserver **刻意设计的安全默认值**:`opserverSettings.json` 里没有 `Security` 配置节,`SecurityManager.GetProvider()` 就会落到 `UnconfiguredProvider`(`IsConfigured = false`),`AuthController.Login` 直接渲染 `Views/Shared/NoConfiguration.cshtml`;同时 `HomeController` 带着 `[OnlyAllow(Roles.Authenticated)]`,访问根路径一律 302 跳到 `/login`。 + +换句话说:**没配鉴权、没配监控对象,它就拒绝给任何人看任何东西**。代码注释写得很直白——"If people want read-all access...it should be explicit. Default is no access."。页面里那句 `See the configuration docs here: TODO: Fix after merge` 是上游模板留下的占位死链,跟配置错误无关。 + +## 二、它到底是什么 + +Opserver 是 Stack Exchange(Stack Overflow 母公司)开源的监控系统,MIT 许可,仓库 `StackExchange/Opserver`。官方 readme 只有一句话定位:*"Opserver is a monitoring system originally from the team at Stack Exchange, home of Stack Overflow."* + +更准确的说法是:**统一运维监控 + 轻量处置面板**。它把 SQL Server、Redis、Elasticsearch、主机、HAProxy、异常日志、PagerDuty 值班、Cloudflare DNS 这些系统的当前健康状态,聚到一套 ASP.NET Core Web UI 里;而且不只是"看",还能直接在页面上切主从、启停 SQL Agent Job、清执行计划。 + +它不是 Prometheus / Grafana 那种长期时序监控:没有时序数据库、不存历史曲线、不让你写查询语句。它更像叠在现有组件上方的一块**实时控制台**——值班时打开一屏,判断现状,顺手处理。 + +## 三、整体架构:五层,一次轮询 + +![Opserver 数据流架构](images/architecture.png) + +从配置到浏览器,数据链路是单向的五层: + +1. **配置层**:`Program.cs` 按顺序加载 `appSettings.json`、一批 `Config/*Settings.json` 兼容文件、`opserverSettings.json`、以及最后加载的 `localSettings.json`(后者被 `.gitignore` 忽略,专门给本地覆盖用)。 +2. **采集层**:`PollingService` 是一个 `IHostedService`,起一条低优先级后台线程,按 `PollNode` 树周期性拉取各系统状态,结果写入 `IMemoryCache`。 +3. **组织层**:`StatusModule` 子类各自负责一类系统。`StatusModule.cs` 里 `AddStatusModules()` 用反射扫描程序集,把所有非抽象子类注册成单例——加新模块不需要改注册代码。 +4. **呈现层**:Razor 视图 + 大量 JSON 端点 + `/hub` 聚合页,配合模块级角色鉴权。 +5. **使用层**:`NavTab.ConfigureAll()` 通过反射找控制器上的 `[DefaultRoute]`,**只为已启用的模块生成顶部 Tab**。 + +三个值得记住的设计取舍: + +- **没有自己的数据库**。轮询结果只留在进程内存里,重启即重新拉取。所以部署极轻,但也就没有历史趋势可查。 +- **一切由配置驱动**。`Modules:*` 下配了数据源,模块才算 `Enabled`;仓库自带的 `opserverSettings.json` 把各模块示例全注释了,默认一个都不开。 +- **权限颗粒度到模块**。`EveryonesReadOnly` 和 `EveryonesAnAdmin` 是两种极端 Provider,生产可用 `ActiveDirectory` 或 `OIDC`;再叠加每个模块的 `ViewGroups` / `AdminGroups`,把「能看」和「能动手」分开。 + +## 四、八大模块:它到底能看什么 + +![Opserver 八大模块能力地图](images/modules.png) + +| 模块 | 路由 | 主要看什么 | 数据来源 | +| --- | --- | --- | --- | +| Dashboard | `/dashboard` | 主机 CPU / 内存 / 磁盘 / 网卡 / 卷 / 服务状态与曲线 | WMI、Bosun、Orion、SignalFx | +| SQL | `/sql` | Top 查询、执行计划、活跃会话、连接、Agent Job、内存、错误日志、库表索引、备份还原、AlwaysOn 可用组 | SQL Server DMV / 系统视图 | +| Redis | `/redis` | 实例、主从、副本、客户端、SlowLog、配置、内存 Key 分析 | Redis `INFO` / `CONFIG` | +| Elastic | `/elastic` | 集群、节点、索引、分片健康、集群设置 | Elasticsearch REST | +| Exceptions | `/exceptions` | 异常聚合、详情、堆栈、筛选、保护与删除、Jira 联动 | StackExchange.Exceptional 的 SQL 存储 | +| HAProxy | `/haproxy` | 后端、流量、健康状态、分组 | HAProxy stats 页 | +| PagerDuty | `/pagerduty` | 值班表、事件、升级链 | PagerDuty API | +| Cloudflare | `/cloudflare` | DNS 记录、边缘流量 | Cloudflare API | + +其中 **SQL 和 Redis 是功能最深的两个**。`Views/SQL` 目录下有二十多个视图,从 `Operations.Top`(按 CPU / 读写的 Top 查询)、`Instance.Memory`、`Connections`,到 `Databases.Modal.MissingIndexes`、`UnusedIndexes`、`Backups`、`Restores`,基本把 DBA 日常排障要看的 DMV 都做成了页面。`Views/Redis` 则覆盖 `Clients`、`Config`、`Info`、`SlowLog`、`Analysis.Memory`,并能导出实例配置 zip。 + +`/hub`(别名 `/headsup`)是另一个有意思的入口:它把各模块的当前问题和告警汇总到一页,是真正意义上的「值班首页」。配套的还有 `/issues`(问题聚合)、`/about`(认证信息与模块状态)、`/about/caches`(缓存)、`/ping`(健康检查)、`/debug`(请求头与轮询线程状态)、`/poll`(轮询控制)以及 `api/node/enable|disable`(维护摘挂)。项目还内置了 MiniProfiler,可以在 `/mini-profiler-resources/results-index` 查看每次请求的耗时明细。 + +## 五、真正的特色:能动手,不只是能看 + +绝大多数监控面板是只读的,Opserver 不是。每个模块都有一份 `*.Admin.cs`,端点带 `[OnlyAllow(...Roles.Admin)]`: + +- Redis(`RedisController.Admin.cs`):kill 客户端、提升主库、切换复制源、清理 Key、设置 / 清除 tiebreaker、批量执行服务端动作; +- SQL(`SQLController.Admin.cs`):移除执行计划、启停 / 开关 Agent Job; +- 其他:HAProxy 后端启停、Dashboard 服务启停、PagerDuty 改事件状态与值班覆盖、Cloudflare DNS 变更、Exceptions 删除 / 保护异常并关联 Jira。 + +这些动作统一受 `SecurityManager` + `Roles`(`Anonymous` / `Authenticated` / `LocalRequest` / `InternalRequest` / `ApiRequest` / `GlobalAdmin` / `GlobalViewer`)+ 模块级 `ViewGroups` / `AdminGroups` 约束。也正因如此,**默认不给任何访问权限**才显得合理:一旦放开,页面上的按钮是真的会改生产状态的。 + +## 六、横向对比:Opserver vs Prometheus + Grafana + +| 维度 | Opserver | Prometheus + Grafana | +| --- | --- | --- | +| 定位 | 实时状态 + 运维操作台 | 长期时序 + 图表 + 告警规则 | +| 数据存储 | 无独立库,轮询结果在进程内存 | 时序数据库,保留历史 | +| 面板来源 | 代码内置,配置即启用 | 自己写 PromQL / 配面板 | +| 数据获取 | 主动轮询各系统原生接口 | 各 exporter 暴露指标后被拉取 | +| 能否处置 | 能,切主从 / 停 Job / 清计划 | 基本只读 | +| 适合场景 | 值班排障、常见操作固化 | 趋势分析、容量规划、告警体系 | + +结论不是「谁替代谁」,而是层次不同:Opserver 是给工程师**当场处理问题**用的,Grafana 是给团队**长期观察系统**用的。 + +## 七、本地跑起来 + +```bash +cd src/Opserver.Web +dotnet run --launch-profile "Opserver.Web" +``` + +默认监听 `http://localhost:56058/`(`Properties/launchSettings.json`,Development 环境)。只跑这一条命令,看到的就是开头那张报错页。想看到真实界面,按 `Program.cs` 的加载顺序,新建一个本地专属的 `localSettings.json`(该文件已被 `.gitignore` 忽略): + +```json +{ + "Security": { "Provider": "EveryonesAnAdmin" }, + "Modules": { + "Redis": { + "Servers": [ + { "Name": "localhost", "Instances": [ { "Name": "Default", "Port": 6379 } ] } + ] + } + } +} +``` + +重启后登录页变成只填用户名(`EveryonesAnAdmin` 的 `FlowType` 是 `Username`,无密码),首页自动跳到 `/redis`。 + +![配置完成后的 Redis 实例列表](images/redis-dashboard.png) + +这张图上是本机 WSL2 里一个 Redis 6.2.21 单机实例:`1 Chained Instance` 前的绿点代表轮询判定健康(`MonitorStatus: Good`),表格里 `Default` 是实例名,主机 `localhost:6379`,角色 `Master`,0 副本,`436` Ops/sec,`7.75MB` 内存,2 个客户端,`9s ago` 是轮询缓存的新鲜度。右上角的 `dashboard` / `instance` 是视图切换。下半部分留白只是因为只配了一个实例。 + +> ⚠️ `EveryonesAnAdmin` 意味着任意用户名都能拿到全站管理员权限,**仅限本地开发**。这个文件不能进版本库,更不能出现在生产或公网环境;生产请改用 `ActiveDirectory` 或 `OIDC`。删掉它就恢复默认拒绝访问。 + +## 八、这个 fork:从 .NET 8 升级到 .NET 10 的记录 + +上游 Opserver 长期停留在 .NET 8。当前这个 fork 在 `feature/upgrade-net10` 分支上完成了一轮「功能不变、只换运行时和依赖」的升级,几个有代表性的改动: + +| 改动 | 原因 | +| --- | --- | +| `net8.0` → `net10.0`;`.sln` → `.slnx` 并删除旧解决方案 | 统一到 .NET 10 LTS 与新解决方案格式;Dockerfile、GitHub Actions、AppVeyor 同步升级 | +| `Program.cs` 改用 `Host.CreateDefaultBuilder` + `ConfigureWebHostDefaults` | .NET 10 把 `WebHost` 标记为过时(`ASPDEPR008`),在 `TreatWarningsAsErrors=true` 下直接变编译错误 | +| `Startup.cs` 改用 `KnownIPNetworks` + `System.Net.IPNetwork` | `ForwardedHeadersOptions.KnownNetworks` 过时(`ASPDEPR005`);保留 `"KnownNetworks"` 配置键以兼容既有部署 | +| 内置 Jil 2.17.0 源码到 `vendor/Jil` | .NET 9+ 新增 `TimeSpan.FromSeconds(long)` 重载,Jil 反射取方法时抛 `AmbiguousMatchException`,反序列化必崩;按精确签名 `FromSeconds(double)` 修一行,业务代码零改动 | +| `System.Data.SqlClient` → `Microsoft.Data.SqlClient 6.1.8` | 旧驱动已弃用;6.1 是支持到 2028-08 的 LTS。新驱动 4.0+ 默认 `Encrypt=true`,用 `Connection.WithLegacyEncryptionDefault()` 显式补回 `Encrypt=False`,保持旧连接语义不变 | +| `StackExchange.Exceptional` 2.2.35 → 3.0.1 | 2.x 的 netstandard2.0 资产在运行时硬引用旧 `System.Data.SqlClient`,直接删包会导致 Web 启动 `FileNotFoundException` | +| `StackExchange.Redis` 2.8.16 → 3.4.31 | 3.x 移除了 `SocketManager`,且随包 analyzer 会报 `SER308`(sync-over-async);前者删字段,后者在 `server.Wait(last)` 处做单点豁免并记录原因。3.x 默认 RESP3,本次在 Redis 6.2 上实测握手与轮询正常 | +| `MiniProfiler` 4.3.13 → 4.5.8、`Dapper` 2.1.89、SourceLink 10.0.403 | 常规依赖升级,构建与 HTTP 冒烟验证通过 | +| `xunit` 2.9.3 → `xunit.v3.mtp-off` 4.0.2 | 迁移到 xUnit v3 但**保留 VSTest / `dotnet test`**;默认的 `xunit.v3` 会切到 Microsoft.Testing.Platform,`mtp-off` 变体不会 | +| 新增 `coverlet.collector` 10.1.0 | 用 `--collect:"XPlat Code Coverage"` 采 VSTest 覆盖率,输出 `coverage.cobertura.xml` | + +整轮改造的验收标准是 `dotnet build` 零警告零错误、`dotnet test` 97/97 通过、Release 发布成功,再辅以启动 / HTTP / Jil 序列化 / SQL 连接四处冒烟。功能逻辑保持原样,变的只是运行时和依赖。 + +## 九、适合谁,不适合谁 + +**适合**:已经在用 SQL Server + Redis + Elastic + HAProxy 这类自建中间件、值班时需要快速判断并处置、且不想为每个系统单独开后台的团队;尤其适合希望「查看」和「操作」都收在同一套权限体系下的场景。 + +**不适合**:需要长期历史趋势、容量规划、自定义告警规则、多租户或大规模指标量的场景——这些应该交给 Prometheus / Grafana / OpenTelemetry 体系。Opserver 不存历史,也不做告警计算,它只回答「现在怎么样」和「我现在能做什么」。 + +## 十、结语 + +Opserver 是个很有 Stack Overflow 气质的项目:不追求通用,不堆抽象,直接把自己机房里每天要用的排障动作做成了页面;默认拒绝一切访问、权限分到模块、轮询只放内存——每一处取舍都透着「给自己运维同事用」的实用主义。 + +它也不是一个可以直接照搬的现代项目:Razor + jQuery 的老前端、部分 `TODO` 占位、对 .NET 8 的长期停留都还在。但正因如此,把它升级到 .NET 10 的过程反而成了很好的一次架构阅读——你能清楚看到哪些是设计、哪些是历史包袱,以及升级一个真实生产项目时,编译错误往往只是最容易的那一层。 + +--- + +*本文基于 `feature/upgrade-net10` 分支的实际代码与本地运行截图整理;项目主页:。* diff --git a/docs/articles/Opserver-WeChat-Draft.json b/docs/articles/Opserver-WeChat-Draft.json new file mode 100644 index 000000000..4cd892a33 --- /dev/null +++ b/docs/articles/Opserver-WeChat-Draft.json @@ -0,0 +1,183 @@ +{ + "title": "Opserver 全景解读:八大模块与架构", + "abstract": "Stack Overflow 开源的统一运维监控与轻量处置面板:五层架构、八个模块逐个拆解,以及升级到 .NET 10 的踩坑记录。", + "cover_img": "https://cdn.jsdelivr.net/gh/sugarst/Opserver@8defbfebccb8bc77adf619728b266e85c4cee092/docs/articles/images/modules.png", + "intro": "第一次把 Opserver 跑起来,浏览器里大概率是一张黄色的 Configuration Problem 报错页。这不是装坏了,而是它刻意设计的安全默认值。本文从这张页面开始,拆开它的五层架构,逐个讲清八个模块分别管什么,以及把它升级到 .NET 10 之后踩过的坑——基于实际代码与一次完整的本地运行验证写成。", + "chapters": [ + { + "type": "chapter", + "title": "从一张黄色的报错页说起", + "blocks": [ + { "type": "paragraph", "content": "很多人第一次启动 Opserver,看到 Uh no! Configuration Problem! 会以为装坏了。其实恰恰相反,这是它刻意设计的安全默认值:没配鉴权、没配监控对象,它就拒绝给任何人看任何东西。源码里的注释写得很直白——如果有人想要「全员只读」,那必须是显式配置出来的,默认不给任何访问权限。" }, + { "type": "image", "url": "https://cdn.jsdelivr.net/gh/sugarst/Opserver@8defbfebccb8bc77adf619728b266e85c4cee092/docs/articles/images/configuration-problem.png", "alt": "首次启动 Opserver 看到的默认页面" }, + { "type": "paragraph", "content": "代码链路是:opserverSettings.json 里没有 Security 配置节,SecurityManager.GetProvider() 落到 UnconfiguredProvider,AuthController.Login 直接渲染 NoConfiguration.cshtml;同时 HomeController 带 [OnlyAllow(Roles.Authenticated)],访问根路径一律 302 跳到 /login。页面里那句 TODO: Fix after merge 是上游模板的占位死链,与配置错误无关。" } + ] + }, + { + "type": "chapter", + "title": "它到底是什么", + "blocks": [ + { "type": "paragraph", "content": "Opserver 是 Stack Exchange(Stack Overflow 母公司)开源的监控系统,MIT 许可。官方 readme 只有一句话:Opserver is a monitoring system originally from the team at Stack Exchange, home of Stack Overflow." }, + { "type": "paragraph", "content": "更准确的说法是「统一运维监控 + 轻量处置面板」。它把 SQL Server、Redis、Elasticsearch、主机、HAProxy、异常日志、PagerDuty 值班、Cloudflare DNS 的当前健康状态,聚到一套 ASP.NET Core Web UI 里;而且不只是看,还能直接在页面上切主从、启停 SQL Agent Job、清执行计划。" }, + { "type": "paragraph", "content": "它不是 Prometheus / Grafana 那种长期时序监控:没有时序数据库、不存历史曲线、不让你写查询语句。它更像叠在现有组件上方的一块实时控制台——值班时打开一屏,判断现状,顺手处理。它回答「现在哪个实例不健康」,不回答「过去 30 天 CPU 趋势如何」。" } + ] + }, + { + "type": "chapter", + "title": "五层架构,三个取舍", + "blocks": [ + { "type": "image", "url": "https://cdn.jsdelivr.net/gh/sugarst/Opserver@8defbfebccb8bc77adf619728b266e85c4cee092/docs/articles/images/architecture.png", "alt": "Opserver 数据流架构" }, + { "type": "list", "style": "ordered", "items": [ + "配置层:Program.cs 依次加载 appSettings.json、一批 Config/*Settings.json 兼容文件、opserverSettings.json,最后加载被 gitignore 的 localSettings.json。", + "采集层:PollingService 是一个 IHostedService,起一条低优先级后台线程,按 PollNode 树周期性拉取状态,结果写入 IMemoryCache。", + "组织层:StatusModule 子类各管一类系统;AddStatusModules() 用反射扫描程序集、注册全部非抽象子类,加新模块不用改注册代码。", + "呈现层:Razor 视图 + 大量 JSON 端点 + /hub 聚合页,配合模块级角色鉴权。", + "使用层:NavTab.ConfigureAll() 反射找控制器上的 [DefaultRoute],只为已启用的模块生成顶部 Tab。" + ] }, + { "type": "paragraph", "content": "三个值得记住的取舍:第一,没有自己的数据库,轮询结果只留在进程内存里,重启即重新拉取,部署极轻但没有历史趋势;第二,一切由配置驱动,Modules:* 下配了数据源模块才算 Enabled,仓库自带配置把示例全注释了,默认一个都不开;第三,权限颗粒度到模块,生产可用 ActiveDirectory 或 OIDC,再叠加每个模块的 ViewGroups / AdminGroups,把「能看」和「能动手」分开。" } + ] + }, + { + "type": "chapter", + "title": "八大模块总览", + "blocks": [ + { "type": "image", "url": "https://cdn.jsdelivr.net/gh/sugarst/Opserver@8defbfebccb8bc77adf619728b266e85c4cee092/docs/articles/images/modules.png", "alt": "Opserver 八大模块能力地图" }, + { "type": "table", "headers": ["模块 / 路由", "主要看什么", "数据来源"], "rows": [ + ["Dashboard /dashboard", "主机 CPU、内存、磁盘、网卡、卷、服务状态与曲线", "WMI、Bosun、Orion、SignalFx"], + ["SQL /sql", "Top 查询、执行计划、连接、Agent Job、索引、备份还原", "SQL Server DMV"], + ["Redis /redis", "实例、主从、客户端、SlowLog、配置、内存分析", "Redis INFO / CONFIG"], + ["Elastic /elastic", "集群、节点、索引、分片健康", "Elasticsearch REST"], + ["Exceptions /exceptions", "异常聚合、详情、堆栈、筛选、Jira 联动", "Exceptional 的 SQL 存储"], + ["HAProxy /haproxy", "后端、流量、健康状态、分组", "HAProxy stats"], + ["PagerDuty /pagerduty", "值班表、事件、升级链", "PagerDuty API"], + ["Cloudflare /cloudflare", "DNS 记录、边缘流量", "Cloudflare API"] + ] } + ] + }, + { + "type": "chapter", + "title": "模块 1 · Dashboard:主机与服务总览", + "blocks": [ + { "type": "paragraph", "content": "基础设施的健康总览。看 CPU、内存、磁盘、卷、网卡流量、接口、服务状态、VM 宿主、节点分类与历史曲线;数据来自 WMI、Bosun、Orion、SignalFx 四种 Provider,按 Providers 配置启用。" }, + { "type": "paragraph", "content": "视图集中在 Views/Dashboard:Dashboard.cshtml、Node.Stats、Node.Network、Node.Volumes、Node.Services、Node.Hardware 等;GraphController 提供 graph/cpu、memory、network、volumePerformance 的 spark 与 json 端点。管理动作是 dashboard/node/service/action,可直接启停节点上的服务。" } + ] + }, + { + "type": "chapter", + "title": "模块 2 · SQL:DBA 的日常排障台", + "blocks": [ + { "type": "paragraph", "content": "八个模块里功能最深的一个。Views/SQL 下有二十多个视图,从 Operations.Top(按 CPU / 读写的 Top 查询)、执行计划详情、Operations.Active(活跃会话)、Connections、Instance.Memory、Instance.Errors、AllJobs,到 Databases.Modal 系列的表、索引、缺失索引、未使用索引、分区、存储过程、备份与还原,以及 Servers.AvailabilityGroup(AlwaysOn 可用组)——基本把 DBA 日常要看的 DMV 都做成了页面。" }, + { "type": "paragraph", "content": "数据经 Microsoft.Data.SqlClient + Dapper 从 SQL Server DMV / 系统视图查询。管理端点集中在 SQLController.Admin.cs:sql/remove-plan 移除执行计划,sql/toggle-agent-job、start-agent-job、stop-agent-job 控制 Agent Job。" } + ] + }, + { + "type": "chapter", + "title": "模块 3 · Redis:实例拓扑与运行时", + "blocks": [ + { "type": "paragraph", "content": "看实例、主从与副本、Ops/sec、内存、客户端、配置、INFO、SlowLog,还能按正则做 Key 内存分析、导出实例配置 zip。数据经 StackExchange.Redis 直连 Redis 的 INFO / CONFIG。视图包括 Dashboard.Instances、Instance.Clients、Instance.Config、Instance.Info、Instance.SlowLog、Instance.Analysis.Memory。" }, + { "type": "paragraph", "content": "管理动作也最丰富:kill 客户端、提升主库(make-master / make-master-promote)、改复制源、清 Key、设置与清除 tiebreaker、批量服务端动作预览与执行。本次本地实际启用的就是这个模块,接的是 WSL2 里的 Redis 6.2.21 单机实例。" }, + { "type": "image", "url": "https://cdn.jsdelivr.net/gh/sugarst/Opserver@8defbfebccb8bc77adf619728b266e85c4cee092/docs/articles/images/redis-dashboard.png", "alt": "配置完成后的 Redis 实例列表" }, + { "type": "paragraph", "content": "图上 1 Chained Instance 前的绿点代表轮询判定健康;表中 Default 是实例名,主机 localhost:6379,角色 Master,0 副本,436 Ops/sec,7.75MB 内存,2 个客户端,9s ago 是轮询缓存的新鲜度。下半部分留白只是因为只配了一个实例。" } + ] + }, + { + "type": "chapter", + "title": "模块 4 · Elastic:集群、索引与分片", + "blocks": [ + { "type": "paragraph", "content": "看集群列表与统计、节点设置、索引列表、分片分布,以及各种 modal 详情;数据来自 Elasticsearch REST,按 Clusters 配置节点。视图有 AllClusters、Cluster.Shards、Cluster.Indexes、Cluster.Panel.Stats、Node.Settings、Indexes.Table。另有 elastic/reroute/{type} 作为分片重路由入口。" } + ] + }, + { + "type": "chapter", + "title": "模块 5 · Exceptions:异常日志处置台", + "blocks": [ + { "type": "paragraph", "content": "把 StackExchange.Exceptional 写入 SQL 存储的应用异常聚合成列表,看详情、堆栈、筛选器、计数与预览;配置里还能写 stackTraceReplacements,把堆栈路径替换成可跳转的 GitHub 源码行链接。" }, + { "type": "paragraph", "content": "管理动作包括 protect(保护)、delete、delete-list(批量删除)以及 Jira 联动建单,对应 Exceptions.Jira 视图和 exceptions/jiraactions、jiraaction 端点。典型的「从告警到建单」闭环就在这里。" } + ] + }, + { + "type": "chapter", + "title": "模块 6 · HAProxy:负载均衡后端", + "blocks": [ + { "type": "paragraph", "content": "按 Instances / Groups 配置抓取 HAProxy stats,展示分组、后端实例、流量与健康状态,视图是 HAProxy.Dashboard 与 HAProxy.cshtml。管理端点 haproxy/admin/action 可以对后端做启停与状态切换,属于典型的值班操作。" } + ] + }, + { + "type": "chapter", + "title": "模块 7 · PagerDuty:值班与事件", + "blocks": [ + { "type": "paragraph", "content": "把「谁在值班」和「现在有什么事」放到同一页:OnCall 值班行、事件详情、完整升级链,数据来自 PagerDuty API(配置 APIKey)。视图有 PagerDuty.OnCallRow、PagerDuty.Incident、PagerDuty.EscFull;动作包括更新事件状态与设置值班覆盖 override。" } + ] + }, + { + "type": "chapter", + "title": "模块 8 · Cloudflare:DNS 与边缘", + "blocks": [ + { "type": "paragraph", "content": "八个模块里最轻的一个,靠 Email + APIKey 调 Cloudflare API,视图是 DNS.cshtml 与 Dashboard.cshtml,看 DNS 记录列表、边缘流量与整体概览,并提供 DNS 记录变更入口。" } + ] + }, + { + "type": "chapter", + "title": "能动手,不只是能看", + "blocks": [ + { "type": "paragraph", "content": "绝大多数监控面板是只读的,Opserver 不是。每个模块都有 *.Admin.cs,端点带 [OnlyAllow(...Roles.Admin)]。这些动作统一受 SecurityManager + Roles(Anonymous / Authenticated / LocalRequest / InternalRequest / ApiRequest / GlobalAdmin / GlobalViewer)+ 模块级 ViewGroups / AdminGroups 约束。也正因如此,默认不给任何访问权限才显得合理。" }, + { "type": "list", "style": "unordered", "items": [ + "/hub(别名 /headsup):把各模块的告警汇总成一页,是真正的「值班首页」。", + "/issues:当前问题聚合;/about 与 /about/caches:认证信息与缓存状态。", + "/ping:健康检查;/debug:请求头与轮询线程状态;/poll:轮询控制。", + "api/node/enable 与 api/node/disable:维护期摘挂节点。", + "MiniProfiler:/mini-profiler-resources/results-index 查看每次请求耗时明细。" + ] } + ] + }, + { + "type": "chapter", + "title": "和 Grafana 怎么分工", + "blocks": [ + { "type": "table", "headers": ["维度", "Opserver", "Prometheus + Grafana"], "rows": [ + ["定位", "实时状态 + 运维操作台", "长期时序 + 图表 + 告警规则"], + ["数据存储", "无独立库,轮询结果在进程内存", "时序数据库,保留历史"], + ["面板来源", "代码内置,配置即启用", "自己写 PromQL / 配面板"], + ["取数方式", "主动轮询各系统原生接口", "exporter 暴露指标后被拉取"], + ["能否处置", "能,切主从 / 停 Job / 清计划", "基本只读"], + ["适合场景", "值班排障、常见操作固化", "趋势分析、容量规划、告警体系"] + ] }, + { "type": "paragraph", "content": "结论不是谁替代谁,而是层次不同:Opserver 是给工程师当场处理问题用的,Grafana 是给团队长期观察系统用的。" } + ] + }, + { + "type": "chapter", + "title": "本地跑起来", + "blocks": [ + { "type": "paragraph", "content": "进入 src/Opserver.Web 目录执行 dotnet run --launch-profile \"Opserver.Web\",默认监听 http://localhost:56058/(Properties/launchSettings.json,Development 环境)。只跑这一条命令,看到的就是开头那张报错页。" }, + { "type": "paragraph", "content": "想看到真实界面,新建一个本地专属的 localSettings.json(该文件已被 .gitignore 忽略):在 Security 下写 \"Provider\": \"EveryonesAnAdmin\",在 Modules.Redis 下写 Servers,包含一个 Name 为 localhost、Instances 里带 Default 与 6379 端口的节点。重启后登录页变成只填用户名(该 Provider 的 FlowType 是 Username,无密码),首页自动跳到 /redis。" }, + { "type": "paragraph", "content": "安全提醒:EveryonesAnAdmin 意味着任意用户名都能拿到全站管理员权限,仅限本地开发。这个文件不能进版本库,更不能出现在生产或公网;生产请改用 ActiveDirectory 或 OIDC。删掉它就恢复默认拒绝访问。" } + ] + }, + { + "type": "chapter", + "title": "升级到 .NET 10 的记录", + "blocks": [ + { "type": "paragraph", "content": "上游 Opserver 长期停留在 .NET 8。当前这个 fork 在 feature/upgrade-net10 分支完成了一轮「功能不变、只换运行时和依赖」的升级,几个有代表性的改动:" }, + { "type": "list", "style": "unordered", "items": [ + "运行时与工程文件:net8.0 → net10.0;.sln → .slnx 并删除旧解决方案;Dockerfile、GitHub Actions、AppVeyor 同步升级。", + "两处废弃 API:Program.cs 改用 Host.CreateDefaultBuilder + ConfigureWebHostDefaults(ASPDEPR008);Startup.cs 改用 KnownIPNetworks + System.Net.IPNetwork(ASPDEPR005),但保留 KnownNetworks 配置键兼容既有部署。在 TreatWarningsAsErrors=true 下两者直接是编译错误。", + "Jil 反序列化必崩:.NET 9+ 新增 TimeSpan.FromSeconds(long) 重载,Jil 2.17.0 反射取方法时抛 AmbiguousMatchException。把源码内置到 vendor/Jil,按精确签名 FromSeconds(double) 改一行,业务代码零改动。", + "SQL 驱动迁移:System.Data.SqlClient → Microsoft.Data.SqlClient 6.1.8(支持到 2028-08 的 LTS)。新驱动默认 Encrypt=true,用 Connection.WithLegacyEncryptionDefault() 补回 Encrypt=False 保持旧连接语义;连带把 StackExchange.Exceptional 从 2.2.35 升到 3.0.1,去掉运行时对旧驱动的硬引用。", + "Redis 3.x 的两个破坏点:SocketManager 被移除(删字段);随包 analyzer 报 SER308 sync-over-async(在 server.Wait(last) 单点豁免并记录原因)。3.x 默认 RESP3,已在 Redis 6.2 上实测握手与轮询正常。", + "测试与可观测性:xunit 2.9.3 → xunit.v3.mtp-off 4.0.2(迁移 v3 但保留 VSTest)、coverlet.collector 10.1.0、MiniProfiler 4.5.8、Dapper 2.1.89、SourceLink 10.0.403。", + "验收:dotnet build 零警告零错误、dotnet test 97/97 通过、Release 发布成功,再辅以启动 / HTTP / Jil 序列化 / SQL 连接四处冒烟。" + ] } + ] + }, + { + "type": "chapter", + "title": "适合谁,以及结语", + "blocks": [ + { "type": "paragraph", "content": "适合:已经在用 SQL Server + Redis + Elastic + HAProxy 这类自建中间件、值班时需要快速判断并处置、不想为每个系统单独开后台、希望查看和操作收在同一套权限体系下的团队。不适合:需要长期历史趋势、容量规划、自定义告警规则、多租户或大规模指标量的场景——这些交给 Prometheus / Grafana / OpenTelemetry。" }, + { "type": "paragraph", "content": "Opserver 是个很有 Stack Overflow 气质的项目:不追求通用,不堆抽象,直接把自己机房里每天要用的排障动作做成页面;默认拒绝一切访问、权限分到模块、轮询只放内存,每一处取舍都透着「给自己运维同事用」的实用主义。它也不是一个能照搬的现代项目:Razor + jQuery 的老前端、部分 TODO 占位、对 .NET 8 的长期停留都还在。但正因如此,把它升级到 .NET 10 的过程反而成了很好的一次架构阅读——你能清楚看到哪些是设计、哪些是历史包袱,以及升级一个真实项目时,编译错误往往只是最容易的那一层。" }, + { "type": "paragraph", "content": "本文基于 feature/upgrade-net10 分支的实际代码与本地运行截图整理,项目主页:github.com/StackExchange/Opserver" } + ] + } + ] +} diff --git a/docs/articles/images/architecture.png b/docs/articles/images/architecture.png new file mode 100644 index 000000000..297d2fb52 Binary files /dev/null and b/docs/articles/images/architecture.png differ diff --git a/docs/articles/images/configuration-problem.png b/docs/articles/images/configuration-problem.png new file mode 100644 index 000000000..2f05142e7 Binary files /dev/null and b/docs/articles/images/configuration-problem.png differ diff --git a/docs/articles/images/modules.png b/docs/articles/images/modules.png new file mode 100644 index 000000000..e43da287c Binary files /dev/null and b/docs/articles/images/modules.png differ diff --git a/docs/articles/images/redis-dashboard.png b/docs/articles/images/redis-dashboard.png new file mode 100644 index 000000000..03cb204e5 Binary files /dev/null and b/docs/articles/images/redis-dashboard.png differ diff --git a/global.json b/global.json new file mode 100644 index 000000000..1f4a13766 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "10.0.404", + "rollForward": "disable", + "allowPrerelease": false + } +} diff --git a/readme.md b/readme.md index 428c7d993..ed334b64e 100644 --- a/readme.md +++ b/readme.md @@ -6,5 +6,17 @@ Opserver is a monitoring system originally from the team at [Stack Exchange](htt [Please see the documentation site here](https://opserver.github.io/Opserver/). +### Build and runtime / 构建与运行时 + +Use .NET SDK **10.0.404** to build this branch. `global.json` selects this exact SDK, including on machines with .NET 11 installed. The web application and tests require .NET runtime **10.0.15** or a compatible later patch; running the web application also requires ASP.NET Core runtime **10.0.15** or a compatible later patch. CI and Docker use the same SDK/runtime versions, and the directly referenced .NET 10 servicing packages use **10.0.15**. Microsoft.Data.SqlClient remains at **6.1.8**. + +本分支使用 .NET SDK **10.0.404** 构建,`global.json` 固定该 SDK,避免在安装了 .NET 11 的机器上使用其他 SDK。Web 应用和测试需要 .NET 运行时 **10.0.15** 或兼容的更高补丁版本;运行 Web 应用还需要 ASP.NET Core 运行时 **10.0.15** 或兼容的更高补丁版本。CI、Docker 使用相同的 SDK/运行时版本,直接引用的 .NET 10 维护包同步升级为 **10.0.15**。Microsoft.Data.SqlClient 保持 **6.1.8**。 + +```shell +dotnet --version +dotnet build Opserver.slnx --configuration Release +dotnet test tests/Opserver.Tests/Opserver.Tests.csproj --configuration Release --no-build --no-restore +``` + ### License Opserver is licensed under the [MIT License](https://opensource.org/licenses/MIT). diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 21c82dae4..433a84ac3 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -24,7 +24,7 @@ - - + +
diff --git a/src/Opserver.Core/Data/Redis/RedisAnalyzer.Memory.cs b/src/Opserver.Core/Data/Redis/RedisAnalyzer.Memory.cs index 0b4094830..7c98df3b3 100644 --- a/src/Opserver.Core/Data/Redis/RedisAnalyzer.Memory.cs +++ b/src/Opserver.Core/Data/Redis/RedisAnalyzer.Memory.cs @@ -173,7 +173,13 @@ public void Analyze(ConnectionMultiplexer muxer) } }); } + // StackExchange.Redis 3.x ships a sync-over-async analyzer (SER308) that flags its own + // Wait helper. This is a synchronous MemCache.GetSet population callback for a low-frequency + // admin operation; converting the chain to async would change the cache API surface. + // Keep the blocking wait and the existing behavior, and record the decision here. +#pragma warning disable SER308 if (last != null) server.Wait(last); +#pragma warning restore SER308 } AnalysisTime = sw.Elapsed; sw.Stop(); diff --git a/src/Opserver.Core/Data/Redis/RedisInstance.cs b/src/Opserver.Core/Data/Redis/RedisInstance.cs index bd832e2b1..834f65b0e 100644 --- a/src/Opserver.Core/Data/Redis/RedisInstance.cs +++ b/src/Opserver.Core/Data/Redis/RedisInstance.cs @@ -103,9 +103,6 @@ public RedisInstance(RedisModule module, RedisConnectionInfo connectionInfo) : b ReplicatesCrossRegion = module.Settings.Replication?.CrossRegionNameRegex?.IsMatch(ConnectionInfo.Name) ?? true; } - // We're not doing a lot of redis access, so tone down the thread count to 1 socket queue handler - public static readonly SocketManager SharedSocketManager = new SocketManager("Opserver Shared"); - private ConnectionMultiplexer GetConnection(bool allowAdmin = false, int syncTimeout = 60000) { var config = new ConfigurationOptions @@ -119,8 +116,7 @@ private ConnectionMultiplexer GetConnection(bool allowAdmin = false, int syncTim { { ConnectionInfo.Host, ConnectionInfo.Port } }, - ClientName = "Opserver", - SocketManager = SharedSocketManager + ClientName = "Opserver" }; return ConnectionMultiplexer.Connect(config); } diff --git a/src/Opserver.Core/Data/SQL/SQLAzureServer.cs b/src/Opserver.Core/Data/SQL/SQLAzureServer.cs index a29403190..0a00d3410 100644 --- a/src/Opserver.Core/Data/SQL/SQLAzureServer.cs +++ b/src/Opserver.Core/Data/SQL/SQLAzureServer.cs @@ -1,6 +1,6 @@ using System.Collections.Concurrent; using System.Collections.Generic; -using System.Data.SqlClient; +using Microsoft.Data.SqlClient; namespace Opserver.Data.SQL { diff --git a/src/Opserver.Core/Data/SQL/SQLInstance.cs b/src/Opserver.Core/Data/SQL/SQLInstance.cs index 7a3e7f0d7..2d11b9135 100644 --- a/src/Opserver.Core/Data/SQL/SQLInstance.cs +++ b/src/Opserver.Core/Data/SQL/SQLInstance.cs @@ -2,9 +2,9 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Data.Common; -using System.Data.SqlClient; using System.Runtime.CompilerServices; using System.Threading.Tasks; +using Microsoft.Data.SqlClient; using Opserver.Helpers; namespace Opserver.Data.SQL diff --git a/src/Opserver.Core/Helpers/Connection.cs b/src/Opserver.Core/Helpers/Connection.cs index 452724c93..4541cadac 100644 --- a/src/Opserver.Core/Helpers/Connection.cs +++ b/src/Opserver.Core/Helpers/Connection.cs @@ -1,9 +1,9 @@ using System; using System.Data; using System.Data.Common; -using System.Data.SqlClient; using System.Threading; using System.Threading.Tasks; +using Microsoft.Data.SqlClient; using StackExchange.Profiling; using StackExchange.Profiling.Data; @@ -11,6 +11,27 @@ namespace Opserver.Helpers { public static class Connection { + /// + /// System.Data.SqlClient defaults to Encrypt=false; Microsoft.Data.SqlClient 4.0+ defaults to Encrypt=true + /// and validates the server certificate. Opserver monitors arbitrary SQL Servers, so swapping the driver + /// must not silently change which servers are reachable. Keep the legacy default when the configured + /// connection string doesn't opt in, and leave any explicit Encrypt=... (including Strict) untouched. + /// Add Encrypt=True to a connection string to opt into encrypted connections. + /// + public static string WithLegacyEncryptionDefault(string connectionString) + { + if (string.IsNullOrWhiteSpace(connectionString)) return connectionString; + + // SqlConnectionStringBuilder pre-populates Encrypt with its own default, so ContainsKey on it is + // always true. The provider-agnostic base builder parses only what is literally in the string. + var parsed = new DbConnectionStringBuilder { ConnectionString = connectionString }; + foreach (string key in parsed.Keys) + { + if (string.Equals(key, "Encrypt", StringComparison.OrdinalIgnoreCase)) return connectionString; + } + return connectionString.TrimEnd(';', ' ') + ";Encrypt=False"; + } + /// /// Gets an open READ UNCOMMITTED connection using the specified connection string, optionally timing out on the initial connect. /// @@ -21,7 +42,7 @@ public static class Connection /// Throws if a connection can't be made in . public static DbConnection GetOpen(string connectionString, int? connectionTimeoutMs = null) { - var conn = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current); + var conn = new ProfiledDbConnection(new SqlConnection(WithLegacyEncryptionDefault(connectionString)), MiniProfiler.Current); static void setReadUncommitted(DbConnection c) { using var cmd = c.CreateCommand(); @@ -75,7 +96,7 @@ static void setReadUncommitted(DbConnection c) /// Throws if a connection can't be made in . public static async Task GetOpenAsync(string connectionString, int? connectionTimeoutMs = null) { - var conn = new ProfiledDbConnection(new SqlConnection(connectionString), MiniProfiler.Current); + var conn = new ProfiledDbConnection(new SqlConnection(WithLegacyEncryptionDefault(connectionString)), MiniProfiler.Current); if (connectionTimeoutMs.GetValueOrDefault(0) == 0) { diff --git a/src/Opserver.Core/Opserver.Core.csproj b/src/Opserver.Core/Opserver.Core.csproj index b16a9181c..6c5b5a174 100644 --- a/src/Opserver.Core/Opserver.Core.csproj +++ b/src/Opserver.Core/Opserver.Core.csproj @@ -2,35 +2,40 @@ Opserver Opserver.Core - net8.0 + net10.0 true embedded - + - - - - - - - + + + + + + + + + + + - - + + + - - - - + + + - - + + - \ No newline at end of file + diff --git a/src/Opserver.Web/Opserver.Web.csproj b/src/Opserver.Web/Opserver.Web.csproj index d69dc84d8..5d092dfa4 100644 --- a/src/Opserver.Web/Opserver.Web.csproj +++ b/src/Opserver.Web/Opserver.Web.csproj @@ -2,16 +2,18 @@ Exe Opserver - net8.0 + net10.0 + 10.0.15 - - - - + + + + + @@ -24,7 +26,7 @@ - - + + 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..7b133097e 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -1,12 +1,19 @@ - Library - 2.4.1 + + Exe + 4.0.2 - - - + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + \ No newline at end of file diff --git a/tests/Opserver.Tests/ConnectionTests.cs b/tests/Opserver.Tests/ConnectionTests.cs new file mode 100644 index 000000000..a3bb6e589 --- /dev/null +++ b/tests/Opserver.Tests/ConnectionTests.cs @@ -0,0 +1,45 @@ +using Microsoft.Data.SqlClient; +using Opserver.Helpers; +using Xunit; + +namespace Opserver.Tests +{ + /// + /// Guards the connection-string compatibility shim used when moving from System.Data.SqlClient + /// (Encrypt defaults to false) to Microsoft.Data.SqlClient (Encrypt defaults to true). + /// + public class ConnectionTests + { + [Theory] + [InlineData("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;", + "Data Source=.;Initial Catalog=master;Integrated Security=SSPI;Encrypt=False")] + [InlineData("Data Source=.;Initial Catalog=master", + "Data Source=.;Initial Catalog=master;Encrypt=False")] + [InlineData("Data Source=.;Initial Catalog=master; ", + "Data Source=.;Initial Catalog=master;Encrypt=False")] + // Explicit settings must never be overridden. + [InlineData("Data Source=.;Encrypt=True;", "Data Source=.;Encrypt=True;")] + [InlineData("Data Source=.;Encrypt=False;", "Data Source=.;Encrypt=False;")] + [InlineData("Data Source=.;Encrypt=Strict;TrustServerCertificate=True;", + "Data Source=.;Encrypt=Strict;TrustServerCertificate=True;")] + [InlineData("data source=.;encrypt = mandatory;", "data source=.;encrypt = mandatory;")] + [InlineData(null, null)] + [InlineData("", "")] + public void LegacyEncryptionDefault(string input, string expected) + { + Assert.Equal(expected, Connection.WithLegacyEncryptionDefault(input)); + } + + [Theory] + [InlineData("Data Source=.;Initial Catalog=master;Integrated Security=SSPI;", "False")] + [InlineData("Data Source=.;Initial Catalog=master;Encrypt=True", "True")] + [InlineData("Data Source=.;Initial Catalog=master;Encrypt=False", "False")] + [InlineData("Data Source=.;Initial Catalog=master;Encrypt=Strict", "Strict")] + public void DriverHonorsTheNormalizedConnectionString(string input, string expectedEncrypt) + { + var normalized = Connection.WithLegacyEncryptionDefault(input); + var builder = new SqlConnectionStringBuilder(normalized); + Assert.Equal(expectedEncrypt, builder.Encrypt.ToString()); + } + } +} diff --git a/tests/Opserver.Tests/IPNetTests.cs b/tests/Opserver.Tests/IPNetTests.cs index f3c97826b..f285f1adc 100644 --- a/tests/Opserver.Tests/IPNetTests.cs +++ b/tests/Opserver.Tests/IPNetTests.cs @@ -1,7 +1,6 @@ using System.Net; using Opserver.Data; using Xunit; -using Xunit.Abstractions; namespace Opserver.Tests { diff --git a/tests/Opserver.Tests/Opserver.Tests.csproj b/tests/Opserver.Tests/Opserver.Tests.csproj index 5cb796eb7..03beafa2c 100644 --- a/tests/Opserver.Tests/Opserver.Tests.csproj +++ b/tests/Opserver.Tests/Opserver.Tests.csproj @@ -2,19 +2,20 @@ Opserver.Tests Opserver.Tests - net8.0 + net10.0 + 10.0.15 - - + + - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - \ No newline at end of file + 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