| | | 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.Concurrent; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Diagnostics; |
| | | 7 | | using System.Diagnostics.CodeAnalysis; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json.Serialization.Metadata |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// Validates and indexes polymorphic type configuration, |
| | | 13 | | /// providing derived JsonTypeInfo resolution methods |
| | | 14 | | /// in both serialization and deserialization scenaria. |
| | | 15 | | /// </summary> |
| | | 16 | | internal sealed class PolymorphicTypeResolver |
| | | 17 | | { |
| | 0 | 18 | | private readonly ConcurrentDictionary<Type, DerivedJsonTypeInfo?> _typeToDiscriminatorId = new(); |
| | | 19 | | private readonly Dictionary<object, DerivedJsonTypeInfo>? _discriminatorIdtoType; |
| | | 20 | | private readonly JsonSerializerOptions _options; |
| | | 21 | | |
| | 0 | 22 | | public PolymorphicTypeResolver(JsonSerializerOptions options, JsonPolymorphismOptions polymorphismOptions, Type |
| | 0 | 23 | | { |
| | 0 | 24 | | UnknownDerivedTypeHandling = polymorphismOptions.UnknownDerivedTypeHandling; |
| | 0 | 25 | | IgnoreUnrecognizedTypeDiscriminators = polymorphismOptions.IgnoreUnrecognizedTypeDiscriminators; |
| | 0 | 26 | | BaseType = baseType; |
| | 0 | 27 | | _options = options; |
| | | 28 | | |
| | 0 | 29 | | if (!IsSupportedPolymorphicBaseType(BaseType)) |
| | 0 | 30 | | { |
| | 0 | 31 | | ThrowHelper.ThrowInvalidOperationException_TypeDoesNotSupportPolymorphism(BaseType); |
| | | 32 | | } |
| | | 33 | | |
| | 0 | 34 | | bool containsDerivedTypes = false; |
| | 0 | 35 | | foreach ((Type derivedType, object? typeDiscriminator) in polymorphismOptions.DerivedTypes) |
| | 0 | 36 | | { |
| | 0 | 37 | | Debug.Assert(typeDiscriminator is null or int or string); |
| | | 38 | | |
| | 0 | 39 | | if (!IsSupportedDerivedType(BaseType, derivedType) || |
| | 0 | 40 | | (derivedType.IsAbstract && UnknownDerivedTypeHandling != JsonUnknownDerivedTypeHandling.FallBackToNe |
| | 0 | 41 | | { |
| | 0 | 42 | | ThrowHelper.ThrowInvalidOperationException_DerivedTypeNotSupported(BaseType, derivedType); |
| | | 43 | | } |
| | | 44 | | |
| | 0 | 45 | | JsonTypeInfo derivedTypeInfo = options.GetTypeInfoInternal(derivedType); |
| | 0 | 46 | | DerivedJsonTypeInfo derivedTypeInfoHolder = new(typeDiscriminator, derivedTypeInfo); |
| | | 47 | | |
| | 0 | 48 | | if (!_typeToDiscriminatorId.TryAdd(derivedType, derivedTypeInfoHolder)) |
| | 0 | 49 | | { |
| | 0 | 50 | | ThrowHelper.ThrowInvalidOperationException_DerivedTypeIsAlreadySpecified(BaseType, derivedType); |
| | | 51 | | } |
| | | 52 | | |
| | 0 | 53 | | if (typeDiscriminator is not null) |
| | 0 | 54 | | { |
| | 0 | 55 | | if (!(_discriminatorIdtoType ??= new()).TryAdd(typeDiscriminator, derivedTypeInfoHolder)) |
| | 0 | 56 | | { |
| | 0 | 57 | | ThrowHelper.ThrowInvalidOperationException_TypeDicriminatorIdIsAlreadySpecified(BaseType, typeDi |
| | | 58 | | } |
| | | 59 | | |
| | 0 | 60 | | UsesTypeDiscriminators = true; |
| | 0 | 61 | | } |
| | | 62 | | |
| | 0 | 63 | | containsDerivedTypes = true; |
| | 0 | 64 | | } |
| | | 65 | | |
| | 0 | 66 | | if (!containsDerivedTypes) |
| | 0 | 67 | | { |
| | 0 | 68 | | ThrowHelper.ThrowInvalidOperationException_PolymorphicTypeConfigurationDoesNotSpecifyDerivedTypes(BaseTy |
| | | 69 | | } |
| | | 70 | | |
| | 0 | 71 | | if (UsesTypeDiscriminators) |
| | 0 | 72 | | { |
| | 0 | 73 | | Debug.Assert(_discriminatorIdtoType is not null, "Discriminator index must have been populated."); |
| | | 74 | | |
| | 0 | 75 | | if (!converterCanHaveMetadata) |
| | 0 | 76 | | { |
| | 0 | 77 | | ThrowHelper.ThrowNotSupportedException_BaseConverterDoesNotSupportMetadata(BaseType); |
| | | 78 | | } |
| | | 79 | | |
| | 0 | 80 | | string propertyName = polymorphismOptions.TypeDiscriminatorPropertyName; |
| | 0 | 81 | | if (!propertyName.Equals(JsonSerializer.TypePropertyName, StringComparison.Ordinal)) |
| | 0 | 82 | | { |
| | 0 | 83 | | byte[] utf8EncodedName = Encoding.UTF8.GetBytes(propertyName); |
| | | 84 | | |
| | | 85 | | // Check if the property name conflicts with other metadata property names |
| | 0 | 86 | | if ((JsonSerializer.GetMetadataPropertyName(utf8EncodedName, resolver: null) & ~MetadataPropertyName |
| | 0 | 87 | | { |
| | 0 | 88 | | ThrowHelper.ThrowInvalidOperationException_InvalidCustomTypeDiscriminatorPropertyName(); |
| | | 89 | | } |
| | | 90 | | |
| | 0 | 91 | | CustomTypeDiscriminatorPropertyNameUtf8 = utf8EncodedName; |
| | 0 | 92 | | CustomTypeDiscriminatorPropertyNameJsonEncoded = JsonEncodedText.Encode(propertyName, options.Encode |
| | 0 | 93 | | } |
| | | 94 | | |
| | | 95 | | // Check if the discriminator property name conflicts with any derived property names. |
| | 0 | 96 | | foreach (DerivedJsonTypeInfo derivedTypeInfo in _discriminatorIdtoType.Values) |
| | 0 | 97 | | { |
| | 0 | 98 | | if (derivedTypeInfo.JsonTypeInfo.Kind is JsonTypeInfoKind.Object) |
| | 0 | 99 | | { |
| | 0 | 100 | | foreach (JsonPropertyInfo property in derivedTypeInfo.JsonTypeInfo.Properties) |
| | 0 | 101 | | { |
| | 0 | 102 | | if (property is { IsIgnored: false, IsExtensionData: false } && property.Name == propertyNam |
| | 0 | 103 | | { |
| | 0 | 104 | | ThrowHelper.ThrowInvalidOperationException_PropertyConflictsWithMetadataPropertyName(der |
| | | 105 | | } |
| | 0 | 106 | | } |
| | 0 | 107 | | } |
| | 0 | 108 | | } |
| | 0 | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | 0 | 112 | | public Type BaseType { get; } |
| | 0 | 113 | | public JsonUnknownDerivedTypeHandling UnknownDerivedTypeHandling { get; } |
| | 0 | 114 | | public bool UsesTypeDiscriminators { get; } |
| | 0 | 115 | | public bool IgnoreUnrecognizedTypeDiscriminators { get; } |
| | 0 | 116 | | public byte[]? CustomTypeDiscriminatorPropertyNameUtf8 { get; } |
| | 0 | 117 | | public JsonEncodedText? CustomTypeDiscriminatorPropertyNameJsonEncoded { get; } |
| | | 118 | | |
| | | 119 | | /// <summary> |
| | | 120 | | /// Resolves a classifier-returned <see cref="Type"/> to its <see cref="JsonTypeInfo"/> using the registered der |
| | | 121 | | /// </summary> |
| | | 122 | | public bool TryResolveDerivedJsonTypeInfo(Type resolvedType, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeInfo) |
| | 0 | 123 | | { |
| | 0 | 124 | | if (_typeToDiscriminatorId.TryGetValue(resolvedType, out DerivedJsonTypeInfo? result) && result is not null) |
| | 0 | 125 | | { |
| | 0 | 126 | | jsonTypeInfo = result.JsonTypeInfo; |
| | 0 | 127 | | return true; |
| | | 128 | | } |
| | | 129 | | |
| | 0 | 130 | | if (IgnoreUnrecognizedTypeDiscriminators) |
| | 0 | 131 | | { |
| | 0 | 132 | | jsonTypeInfo = null; |
| | 0 | 133 | | return false; |
| | | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | ThrowHelper.ThrowNotSupportedException_RuntimeTypeNotSupported(BaseType, resolvedType); |
| | | 137 | | jsonTypeInfo = null; |
| | | 138 | | return false; |
| | 0 | 139 | | } |
| | | 140 | | |
| | | 141 | | public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeInfo, out |
| | 0 | 142 | | { |
| | 0 | 143 | | Debug.Assert(BaseType.IsAssignableFrom(runtimeType)); |
| | | 144 | | |
| | 0 | 145 | | if (!_typeToDiscriminatorId.TryGetValue(runtimeType, out DerivedJsonTypeInfo? result)) |
| | 0 | 146 | | { |
| | 0 | 147 | | switch (UnknownDerivedTypeHandling) |
| | | 148 | | { |
| | | 149 | | case JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor: |
| | | 150 | | // Calculate (and cache the result) of the nearest ancestor for given runtime type. |
| | | 151 | | // A `null` result denotes no matching ancestor type, we also cache that. |
| | 0 | 152 | | result = CalculateNearestAncestor(runtimeType); |
| | 0 | 153 | | _typeToDiscriminatorId[runtimeType] = result; |
| | 0 | 154 | | break; |
| | | 155 | | case JsonUnknownDerivedTypeHandling.FallBackToBaseType: |
| | | 156 | | // Recover the polymorphic contract (i.e. any type discriminators) for the base type, if it exis |
| | 0 | 157 | | _typeToDiscriminatorId.TryGetValue(BaseType, out result); |
| | 0 | 158 | | _typeToDiscriminatorId[runtimeType] = result; |
| | 0 | 159 | | break; |
| | | 160 | | |
| | | 161 | | case JsonUnknownDerivedTypeHandling.FailSerialization: |
| | | 162 | | default: |
| | 0 | 163 | | if (runtimeType != BaseType) |
| | 0 | 164 | | { |
| | 0 | 165 | | ThrowHelper.ThrowNotSupportedException_RuntimeTypeNotSupported(BaseType, runtimeType); |
| | | 166 | | } |
| | 0 | 167 | | break; |
| | | 168 | | } |
| | 0 | 169 | | } |
| | | 170 | | |
| | 0 | 171 | | if (result is null) |
| | 0 | 172 | | { |
| | 0 | 173 | | jsonTypeInfo = null; |
| | 0 | 174 | | typeDiscriminator = null; |
| | 0 | 175 | | return false; |
| | | 176 | | } |
| | | 177 | | else |
| | 0 | 178 | | { |
| | 0 | 179 | | jsonTypeInfo = result.JsonTypeInfo; |
| | 0 | 180 | | typeDiscriminator = result.TypeDiscriminator; |
| | 0 | 181 | | return true; |
| | | 182 | | } |
| | 0 | 183 | | } |
| | | 184 | | |
| | | 185 | | public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeIn |
| | 0 | 186 | | { |
| | 0 | 187 | | Debug.Assert(typeDiscriminator is int or string); |
| | 0 | 188 | | Debug.Assert(UsesTypeDiscriminators); |
| | 0 | 189 | | Debug.Assert(_discriminatorIdtoType is not null); |
| | | 190 | | |
| | 0 | 191 | | if (_discriminatorIdtoType.TryGetValue(typeDiscriminator, out DerivedJsonTypeInfo? result)) |
| | 0 | 192 | | { |
| | 0 | 193 | | Debug.Assert(typeDiscriminator.Equals(result.TypeDiscriminator)); |
| | 0 | 194 | | jsonTypeInfo = result.JsonTypeInfo; |
| | 0 | 195 | | return true; |
| | | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | if (!IgnoreUnrecognizedTypeDiscriminators) |
| | 0 | 199 | | { |
| | 0 | 200 | | ThrowHelper.ThrowJsonException_UnrecognizedTypeDiscriminator(typeDiscriminator); |
| | | 201 | | } |
| | | 202 | | |
| | 0 | 203 | | jsonTypeInfo = null; |
| | 0 | 204 | | return false; |
| | 0 | 205 | | } |
| | | 206 | | |
| | | 207 | | public static bool IsSupportedPolymorphicBaseType(Type? type) => |
| | 0 | 208 | | type != null && |
| | 0 | 209 | | (type.IsClass || type.IsInterface) && |
| | 0 | 210 | | !type.IsSealed && |
| | 0 | 211 | | !type.IsGenericTypeDefinition && |
| | 0 | 212 | | !type.IsPointer && |
| | 0 | 213 | | type != typeof(object); |
| | | 214 | | |
| | | 215 | | public static bool IsSupportedDerivedType(Type baseType, Type? derivedType) => |
| | 0 | 216 | | baseType.IsAssignableFrom(derivedType) && !derivedType.IsGenericTypeDefinition; |
| | | 217 | | |
| | | 218 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", |
| | | 219 | | Justification = "The call to GetInterfaces will cross-reference results with interface types " + |
| | | 220 | | "already declared as derived types of the polymorphic base type.")] |
| | | 221 | | private DerivedJsonTypeInfo? CalculateNearestAncestor(Type type) |
| | 0 | 222 | | { |
| | 0 | 223 | | Debug.Assert(!type.IsAbstract); |
| | 0 | 224 | | Debug.Assert(BaseType.IsAssignableFrom(type)); |
| | 0 | 225 | | Debug.Assert(UnknownDerivedTypeHandling == JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor); |
| | | 226 | | |
| | 0 | 227 | | if (type == BaseType) |
| | 0 | 228 | | { |
| | 0 | 229 | | return null; |
| | | 230 | | } |
| | | 231 | | |
| | 0 | 232 | | DerivedJsonTypeInfo? result = null; |
| | | 233 | | |
| | | 234 | | // First, walk up the class hierarchy for any supported types. |
| | 0 | 235 | | for (Type? candidate = type.BaseType; BaseType.IsAssignableFrom(candidate); candidate = candidate.BaseType) |
| | 0 | 236 | | { |
| | 0 | 237 | | Debug.Assert(candidate != null); |
| | | 238 | | |
| | 0 | 239 | | if (_typeToDiscriminatorId.TryGetValue(candidate, out result)) |
| | 0 | 240 | | { |
| | 0 | 241 | | break; |
| | | 242 | | } |
| | 0 | 243 | | } |
| | | 244 | | |
| | | 245 | | // Interface hierarchies admit the possibility of diamond ambiguities in type discriminators. |
| | | 246 | | // Examine all interface implementations and identify potential conflicts. |
| | 0 | 247 | | if (BaseType.IsInterface) |
| | 0 | 248 | | { |
| | 0 | 249 | | foreach (Type interfaceTy in type.GetInterfaces()) |
| | 0 | 250 | | { |
| | 0 | 251 | | if (interfaceTy != BaseType && BaseType.IsAssignableFrom(interfaceTy) && |
| | 0 | 252 | | _typeToDiscriminatorId.TryGetValue(interfaceTy, out DerivedJsonTypeInfo? interfaceResult) && |
| | 0 | 253 | | interfaceResult is not null) |
| | 0 | 254 | | { |
| | 0 | 255 | | if (result is null) |
| | 0 | 256 | | { |
| | 0 | 257 | | result = interfaceResult; |
| | 0 | 258 | | } |
| | | 259 | | else |
| | 0 | 260 | | { |
| | 0 | 261 | | ThrowHelper.ThrowNotSupportedException_RuntimeTypeDiamondAmbiguity(BaseType, type, result.Js |
| | | 262 | | } |
| | 0 | 263 | | } |
| | 0 | 264 | | } |
| | 0 | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | return result; |
| | 0 | 268 | | } |
| | | 269 | | |
| | | 270 | | /// <summary> |
| | | 271 | | /// Walks the type hierarchy above the current type for any types that use polymorphic configuration. |
| | | 272 | | /// </summary> |
| | | 273 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", |
| | | 274 | | Justification = "The call to GetInterfaces will cross-reference results with interface types " + |
| | | 275 | | "already declared as derived types of the polymorphic base type.")] |
| | | 276 | | internal static JsonTypeInfo? FindNearestPolymorphicBaseType(JsonTypeInfo typeInfo) |
| | 0 | 277 | | { |
| | 0 | 278 | | Debug.Assert(typeInfo.IsConfigured); |
| | | 279 | | |
| | 0 | 280 | | if (typeInfo.PolymorphismOptions is not null) |
| | 0 | 281 | | { |
| | | 282 | | // Type defines its own polymorphic configuration. |
| | 0 | 283 | | return null; |
| | | 284 | | } |
| | | 285 | | |
| | 0 | 286 | | JsonTypeInfo? matchingResult = null; |
| | | 287 | | |
| | | 288 | | // First, walk up the class hierarchy for any supported types. |
| | 0 | 289 | | for (Type? candidate = typeInfo.Type.BaseType; candidate != null; candidate = candidate.BaseType) |
| | 0 | 290 | | { |
| | 0 | 291 | | JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(candidate, typeInfo.Options); |
| | 0 | 292 | | if (candidateInfo?.PolymorphismOptions is not null) |
| | 0 | 293 | | { |
| | | 294 | | // stop on the first ancestor that has a match |
| | 0 | 295 | | matchingResult = candidateInfo; |
| | 0 | 296 | | break; |
| | | 297 | | } |
| | 0 | 298 | | } |
| | | 299 | | |
| | | 300 | | // Now, walk the interface hierarchy for any polymorphic interface declarations. |
| | 0 | 301 | | foreach (Type interfaceType in typeInfo.Type.GetInterfaces()) |
| | 0 | 302 | | { |
| | 0 | 303 | | JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(interfaceType, typeInfo.Options); |
| | 0 | 304 | | if (candidateInfo?.PolymorphismOptions is not null) |
| | 0 | 305 | | { |
| | 0 | 306 | | if (matchingResult is not null) |
| | 0 | 307 | | { |
| | | 308 | | // Resolve any conflicting matches. |
| | 0 | 309 | | if (matchingResult.Type.IsAssignableFrom(interfaceType)) |
| | 0 | 310 | | { |
| | | 311 | | // interface is more derived than previous match, replace it. |
| | 0 | 312 | | matchingResult = candidateInfo; |
| | 0 | 313 | | } |
| | 0 | 314 | | else if (interfaceType.IsAssignableFrom(matchingResult.Type)) |
| | 0 | 315 | | { |
| | | 316 | | // interface is less derived than previous match, keep the previous one. |
| | 0 | 317 | | continue; |
| | | 318 | | } |
| | | 319 | | else |
| | 0 | 320 | | { |
| | | 321 | | // Diamond ambiguity, do not report any ancestors. |
| | 0 | 322 | | return null; |
| | | 323 | | } |
| | 0 | 324 | | } |
| | | 325 | | else |
| | 0 | 326 | | { |
| | 0 | 327 | | matchingResult = candidateInfo; |
| | 0 | 328 | | } |
| | 0 | 329 | | } |
| | 0 | 330 | | } |
| | | 331 | | |
| | 0 | 332 | | return matchingResult; |
| | | 333 | | |
| | | 334 | | static JsonTypeInfo? ResolveAncestorTypeInfo(Type type, JsonSerializerOptions options) |
| | 0 | 335 | | { |
| | | 336 | | try |
| | 0 | 337 | | { |
| | 0 | 338 | | return options.GetTypeInfoInternal(type, ensureNotNull: null); |
| | | 339 | | } |
| | 0 | 340 | | catch |
| | 0 | 341 | | { |
| | | 342 | | // The resolver produced an exception when resolving the ancestor type. |
| | | 343 | | // Eat the exception and report no result instead. |
| | 0 | 344 | | return null; |
| | | 345 | | } |
| | 0 | 346 | | } |
| | 0 | 347 | | } |
| | | 348 | | |
| | | 349 | | /// <summary> |
| | | 350 | | /// JsonTypeInfo result holder for a derived type. |
| | | 351 | | /// </summary> |
| | | 352 | | private sealed class DerivedJsonTypeInfo |
| | | 353 | | { |
| | 0 | 354 | | public DerivedJsonTypeInfo(object? typeDiscriminator, JsonTypeInfo derivedTypeInfo) |
| | 0 | 355 | | { |
| | 0 | 356 | | Debug.Assert(typeDiscriminator is null or int or string); |
| | | 357 | | |
| | 0 | 358 | | TypeDiscriminator = typeDiscriminator; |
| | 0 | 359 | | JsonTypeInfo = derivedTypeInfo; |
| | 0 | 360 | | } |
| | | 361 | | |
| | 0 | 362 | | public object? TypeDiscriminator { get; } |
| | 0 | 363 | | public JsonTypeInfo JsonTypeInfo { get; } |
| | | 364 | | } |
| | | 365 | | } |
| | | 366 | | } |
| | | 367 | | |