| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Collections; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Diagnostics.CodeAnalysis; |
| | | 8 | | using System.Reflection; |
| | | 9 | | using System.Runtime.CompilerServices; |
| | | 10 | | using System.Text.Json.Reflection; |
| | | 11 | | using System.Text.Json.Serialization.Metadata; |
| | | 12 | | |
| | | 13 | | namespace System.Text.Json.Serialization.Converters |
| | | 14 | | { |
| | | 15 | | // Converter for F# discriminated unions. |
| | | 16 | | // Fieldless cases are serialized as JSON strings. |
| | | 17 | | // Cases with fields are serialized as JSON objects with a type discriminator and named field properties. |
| | | 18 | | // The discriminator property name defaults to "$type" but can be customized via [JsonPolymorphic]. |
| | | 19 | | internal sealed class FSharpUnionConverter<T> : JsonConverter<T> |
| | | 20 | | { |
| | 0 | 21 | | internal override bool CanHaveMetadata => true; |
| | | 22 | | private readonly CaseInfo[] _casesByTag; |
| | | 23 | | private readonly Dictionary<string, CaseInfo> _casesByName; |
| | | 24 | | private readonly Dictionary<string, CaseInfo>? _casesByNameCaseInsensitive; |
| | | 25 | | private readonly Func<object, int> _tagReader; |
| | | 26 | | private readonly string _typeDiscriminatorPropertyName; |
| | | 27 | | private readonly JsonEncodedText _typeDiscriminatorPropertyNameEncoded; |
| | | 28 | | private readonly JsonUnmappedMemberHandling _effectiveUnmappedMemberHandling; |
| | | 29 | | |
| | | 30 | | [RequiresUnreferencedCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | | 31 | | [RequiresDynamicCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | 0 | 32 | | public FSharpUnionConverter( |
| | 0 | 33 | | FSharpCoreReflectionProxy.FSharpUnionCaseInfo[] unionCases, |
| | 0 | 34 | | Func<object, int> tagReader, |
| | 0 | 35 | | JsonSerializerOptions options, |
| | 0 | 36 | | string typeDiscriminatorPropertyName) |
| | 0 | 37 | | { |
| | 0 | 38 | | ConverterStrategy = ConverterStrategy.Object; |
| | 0 | 39 | | SupportsMultipleTokenTypes = true; |
| | 0 | 40 | | RequiresReadAhead = true; |
| | 0 | 41 | | _tagReader = tagReader; |
| | 0 | 42 | | _typeDiscriminatorPropertyName = typeDiscriminatorPropertyName; |
| | 0 | 43 | | _typeDiscriminatorPropertyNameEncoded = JsonEncodedText.Encode(typeDiscriminatorPropertyName, options.Encode |
| | 0 | 44 | | _effectiveUnmappedMemberHandling = typeof(T).GetUniqueCustomAttribute<JsonUnmappedMemberHandlingAttribute>(i |
| | 0 | 45 | | ?? options.UnmappedMemberHandling; |
| | | 46 | | |
| | 0 | 47 | | _casesByTag = new CaseInfo[unionCases.Length]; |
| | 0 | 48 | | _casesByName = new Dictionary<string, CaseInfo>(unionCases.Length, StringComparer.Ordinal); |
| | | 49 | | |
| | 0 | 50 | | Dictionary<string, CaseInfo>? caseInsensitiveMap = options.PropertyNameCaseInsensitive |
| | 0 | 51 | | ? new Dictionary<string, CaseInfo>(unionCases.Length, StringComparer.OrdinalIgnoreCase) |
| | 0 | 52 | | : null; |
| | | 53 | | |
| | 0 | 54 | | JsonNamingPolicy? namingPolicy = options.PropertyNamingPolicy; |
| | | 55 | | |
| | 0 | 56 | | foreach (FSharpCoreReflectionProxy.FSharpUnionCaseInfo uc in unionCases) |
| | 0 | 57 | | { |
| | | 58 | | // Case name resolution: JsonPropertyNameAttribute > PropertyNamingPolicy > raw name |
| | 0 | 59 | | string discriminatorName = uc.JsonPropertyName |
| | 0 | 60 | | ?? namingPolicy?.ConvertName(uc.Name) |
| | 0 | 61 | | ?? uc.Name; |
| | | 62 | | |
| | 0 | 63 | | JsonEncodedText encodedDiscriminatorName = JsonEncodedText.Encode(discriminatorName, options.Encoder); |
| | | 64 | | |
| | | 65 | | // Build field info for cases with fields |
| | 0 | 66 | | CaseFieldInfo[]? fields = null; |
| | 0 | 67 | | if (!uc.IsFieldless) |
| | 0 | 68 | | { |
| | 0 | 69 | | fields = new CaseFieldInfo[uc.Fields.Length]; |
| | 0 | 70 | | for (int i = 0; i < uc.Fields.Length; i++) |
| | 0 | 71 | | { |
| | 0 | 72 | | PropertyInfo prop = uc.Fields[i]; |
| | 0 | 73 | | string fieldName = prop.GetCustomAttribute<JsonPropertyNameAttribute>()?.Name |
| | 0 | 74 | | ?? namingPolicy?.ConvertName(prop.Name) |
| | 0 | 75 | | ?? prop.Name; |
| | 0 | 76 | | JsonEncodedText encodedFieldName = JsonEncodedText.Encode(fieldName, options.Encoder); |
| | | 77 | | |
| | 0 | 78 | | fields[i] = new CaseFieldInfo(fieldName, encodedFieldName, prop, options); |
| | 0 | 79 | | } |
| | | 80 | | |
| | | 81 | | // Validate that no field name conflicts with the discriminator property name. |
| | 0 | 82 | | StringComparison conflictComparison = options.PropertyNameCaseInsensitive |
| | 0 | 83 | | ? StringComparison.OrdinalIgnoreCase |
| | 0 | 84 | | : StringComparison.Ordinal; |
| | | 85 | | |
| | 0 | 86 | | for (int i = 0; i < fields.Length; i++) |
| | 0 | 87 | | { |
| | 0 | 88 | | if (fields[i].FieldName.Equals(typeDiscriminatorPropertyName, conflictComparison)) |
| | 0 | 89 | | { |
| | 0 | 90 | | throw new InvalidOperationException(SR.Format(SR.FSharpUnionFieldConflictsWithDiscriminator, |
| | | 91 | | } |
| | 0 | 92 | | } |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | // Build default field values for deserialization with missing fields. |
| | 0 | 96 | | object[]? defaultFieldValues = null; |
| | 0 | 97 | | if (fields is not null) |
| | 0 | 98 | | { |
| | 0 | 99 | | defaultFieldValues = new object[fields.Length]; |
| | 0 | 100 | | for (int i = 0; i < fields.Length; i++) |
| | 0 | 101 | | { |
| | 0 | 102 | | Type fieldType = fields[i].FieldType; |
| | 0 | 103 | | defaultFieldValues[i] = fieldType.IsValueType ? |
| | 0 | 104 | | RuntimeHelpers.GetUninitializedObject(fieldType) : |
| | 0 | 105 | | null!; |
| | 0 | 106 | | } |
| | 0 | 107 | | } |
| | | 108 | | |
| | 0 | 109 | | var caseInfo = new CaseInfo( |
| | 0 | 110 | | discriminatorName, |
| | 0 | 111 | | encodedDiscriminatorName, |
| | 0 | 112 | | uc.Tag, |
| | 0 | 113 | | uc.IsFieldless, |
| | 0 | 114 | | fields, |
| | 0 | 115 | | defaultFieldValues, |
| | 0 | 116 | | fields is not null ? BuildFieldIndexMap(fields, StringComparer.Ordinal, typeof(T), discriminatorName |
| | 0 | 117 | | fields is not null && options.PropertyNameCaseInsensitive ? BuildFieldIndexMap(fields, StringCompare |
| | 0 | 118 | | uc.FieldReader, |
| | 0 | 119 | | uc.Constructor, |
| | 0 | 120 | | typeof(T)); |
| | | 121 | | |
| | 0 | 122 | | _casesByTag[uc.Tag] = caseInfo; |
| | | 123 | | |
| | 0 | 124 | | if (!_casesByName.TryAdd(discriminatorName, caseInfo)) |
| | 0 | 125 | | { |
| | 0 | 126 | | throw new InvalidOperationException(SR.Format(SR.FSharpUnionDuplicateCaseName, typeof(T), discrimina |
| | | 127 | | } |
| | | 128 | | |
| | 0 | 129 | | if (caseInsensitiveMap is not null && !caseInsensitiveMap.TryAdd(discriminatorName, caseInfo)) |
| | 0 | 130 | | { |
| | 0 | 131 | | throw new InvalidOperationException(SR.Format(SR.FSharpUnionDuplicateCaseName, typeof(T), discrimina |
| | | 132 | | } |
| | 0 | 133 | | } |
| | | 134 | | |
| | 0 | 135 | | _casesByNameCaseInsensitive = caseInsensitiveMap; |
| | 0 | 136 | | } |
| | | 137 | | |
| | | 138 | | public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 0 | 139 | | { |
| | | 140 | | // Fallback for direct converter invocations. The normal pipeline |
| | | 141 | | // uses TryRead -> OnTryRead which forwards state automatically. |
| | 0 | 142 | | ReadStack state = default; |
| | 0 | 143 | | JsonTypeInfo jsonTypeInfo = options.GetTypeInfoInternal(typeToConvert); |
| | 0 | 144 | | state.Initialize(jsonTypeInfo); |
| | 0 | 145 | | state.Push(); |
| | | 146 | | |
| | 0 | 147 | | OnTryRead(ref reader, typeToConvert, options, ref state, out T? value); |
| | 0 | 148 | | return value!; |
| | 0 | 149 | | } |
| | | 150 | | |
| | | 151 | | internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, s |
| | 0 | 152 | | { |
| | 0 | 153 | | if (reader.TokenType == JsonTokenType.String) |
| | 0 | 154 | | { |
| | 0 | 155 | | value = ReadFromString(ref reader, options); |
| | 0 | 156 | | return true; |
| | | 157 | | } |
| | | 158 | | |
| | 0 | 159 | | if (reader.TokenType == JsonTokenType.StartObject) |
| | 0 | 160 | | { |
| | 0 | 161 | | value = ReadFromObject(ref reader, options, ref state); |
| | 0 | 162 | | return true; |
| | | 163 | | } |
| | | 164 | | |
| | 0 | 165 | | ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(typeof(T)); |
| | | 166 | | value = default; |
| | | 167 | | return true; |
| | 0 | 168 | | } |
| | | 169 | | |
| | | 170 | | private T ReadFromString(ref Utf8JsonReader reader, JsonSerializerOptions options) |
| | 0 | 171 | | { |
| | 0 | 172 | | string? caseName = reader.GetString(); |
| | 0 | 173 | | if (caseName is null) |
| | 0 | 174 | | { |
| | 0 | 175 | | ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(typeof(T)); |
| | | 176 | | } |
| | | 177 | | |
| | 0 | 178 | | CaseInfo caseInfo = LookupCaseByName(caseName!); |
| | | 179 | | |
| | 0 | 180 | | if (caseInfo.IsFieldless) |
| | 0 | 181 | | { |
| | 0 | 182 | | return (T)caseInfo.Constructor(Array.Empty<object>()); |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | // String form for a case with fields: only allowed when fields are not required. |
| | 0 | 186 | | if (options.RespectRequiredConstructorParameters) |
| | 0 | 187 | | { |
| | 0 | 188 | | ThrowHelper.ThrowJsonException(); |
| | | 189 | | } |
| | | 190 | | |
| | 0 | 191 | | return (T)caseInfo.Constructor((object[])caseInfo.DefaultFieldValues!.Clone()); |
| | 0 | 192 | | } |
| | | 193 | | |
| | | 194 | | private T ReadFromObject(ref Utf8JsonReader reader, JsonSerializerOptions options, scoped ref ReadStack state) |
| | 0 | 195 | | { |
| | 0 | 196 | | Debug.Assert(reader.TokenType == JsonTokenType.StartObject); |
| | | 197 | | |
| | | 198 | | // This converter opts into read-ahead buffering (via RequiresReadAhead), |
| | | 199 | | // so by the time ReadFromObject is called the entire JSON value has been |
| | | 200 | | // buffered and we can safely scan ahead for the discriminator and restore the reader position. |
| | 0 | 201 | | Utf8JsonReader checkpoint = reader; |
| | | 202 | | |
| | 0 | 203 | | bool preserveReferences = !typeof(T).IsValueType && |
| | 0 | 204 | | options.ReferenceHandlingStrategy == JsonKnownReferenceHandler.Preserve; |
| | | 205 | | |
| | | 206 | | // Scan for the type discriminator and any reference metadata ($id, $ref). |
| | 0 | 207 | | string? caseName = null; |
| | 0 | 208 | | string? referenceId = null; |
| | 0 | 209 | | bool hasNonMetadataProperties = false; |
| | 0 | 210 | | while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) |
| | 0 | 211 | | { |
| | 0 | 212 | | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| | | 213 | | |
| | 0 | 214 | | if (preserveReferences) |
| | 0 | 215 | | { |
| | 0 | 216 | | switch (JsonSerializer.GetMetadataPropertyName(reader.GetUnescapedSpan(), resolver: null)) |
| | | 217 | | { |
| | | 218 | | case MetadataPropertyName.Ref: |
| | 0 | 219 | | if (hasNonMetadataProperties || referenceId is not null) |
| | 0 | 220 | | { |
| | 0 | 221 | | ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); |
| | | 222 | | } |
| | | 223 | | |
| | 0 | 224 | | reader.Read(); |
| | 0 | 225 | | if (reader.TokenType != JsonTokenType.String) |
| | 0 | 226 | | { |
| | 0 | 227 | | ThrowHelper.ThrowJsonException(); |
| | | 228 | | } |
| | | 229 | | |
| | 0 | 230 | | string refValue = reader.GetString()!; |
| | | 231 | | |
| | | 232 | | // Validate that no other properties follow $ref. |
| | 0 | 233 | | while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) |
| | 0 | 234 | | { |
| | 0 | 235 | | ThrowHelper.ThrowJsonException_MetadataReferenceObjectCannotContainOtherProperties(); |
| | | 236 | | } |
| | | 237 | | |
| | 0 | 238 | | return (T)state.ReferenceResolver.ResolveReference(refValue); |
| | | 239 | | |
| | | 240 | | case MetadataPropertyName.Id: |
| | 0 | 241 | | if (referenceId is not null) |
| | 0 | 242 | | { |
| | 0 | 243 | | ThrowHelper.ThrowJsonException(); |
| | | 244 | | } |
| | | 245 | | |
| | 0 | 246 | | reader.Read(); |
| | 0 | 247 | | if (reader.TokenType != JsonTokenType.String) |
| | 0 | 248 | | { |
| | 0 | 249 | | ThrowHelper.ThrowJsonException(); |
| | | 250 | | } |
| | | 251 | | |
| | 0 | 252 | | referenceId = reader.GetString(); |
| | 0 | 253 | | continue; |
| | | 254 | | } |
| | 0 | 255 | | } |
| | | 256 | | |
| | 0 | 257 | | hasNonMetadataProperties = true; |
| | 0 | 258 | | bool isDiscriminator = reader.ValueTextEquals(_typeDiscriminatorPropertyName); |
| | 0 | 259 | | reader.Read(); |
| | | 260 | | |
| | 0 | 261 | | if (isDiscriminator) |
| | 0 | 262 | | { |
| | 0 | 263 | | if (reader.TokenType != JsonTokenType.String) |
| | 0 | 264 | | { |
| | 0 | 265 | | ThrowHelper.ThrowJsonException(); |
| | | 266 | | } |
| | | 267 | | |
| | 0 | 268 | | caseName = reader.GetString(); |
| | | 269 | | |
| | 0 | 270 | | if (!preserveReferences) |
| | 0 | 271 | | { |
| | 0 | 272 | | break; |
| | | 273 | | } |
| | | 274 | | |
| | 0 | 275 | | continue; |
| | | 276 | | } |
| | | 277 | | |
| | 0 | 278 | | reader.TrySkip(); |
| | 0 | 279 | | } |
| | | 280 | | |
| | 0 | 281 | | if (caseName is null) |
| | 0 | 282 | | { |
| | 0 | 283 | | throw new JsonException(SR.Format(SR.FSharpUnionMissingDiscriminatorProperty, _typeDiscriminatorProperty |
| | | 284 | | } |
| | | 285 | | |
| | 0 | 286 | | CaseInfo caseInfo = LookupCaseByName(caseName); |
| | | 287 | | |
| | | 288 | | // Second pass: restore reader and process all properties in a single loop. |
| | 0 | 289 | | reader = checkpoint; |
| | 0 | 290 | | bool discriminatorSeen = false; |
| | 0 | 291 | | object[]? fieldValues = caseInfo.IsFieldless ? null : (object[])caseInfo.DefaultFieldValues!.Clone(); |
| | 0 | 292 | | bool trackPopulated = !caseInfo.IsFieldless && (options.RespectRequiredConstructorParameters || !options.All |
| | 0 | 293 | | BitArray? populatedFields = trackPopulated ? new BitArray(caseInfo.Fields!.Length) : null; |
| | | 294 | | |
| | 0 | 295 | | while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) |
| | 0 | 296 | | { |
| | 0 | 297 | | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| | | 298 | | |
| | | 299 | | // Skip discriminator property, detecting duplicates. |
| | 0 | 300 | | if (reader.ValueTextEquals(_typeDiscriminatorPropertyName)) |
| | 0 | 301 | | { |
| | 0 | 302 | | if (discriminatorSeen) |
| | 0 | 303 | | { |
| | 0 | 304 | | ThrowHelper.ThrowJsonException_DuplicatePropertyNotAllowed(_typeDiscriminatorPropertyName); |
| | | 305 | | } |
| | | 306 | | |
| | 0 | 307 | | discriminatorSeen = true; |
| | 0 | 308 | | reader.Read(); |
| | 0 | 309 | | reader.TrySkip(); |
| | 0 | 310 | | continue; |
| | | 311 | | } |
| | | 312 | | |
| | | 313 | | // Skip metadata properties ($id, $ref) already processed in the first pass. |
| | 0 | 314 | | if (preserveReferences && |
| | 0 | 315 | | JsonSerializer.GetMetadataPropertyName(reader.GetUnescapedSpan(), resolver: null) is not MetadataPro |
| | 0 | 316 | | { |
| | 0 | 317 | | reader.Read(); |
| | 0 | 318 | | reader.TrySkip(); |
| | 0 | 319 | | continue; |
| | | 320 | | } |
| | | 321 | | |
| | | 322 | | // Try to match a union case field. |
| | 0 | 323 | | string? fieldName = reader.GetString(); |
| | 0 | 324 | | reader.Read(); |
| | | 325 | | |
| | 0 | 326 | | if (fieldValues is not null && fieldName is not null && TryGetFieldIndex(fieldName, caseInfo, out int fi |
| | 0 | 327 | | { |
| | 0 | 328 | | if (populatedFields is not null) |
| | 0 | 329 | | { |
| | 0 | 330 | | if (!options.AllowDuplicateProperties && populatedFields[fieldIndex]) |
| | 0 | 331 | | { |
| | 0 | 332 | | ThrowHelper.ThrowJsonException_DuplicatePropertyNotAllowed(fieldName); |
| | | 333 | | } |
| | | 334 | | |
| | 0 | 335 | | populatedFields[fieldIndex] = true; |
| | 0 | 336 | | } |
| | | 337 | | |
| | 0 | 338 | | CaseFieldInfo field = caseInfo.Fields![fieldIndex]; |
| | 0 | 339 | | state.Current.JsonPropertyInfo = field.PropertyInfoForTypeInfo; |
| | 0 | 340 | | state.Current.NumberHandling = field.NumberHandling; |
| | 0 | 341 | | bool success = field.Converter.TryReadAsObject(ref reader, field.FieldType, options, ref state, out |
| | 0 | 342 | | Debug.Assert(success, "Nested converter should not suspend since the union payload is fully buffered |
| | 0 | 343 | | fieldValues[fieldIndex] = fieldValue!; |
| | 0 | 344 | | } |
| | | 345 | | else |
| | 0 | 346 | | { |
| | 0 | 347 | | if (_effectiveUnmappedMemberHandling is JsonUnmappedMemberHandling.Disallow) |
| | 0 | 348 | | { |
| | 0 | 349 | | ThrowHelper.ThrowJsonException_UnmappedJsonProperty(typeof(T), fieldName ?? string.Empty); |
| | | 350 | | } |
| | | 351 | | |
| | 0 | 352 | | reader.TrySkip(); |
| | 0 | 353 | | } |
| | 0 | 354 | | } |
| | | 355 | | |
| | 0 | 356 | | if (options.RespectRequiredConstructorParameters && populatedFields is not null && !populatedFields.HasAllSe |
| | 0 | 357 | | { |
| | 0 | 358 | | ThrowForMissingRequiredFields(caseInfo, populatedFields); |
| | 0 | 359 | | } |
| | | 360 | | |
| | 0 | 361 | | T result = caseInfo.IsFieldless |
| | 0 | 362 | | ? (T)caseInfo.Constructor(Array.Empty<object>()) |
| | 0 | 363 | | : (T)caseInfo.Constructor(fieldValues!); |
| | | 364 | | |
| | 0 | 365 | | if (referenceId is not null) |
| | 0 | 366 | | { |
| | 0 | 367 | | state.ReferenceResolver.AddReference(referenceId, result); |
| | 0 | 368 | | } |
| | | 369 | | |
| | 0 | 370 | | return result; |
| | 0 | 371 | | } |
| | | 372 | | |
| | | 373 | | private static void ThrowForMissingRequiredFields(CaseInfo caseInfo, BitArray populatedFields) |
| | 0 | 374 | | { |
| | 0 | 375 | | StringBuilder builder = new(); |
| | 0 | 376 | | for (int i = 0; i < caseInfo.Fields!.Length; i++) |
| | 0 | 377 | | { |
| | 0 | 378 | | if (!populatedFields[i]) |
| | 0 | 379 | | { |
| | 0 | 380 | | if (!ThrowHelper.AppendMissingProperty(builder, caseInfo.Fields[i].FieldName)) |
| | 0 | 381 | | { |
| | 0 | 382 | | break; |
| | | 383 | | } |
| | 0 | 384 | | } |
| | 0 | 385 | | } |
| | | 386 | | |
| | 0 | 387 | | ThrowHelper.ThrowJsonException_JsonRequiredPropertyMissing(caseInfo.DeclaringType, builder.ToString()); |
| | | 388 | | } |
| | | 389 | | |
| | | 390 | | public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) |
| | 0 | 391 | | { |
| | | 392 | | // Fallback for direct converter invocations. The normal pipeline |
| | | 393 | | // uses TryWrite -> OnTryWrite which forwards state automatically. |
| | 0 | 394 | | WriteStack state = default; |
| | 0 | 395 | | JsonTypeInfo typeInfo = options.GetTypeInfoInternal(typeof(T)); |
| | 0 | 396 | | state.Initialize(typeInfo); |
| | 0 | 397 | | state.Push(); |
| | | 398 | | |
| | | 399 | | try |
| | 0 | 400 | | { |
| | 0 | 401 | | OnTryWrite(writer, value, options, ref state); |
| | 0 | 402 | | } |
| | 0 | 403 | | catch |
| | 0 | 404 | | { |
| | 0 | 405 | | state.DisposePendingDisposablesOnException(); |
| | 0 | 406 | | throw; |
| | | 407 | | } |
| | 0 | 408 | | } |
| | | 409 | | |
| | | 410 | | internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack |
| | 0 | 411 | | { |
| | 0 | 412 | | int tag = _tagReader(value!); |
| | 0 | 413 | | CaseInfo caseInfo = _casesByTag[tag]; |
| | | 414 | | |
| | | 415 | | // Fieldless cases serialize as strings when reference tracking is not active. |
| | 0 | 416 | | if (caseInfo.IsFieldless && state.NewReferenceId is null) |
| | 0 | 417 | | { |
| | 0 | 418 | | writer.WriteStringValue(caseInfo.EncodedDiscriminatorName); |
| | 0 | 419 | | return true; |
| | | 420 | | } |
| | | 421 | | |
| | 0 | 422 | | writer.WriteStartObject(); |
| | | 423 | | |
| | | 424 | | // Write $id metadata if a new reference was registered by TryWrite. |
| | 0 | 425 | | if (state.NewReferenceId is not null) |
| | 0 | 426 | | { |
| | 0 | 427 | | writer.WriteString(JsonSerializer.s_metadataId, state.NewReferenceId); |
| | 0 | 428 | | state.NewReferenceId = null; |
| | 0 | 429 | | } |
| | | 430 | | |
| | 0 | 431 | | writer.WriteString(_typeDiscriminatorPropertyNameEncoded, caseInfo.EncodedDiscriminatorName); |
| | | 432 | | |
| | 0 | 433 | | if (!caseInfo.IsFieldless) |
| | 0 | 434 | | { |
| | 0 | 435 | | object[] fieldValues = caseInfo.FieldReader(value!); |
| | 0 | 436 | | Debug.Assert(fieldValues.Length == caseInfo.Fields!.Length); |
| | | 437 | | |
| | 0 | 438 | | for (int i = 0; i < caseInfo.Fields.Length; i++) |
| | 0 | 439 | | { |
| | 0 | 440 | | CaseFieldInfo field = caseInfo.Fields[i]; |
| | 0 | 441 | | writer.WritePropertyName(field.EncodedFieldName); |
| | 0 | 442 | | state.Current.JsonPropertyInfo = field.PropertyInfoForTypeInfo; |
| | 0 | 443 | | state.Current.NumberHandling = field.NumberHandling; |
| | 0 | 444 | | bool success = field.Converter.TryWriteAsObject(writer, fieldValues[i], options, ref state); |
| | 0 | 445 | | Debug.Assert(success, "Nested converter should not suspend since the union payload is fully buffered |
| | 0 | 446 | | } |
| | 0 | 447 | | } |
| | | 448 | | |
| | 0 | 449 | | writer.WriteEndObject(); |
| | 0 | 450 | | return true; |
| | 0 | 451 | | } |
| | | 452 | | |
| | | 453 | | internal override void ConfigureJsonTypeInfo(JsonTypeInfo jsonTypeInfo, JsonSerializerOptions options) |
| | 0 | 454 | | { |
| | | 455 | | // Clear any polymorphism options that PopulatePolymorphismMetadata() may have set |
| | | 456 | | // from a [JsonPolymorphic] attribute. The F# union converter handles the type |
| | | 457 | | // discriminator internally and does not use the standard polymorphism pipeline. |
| | 0 | 458 | | jsonTypeInfo.PolymorphismOptions = null; |
| | 0 | 459 | | } |
| | | 460 | | |
| | | 461 | | private CaseInfo LookupCaseByName(string caseName) |
| | 0 | 462 | | { |
| | 0 | 463 | | if (_casesByName.TryGetValue(caseName, out CaseInfo? caseInfo)) |
| | 0 | 464 | | { |
| | 0 | 465 | | return caseInfo; |
| | | 466 | | } |
| | | 467 | | |
| | 0 | 468 | | if (_casesByNameCaseInsensitive?.TryGetValue(caseName, out caseInfo) == true) |
| | 0 | 469 | | { |
| | 0 | 470 | | return caseInfo; |
| | | 471 | | } |
| | | 472 | | |
| | 0 | 473 | | ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(typeof(T)); |
| | | 474 | | return default!; |
| | 0 | 475 | | } |
| | | 476 | | |
| | | 477 | | private static bool TryGetFieldIndex( |
| | | 478 | | string fieldName, |
| | | 479 | | CaseInfo caseInfo, |
| | | 480 | | out int fieldIndex) |
| | 0 | 481 | | { |
| | 0 | 482 | | if (caseInfo.FieldIndexMap!.TryGetValue(fieldName, out fieldIndex)) |
| | 0 | 483 | | { |
| | 0 | 484 | | return true; |
| | | 485 | | } |
| | | 486 | | |
| | 0 | 487 | | if (caseInfo.FieldIndexMapCaseInsensitive?.TryGetValue(fieldName, out fieldIndex) == true) |
| | 0 | 488 | | { |
| | 0 | 489 | | return true; |
| | | 490 | | } |
| | | 491 | | |
| | 0 | 492 | | fieldIndex = -1; |
| | 0 | 493 | | return false; |
| | 0 | 494 | | } |
| | | 495 | | |
| | | 496 | | private static Dictionary<string, int> BuildFieldIndexMap(CaseFieldInfo[] fields, StringComparer comparer, Type |
| | 0 | 497 | | { |
| | 0 | 498 | | var map = new Dictionary<string, int>(fields.Length, comparer); |
| | 0 | 499 | | for (int i = 0; i < fields.Length; i++) |
| | 0 | 500 | | { |
| | 0 | 501 | | if (!map.TryAdd(fields[i].FieldName, i)) |
| | 0 | 502 | | { |
| | 0 | 503 | | throw new InvalidOperationException(SR.Format(SR.FSharpUnionDuplicateFieldName, declaringType, caseN |
| | | 504 | | } |
| | 0 | 505 | | } |
| | | 506 | | |
| | 0 | 507 | | return map; |
| | 0 | 508 | | } |
| | | 509 | | |
| | | 510 | | private sealed class CaseInfo |
| | | 511 | | { |
| | 0 | 512 | | public CaseInfo( |
| | 0 | 513 | | string discriminatorName, |
| | 0 | 514 | | JsonEncodedText encodedDiscriminatorName, |
| | 0 | 515 | | int tag, |
| | 0 | 516 | | bool isFieldless, |
| | 0 | 517 | | CaseFieldInfo[]? fields, |
| | 0 | 518 | | object[]? defaultFieldValues, |
| | 0 | 519 | | Dictionary<string, int>? fieldIndexMap, |
| | 0 | 520 | | Dictionary<string, int>? fieldIndexMapCaseInsensitive, |
| | 0 | 521 | | Func<object, object[]> fieldReader, |
| | 0 | 522 | | Func<object[], object> constructor, |
| | 0 | 523 | | Type declaringType) |
| | 0 | 524 | | { |
| | 0 | 525 | | DiscriminatorName = discriminatorName; |
| | 0 | 526 | | EncodedDiscriminatorName = encodedDiscriminatorName; |
| | 0 | 527 | | Tag = tag; |
| | 0 | 528 | | IsFieldless = isFieldless; |
| | 0 | 529 | | Fields = fields; |
| | 0 | 530 | | DefaultFieldValues = defaultFieldValues; |
| | 0 | 531 | | FieldIndexMap = fieldIndexMap; |
| | 0 | 532 | | FieldIndexMapCaseInsensitive = fieldIndexMapCaseInsensitive; |
| | 0 | 533 | | FieldReader = fieldReader; |
| | 0 | 534 | | Constructor = constructor; |
| | 0 | 535 | | DeclaringType = declaringType; |
| | 0 | 536 | | } |
| | | 537 | | |
| | | 538 | | public string DiscriminatorName { get; } |
| | 0 | 539 | | public JsonEncodedText EncodedDiscriminatorName { get; } |
| | | 540 | | public int Tag { get; } |
| | 0 | 541 | | public bool IsFieldless { get; } |
| | 0 | 542 | | public CaseFieldInfo[]? Fields { get; } |
| | 0 | 543 | | public object[]? DefaultFieldValues { get; } |
| | 0 | 544 | | public Dictionary<string, int>? FieldIndexMap { get; } |
| | 0 | 545 | | public Dictionary<string, int>? FieldIndexMapCaseInsensitive { get; } |
| | 0 | 546 | | public Func<object, object[]> FieldReader { get; } |
| | 0 | 547 | | public Func<object[], object> Constructor { get; } |
| | 0 | 548 | | public Type DeclaringType { get; } |
| | | 549 | | } |
| | | 550 | | |
| | | 551 | | private sealed class CaseFieldInfo |
| | | 552 | | { |
| | | 553 | | private readonly JsonSerializerOptions _options; |
| | | 554 | | private JsonConverter? _converter; |
| | | 555 | | private JsonPropertyInfo? _propertyInfoForTypeInfo; |
| | | 556 | | |
| | | 557 | | [RequiresUnreferencedCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | | 558 | | [RequiresDynamicCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | 0 | 559 | | public CaseFieldInfo( |
| | 0 | 560 | | string fieldName, |
| | 0 | 561 | | JsonEncodedText encodedFieldName, |
| | 0 | 562 | | PropertyInfo propertyInfo, |
| | 0 | 563 | | JsonSerializerOptions options) |
| | 0 | 564 | | { |
| | 0 | 565 | | FieldName = fieldName; |
| | 0 | 566 | | EncodedFieldName = encodedFieldName; |
| | 0 | 567 | | FieldType = propertyInfo.PropertyType; |
| | 0 | 568 | | _options = options; |
| | | 569 | | |
| | | 570 | | // Honor [JsonConverter] on the field PropertyInfo. |
| | 0 | 571 | | JsonConverterAttribute? converterAttr = propertyInfo.GetCustomAttribute<JsonConverterAttribute>(inherit: |
| | 0 | 572 | | if (converterAttr is not null) |
| | 0 | 573 | | { |
| | 0 | 574 | | _converter = ResolveCustomConverter(converterAttr, FieldType, propertyInfo, options); |
| | 0 | 575 | | } |
| | | 576 | | |
| | | 577 | | // Honor [JsonNumberHandling] on the field PropertyInfo. |
| | 0 | 578 | | NumberHandling = propertyInfo.GetCustomAttribute<JsonNumberHandlingAttribute>(inherit: false)?.Handling; |
| | 0 | 579 | | } |
| | | 580 | | |
| | 0 | 581 | | public string FieldName { get; } |
| | 0 | 582 | | public JsonEncodedText EncodedFieldName { get; } |
| | 0 | 583 | | public Type FieldType { get; } |
| | 0 | 584 | | public JsonNumberHandling? NumberHandling { get; } |
| | 0 | 585 | | public JsonConverter Converter => _converter ??= _options.GetConverterInternal(FieldType); |
| | 0 | 586 | | public JsonPropertyInfo PropertyInfoForTypeInfo => _propertyInfoForTypeInfo ??= _options.GetTypeInfoInternal |
| | | 587 | | |
| | | 588 | | [RequiresUnreferencedCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | | 589 | | [RequiresDynamicCode(FSharpCoreReflectionProxy.FSharpCoreUnreferencedCodeMessage)] |
| | | 590 | | private static JsonConverter ResolveCustomConverter(JsonConverterAttribute converterAttribute, Type fieldTyp |
| | 0 | 591 | | { |
| | 0 | 592 | | Type? converterType = converterAttribute.ConverterType; |
| | | 593 | | JsonConverter? converter; |
| | | 594 | | |
| | 0 | 595 | | if (converterType is null) |
| | 0 | 596 | | { |
| | 0 | 597 | | converter = converterAttribute.CreateConverter(fieldType); |
| | 0 | 598 | | if (converter is null) |
| | 0 | 599 | | { |
| | 0 | 600 | | ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(proper |
| | | 601 | | } |
| | 0 | 602 | | } |
| | | 603 | | else |
| | 0 | 604 | | { |
| | 0 | 605 | | ConstructorInfo? ctor = converterType.GetConstructor(Type.EmptyTypes); |
| | 0 | 606 | | if (!typeof(JsonConverter).IsAssignableFrom(converterType) || ctor is null || !ctor.IsPublic) |
| | 0 | 607 | | { |
| | 0 | 608 | | ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeInvalid(propertyInfo |
| | | 609 | | } |
| | | 610 | | |
| | 0 | 611 | | converter = (JsonConverter)Activator.CreateInstance(converterType)!; |
| | 0 | 612 | | } |
| | | 613 | | |
| | 0 | 614 | | if (!converter!.CanConvert(fieldType)) |
| | 0 | 615 | | { |
| | 0 | 616 | | ThrowHelper.ThrowInvalidOperationException_SerializationConverterOnAttributeNotCompatible(propertyIn |
| | | 617 | | } |
| | | 618 | | |
| | 0 | 619 | | if (converter is JsonConverterFactory factory) |
| | 0 | 620 | | { |
| | 0 | 621 | | converter = factory.GetConverterInternal(fieldType, options); |
| | 0 | 622 | | } |
| | | 623 | | |
| | 0 | 624 | | return converter!; |
| | 0 | 625 | | } |
| | | 626 | | } |
| | | 627 | | } |
| | | 628 | | } |
| | | 629 | | |