| | | 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 != 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 | | public bool TryGetDerivedJsonTypeInfo(Type runtimeType, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeInfo, out |
| | 0 | 120 | | { |
| | 0 | 121 | | Debug.Assert(BaseType.IsAssignableFrom(runtimeType)); |
| | | 122 | | |
| | 0 | 123 | | if (!_typeToDiscriminatorId.TryGetValue(runtimeType, out DerivedJsonTypeInfo? result)) |
| | 0 | 124 | | { |
| | 0 | 125 | | switch (UnknownDerivedTypeHandling) |
| | | 126 | | { |
| | | 127 | | case JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor: |
| | | 128 | | // Calculate (and cache the result) of the nearest ancestor for given runtime type. |
| | | 129 | | // A `null` result denotes no matching ancestor type, we also cache that. |
| | 0 | 130 | | result = CalculateNearestAncestor(runtimeType); |
| | 0 | 131 | | _typeToDiscriminatorId[runtimeType] = result; |
| | 0 | 132 | | break; |
| | | 133 | | case JsonUnknownDerivedTypeHandling.FallBackToBaseType: |
| | | 134 | | // Recover the polymorphic contract (i.e. any type discriminators) for the base type, if it exis |
| | 0 | 135 | | _typeToDiscriminatorId.TryGetValue(BaseType, out result); |
| | 0 | 136 | | _typeToDiscriminatorId[runtimeType] = result; |
| | 0 | 137 | | break; |
| | | 138 | | |
| | | 139 | | case JsonUnknownDerivedTypeHandling.FailSerialization: |
| | | 140 | | default: |
| | 0 | 141 | | if (runtimeType != BaseType) |
| | 0 | 142 | | { |
| | 0 | 143 | | ThrowHelper.ThrowNotSupportedException_RuntimeTypeNotSupported(BaseType, runtimeType); |
| | | 144 | | } |
| | 0 | 145 | | break; |
| | | 146 | | } |
| | 0 | 147 | | } |
| | | 148 | | |
| | 0 | 149 | | if (result is null) |
| | 0 | 150 | | { |
| | 0 | 151 | | jsonTypeInfo = null; |
| | 0 | 152 | | typeDiscriminator = null; |
| | 0 | 153 | | return false; |
| | | 154 | | } |
| | | 155 | | else |
| | 0 | 156 | | { |
| | 0 | 157 | | jsonTypeInfo = result.JsonTypeInfo; |
| | 0 | 158 | | typeDiscriminator = result.TypeDiscriminator; |
| | 0 | 159 | | return true; |
| | | 160 | | } |
| | 0 | 161 | | } |
| | | 162 | | |
| | | 163 | | public bool TryGetDerivedJsonTypeInfo(object typeDiscriminator, [NotNullWhen(true)] out JsonTypeInfo? jsonTypeIn |
| | 0 | 164 | | { |
| | 0 | 165 | | Debug.Assert(typeDiscriminator is int or string); |
| | 0 | 166 | | Debug.Assert(UsesTypeDiscriminators); |
| | 0 | 167 | | Debug.Assert(_discriminatorIdtoType != null); |
| | | 168 | | |
| | 0 | 169 | | if (_discriminatorIdtoType.TryGetValue(typeDiscriminator, out DerivedJsonTypeInfo? result)) |
| | 0 | 170 | | { |
| | 0 | 171 | | Debug.Assert(typeDiscriminator.Equals(result.TypeDiscriminator)); |
| | 0 | 172 | | jsonTypeInfo = result.JsonTypeInfo; |
| | 0 | 173 | | return true; |
| | | 174 | | } |
| | | 175 | | |
| | 0 | 176 | | if (!IgnoreUnrecognizedTypeDiscriminators) |
| | 0 | 177 | | { |
| | 0 | 178 | | ThrowHelper.ThrowJsonException_UnrecognizedTypeDiscriminator(typeDiscriminator); |
| | | 179 | | } |
| | | 180 | | |
| | 0 | 181 | | jsonTypeInfo = null; |
| | 0 | 182 | | return false; |
| | 0 | 183 | | } |
| | | 184 | | |
| | | 185 | | public static bool IsSupportedPolymorphicBaseType(Type? type) => |
| | 0 | 186 | | type != null && |
| | 0 | 187 | | (type.IsClass || type.IsInterface) && |
| | 0 | 188 | | !type.IsSealed && |
| | 0 | 189 | | !type.IsGenericTypeDefinition && |
| | 0 | 190 | | !type.IsPointer && |
| | 0 | 191 | | type != JsonTypeInfo.ObjectType; |
| | | 192 | | |
| | | 193 | | public static bool IsSupportedDerivedType(Type baseType, Type? derivedType) => |
| | 0 | 194 | | baseType.IsAssignableFrom(derivedType) && !derivedType.IsGenericTypeDefinition; |
| | | 195 | | |
| | | 196 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", |
| | | 197 | | Justification = "The call to GetInterfaces will cross-reference results with interface types " + |
| | | 198 | | "already declared as derived types of the polymorphic base type.")] |
| | | 199 | | private DerivedJsonTypeInfo? CalculateNearestAncestor(Type type) |
| | 0 | 200 | | { |
| | 0 | 201 | | Debug.Assert(!type.IsAbstract); |
| | 0 | 202 | | Debug.Assert(BaseType.IsAssignableFrom(type)); |
| | 0 | 203 | | Debug.Assert(UnknownDerivedTypeHandling == JsonUnknownDerivedTypeHandling.FallBackToNearestAncestor); |
| | | 204 | | |
| | 0 | 205 | | if (type == BaseType) |
| | 0 | 206 | | { |
| | 0 | 207 | | return null; |
| | | 208 | | } |
| | | 209 | | |
| | 0 | 210 | | DerivedJsonTypeInfo? result = null; |
| | | 211 | | |
| | | 212 | | // First, walk up the class hierarchy for any supported types. |
| | 0 | 213 | | for (Type? candidate = type.BaseType; BaseType.IsAssignableFrom(candidate); candidate = candidate.BaseType) |
| | 0 | 214 | | { |
| | 0 | 215 | | Debug.Assert(candidate != null); |
| | | 216 | | |
| | 0 | 217 | | if (_typeToDiscriminatorId.TryGetValue(candidate, out result)) |
| | 0 | 218 | | { |
| | 0 | 219 | | break; |
| | | 220 | | } |
| | 0 | 221 | | } |
| | | 222 | | |
| | | 223 | | // Interface hierarchies admit the possibility of diamond ambiguities in type discriminators. |
| | | 224 | | // Examine all interface implementations and identify potential conflicts. |
| | 0 | 225 | | if (BaseType.IsInterface) |
| | 0 | 226 | | { |
| | 0 | 227 | | foreach (Type interfaceTy in type.GetInterfaces()) |
| | 0 | 228 | | { |
| | 0 | 229 | | if (interfaceTy != BaseType && BaseType.IsAssignableFrom(interfaceTy) && |
| | 0 | 230 | | _typeToDiscriminatorId.TryGetValue(interfaceTy, out DerivedJsonTypeInfo? interfaceResult) && |
| | 0 | 231 | | interfaceResult is not null) |
| | 0 | 232 | | { |
| | 0 | 233 | | if (result is null) |
| | 0 | 234 | | { |
| | 0 | 235 | | result = interfaceResult; |
| | 0 | 236 | | } |
| | | 237 | | else |
| | 0 | 238 | | { |
| | 0 | 239 | | ThrowHelper.ThrowNotSupportedException_RuntimeTypeDiamondAmbiguity(BaseType, type, result.Js |
| | | 240 | | } |
| | 0 | 241 | | } |
| | 0 | 242 | | } |
| | 0 | 243 | | } |
| | | 244 | | |
| | 0 | 245 | | return result; |
| | 0 | 246 | | } |
| | | 247 | | |
| | | 248 | | /// <summary> |
| | | 249 | | /// Walks the type hierarchy above the current type for any types that use polymorphic configuration. |
| | | 250 | | /// </summary> |
| | | 251 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", |
| | | 252 | | Justification = "The call to GetInterfaces will cross-reference results with interface types " + |
| | | 253 | | "already declared as derived types of the polymorphic base type.")] |
| | | 254 | | internal static JsonTypeInfo? FindNearestPolymorphicBaseType(JsonTypeInfo typeInfo) |
| | 0 | 255 | | { |
| | 0 | 256 | | Debug.Assert(typeInfo.IsConfigured); |
| | | 257 | | |
| | 0 | 258 | | if (typeInfo.PolymorphismOptions != null) |
| | 0 | 259 | | { |
| | | 260 | | // Type defines its own polymorphic configuration. |
| | 0 | 261 | | return null; |
| | | 262 | | } |
| | | 263 | | |
| | 0 | 264 | | JsonTypeInfo? matchingResult = null; |
| | | 265 | | |
| | | 266 | | // First, walk up the class hierarchy for any supported types. |
| | 0 | 267 | | for (Type? candidate = typeInfo.Type.BaseType; candidate != null; candidate = candidate.BaseType) |
| | 0 | 268 | | { |
| | 0 | 269 | | JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(candidate, typeInfo.Options); |
| | 0 | 270 | | if (candidateInfo?.PolymorphismOptions != null) |
| | 0 | 271 | | { |
| | | 272 | | // stop on the first ancestor that has a match |
| | 0 | 273 | | matchingResult = candidateInfo; |
| | 0 | 274 | | break; |
| | | 275 | | } |
| | 0 | 276 | | } |
| | | 277 | | |
| | | 278 | | // Now, walk the interface hierarchy for any polymorphic interface declarations. |
| | 0 | 279 | | foreach (Type interfaceType in typeInfo.Type.GetInterfaces()) |
| | 0 | 280 | | { |
| | 0 | 281 | | JsonTypeInfo? candidateInfo = ResolveAncestorTypeInfo(interfaceType, typeInfo.Options); |
| | 0 | 282 | | if (candidateInfo?.PolymorphismOptions != null) |
| | 0 | 283 | | { |
| | 0 | 284 | | if (matchingResult != null) |
| | 0 | 285 | | { |
| | | 286 | | // Resolve any conflicting matches. |
| | 0 | 287 | | if (matchingResult.Type.IsAssignableFrom(interfaceType)) |
| | 0 | 288 | | { |
| | | 289 | | // interface is more derived than previous match, replace it. |
| | 0 | 290 | | matchingResult = candidateInfo; |
| | 0 | 291 | | } |
| | 0 | 292 | | else if (interfaceType.IsAssignableFrom(matchingResult.Type)) |
| | 0 | 293 | | { |
| | | 294 | | // interface is less derived than previous match, keep the previous one. |
| | 0 | 295 | | continue; |
| | | 296 | | } |
| | | 297 | | else |
| | 0 | 298 | | { |
| | | 299 | | // Diamond ambiguity, do not report any ancestors. |
| | 0 | 300 | | return null; |
| | | 301 | | } |
| | 0 | 302 | | } |
| | | 303 | | else |
| | 0 | 304 | | { |
| | 0 | 305 | | matchingResult = candidateInfo; |
| | 0 | 306 | | } |
| | 0 | 307 | | } |
| | 0 | 308 | | } |
| | | 309 | | |
| | 0 | 310 | | return matchingResult; |
| | | 311 | | |
| | | 312 | | static JsonTypeInfo? ResolveAncestorTypeInfo(Type type, JsonSerializerOptions options) |
| | 0 | 313 | | { |
| | | 314 | | try |
| | 0 | 315 | | { |
| | 0 | 316 | | return options.GetTypeInfoInternal(type, ensureNotNull: null); |
| | | 317 | | } |
| | 0 | 318 | | catch |
| | 0 | 319 | | { |
| | | 320 | | // The resolver produced an exception when resolving the ancestor type. |
| | | 321 | | // Eat the exception and report no result instead. |
| | 0 | 322 | | return null; |
| | | 323 | | } |
| | 0 | 324 | | } |
| | 0 | 325 | | } |
| | | 326 | | |
| | | 327 | | /// <summary> |
| | | 328 | | /// JsonTypeInfo result holder for a derived type. |
| | | 329 | | /// </summary> |
| | | 330 | | private sealed class DerivedJsonTypeInfo |
| | | 331 | | { |
| | 0 | 332 | | public DerivedJsonTypeInfo(object? typeDiscriminator, JsonTypeInfo derivedTypeInfo) |
| | 0 | 333 | | { |
| | 0 | 334 | | Debug.Assert(typeDiscriminator is null or int or string); |
| | | 335 | | |
| | 0 | 336 | | TypeDiscriminator = typeDiscriminator; |
| | 0 | 337 | | JsonTypeInfo = derivedTypeInfo; |
| | 0 | 338 | | } |
| | | 339 | | |
| | 0 | 340 | | public object? TypeDiscriminator { get; } |
| | 0 | 341 | | public JsonTypeInfo JsonTypeInfo { get; } |
| | | 342 | | } |
| | | 343 | | } |
| | | 344 | | } |