| | | 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.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.Reflection; |
| | | 8 | | using System.Runtime.CompilerServices; |
| | | 9 | | using System.Runtime.ExceptionServices; |
| | | 10 | | using System.Text.Json.Serialization; |
| | | 11 | | |
| | | 12 | | namespace System.Text.Json.Reflection |
| | | 13 | | { |
| | | 14 | | internal static partial class ReflectionExtensions |
| | | 15 | | { |
| | | 16 | | /// <summary> |
| | | 17 | | /// Returns <see langword="true" /> when the given type is of type <see cref="Nullable{T}"/>. |
| | | 18 | | /// </summary> |
| | | 19 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 20 | | public static bool IsNullableOfT(this Type type) => |
| | 11488 | 21 | | type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); |
| | | 22 | | |
| | 1998 | 23 | | public static bool IsNullableType(this Type type) => !type.IsValueType || IsNullableOfT(type); |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Returns <see langword="true" /> when the given type is assignable from <paramref name="from"/> including sup |
| | | 27 | | /// when <paramref name="from"/> is <see cref="Nullable{T}"/> by using the {T} generic parameter for <paramref n |
| | | 28 | | /// </summary> |
| | | 29 | | public static bool IsAssignableFromInternal(this Type type, Type from) |
| | 4147 | 30 | | { |
| | 4147 | 31 | | if (IsNullableOfT(from) && type.IsInterface) |
| | 0 | 32 | | { |
| | 0 | 33 | | return type.IsAssignableFrom(from.GetGenericArguments()[0]); |
| | | 34 | | } |
| | | 35 | | |
| | 4147 | 36 | | return type.IsAssignableFrom(from); |
| | 4147 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// Returns <see langword="true" /> when either type is assignable to the other. |
| | | 41 | | /// </summary> |
| | | 42 | | public static bool IsInSubtypeRelationshipWith(this Type type, Type other) => |
| | 4147 | 43 | | type.IsAssignableFromInternal(other) || other.IsAssignableFromInternal(type); |
| | | 44 | | |
| | | 45 | | private static bool HasJsonConstructorAttribute(ConstructorInfo constructorInfo) |
| | 829 | 46 | | => constructorInfo.IsDefined(typeof(JsonConstructorAttribute), inherit: false); |
| | | 47 | | |
| | | 48 | | public static bool HasRequiredMemberAttribute(this MemberInfo memberInfo) |
| | 496 | 49 | | { |
| | | 50 | | // For compiler related attributes we should only look at full type name rather than trying to do something |
| | | 51 | | // I.e. library is targeting netstandard2.0 with polyfilled attributes and is being consumed by an app targe |
| | 496 | 52 | | return memberInfo.HasCustomAttributeWithName("System.Runtime.CompilerServices.RequiredMemberAttribute", inhe |
| | 496 | 53 | | } |
| | | 54 | | |
| | | 55 | | public static bool HasSetsRequiredMembersAttribute(this MemberInfo memberInfo) |
| | 496 | 56 | | { |
| | | 57 | | // See comment for HasRequiredMemberAttribute for why we need to always only look at full name |
| | 496 | 58 | | return memberInfo.HasCustomAttributeWithName("System.Diagnostics.CodeAnalysis.SetsRequiredMembersAttribute", |
| | 496 | 59 | | } |
| | | 60 | | |
| | | 61 | | private static bool HasCustomAttributeWithName(this MemberInfo memberInfo, string fullName, bool inherit) |
| | 992 | 62 | | { |
| | 2976 | 63 | | foreach (object attribute in memberInfo.GetCustomAttributes(inherit)) |
| | 0 | 64 | | { |
| | 0 | 65 | | if (attribute.GetType().FullName == fullName) |
| | 0 | 66 | | { |
| | 0 | 67 | | return true; |
| | | 68 | | } |
| | 0 | 69 | | } |
| | | 70 | | |
| | 992 | 71 | | return false; |
| | 992 | 72 | | } |
| | | 73 | | |
| | | 74 | | public static TAttribute? GetUniqueCustomAttribute<TAttribute>(this MemberInfo memberInfo, bool inherit) |
| | | 75 | | where TAttribute : Attribute |
| | 20556 | 76 | | { |
| | 20556 | 77 | | object[] attributes = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit); |
| | | 78 | | |
| | 20556 | 79 | | if (attributes.Length == 0) |
| | 20470 | 80 | | { |
| | 20470 | 81 | | return null; |
| | | 82 | | } |
| | | 83 | | |
| | 86 | 84 | | if (attributes.Length == 1) |
| | 86 | 85 | | { |
| | 86 | 86 | | return (TAttribute)attributes[0]; |
| | | 87 | | } |
| | | 88 | | |
| | 0 | 89 | | ThrowHelper.ThrowInvalidOperationException_SerializationDuplicateAttribute(typeof(TAttribute), memberInfo); |
| | | 90 | | return null; |
| | 20556 | 91 | | } |
| | | 92 | | |
| | | 93 | | /// <summary> |
| | | 94 | | /// Polyfill for BindingFlags.DoNotWrapExceptions |
| | | 95 | | /// </summary> |
| | | 96 | | public static object? CreateInstanceNoWrapExceptions( |
| | | 97 | | [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTyp |
| | | 98 | | Type[] parameterTypes, |
| | | 99 | | object?[] parameters) |
| | 681 | 100 | | { |
| | 681 | 101 | | ConstructorInfo ctorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.I |
| | | 102 | | #if NET |
| | 681 | 103 | | return ctorInfo.Invoke(BindingFlags.DoNotWrapExceptions, null, parameters, null); |
| | | 104 | | #else |
| | | 105 | | try |
| | | 106 | | { |
| | | 107 | | return ctorInfo.Invoke(parameters); |
| | | 108 | | } |
| | | 109 | | catch (TargetInvocationException ex) when (ex.InnerException is not null) |
| | | 110 | | { |
| | | 111 | | ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); |
| | | 112 | | throw; // unreachable |
| | | 113 | | } |
| | | 114 | | #endif |
| | 681 | 115 | | } |
| | | 116 | | |
| | | 117 | | /// <summary> |
| | | 118 | | /// Invokes <paramref name="methodInfo"/> without wrapping any exception thrown by the |
| | | 119 | | /// target method in a <see cref="TargetInvocationException"/>. This matches the behavior of |
| | | 120 | | /// the Reflection.Emit-based accessor, which emits direct calls into user code. |
| | | 121 | | /// </summary> |
| | | 122 | | public static object? InvokeNoWrapExceptions(this MethodInfo methodInfo, object? obj, object?[]? parameters) |
| | | 123 | | { |
| | | 124 | | #if NET |
| | | 125 | | return methodInfo.Invoke(obj, BindingFlags.DoNotWrapExceptions, binder: null, parameters, culture: null); |
| | | 126 | | #else |
| | | 127 | | try |
| | | 128 | | { |
| | | 129 | | return methodInfo.Invoke(obj, parameters); |
| | | 130 | | } |
| | | 131 | | catch (TargetInvocationException ex) when (ex.InnerException is not null) |
| | | 132 | | { |
| | | 133 | | ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); |
| | | 134 | | throw; // unreachable |
| | | 135 | | } |
| | | 136 | | #endif |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Invokes <paramref name="constructorInfo"/> without wrapping any exception thrown by the |
| | | 141 | | /// constructor in a <see cref="TargetInvocationException"/>. This matches the behavior of |
| | | 142 | | /// the Reflection.Emit-based accessor, which emits direct calls into user code. |
| | | 143 | | /// </summary> |
| | | 144 | | public static object InvokeNoWrapExceptions(this ConstructorInfo constructorInfo, object?[]? parameters) |
| | | 145 | | { |
| | | 146 | | #if NET |
| | | 147 | | return constructorInfo.Invoke(BindingFlags.DoNotWrapExceptions, binder: null, parameters, culture: null); |
| | | 148 | | #else |
| | | 149 | | try |
| | | 150 | | { |
| | | 151 | | return constructorInfo.Invoke(parameters); |
| | | 152 | | } |
| | | 153 | | catch (TargetInvocationException ex) when (ex.InnerException is not null) |
| | | 154 | | { |
| | | 155 | | ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); |
| | | 156 | | throw; // unreachable |
| | | 157 | | } |
| | | 158 | | #endif |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | /// <summary> |
| | | 162 | | /// Enumerates every ancestor of <paramref name="type"/> whose generic type definition |
| | | 163 | | /// matches <paramref name="baseTypeDefinition"/>. For interface bases this yields every |
| | | 164 | | /// implementing instantiation (a type can implement the same interface definition with |
| | | 165 | | /// different type arguments); for class bases it yields at most the first match found |
| | | 166 | | /// while walking the base-type chain (only one such instantiation is reachable). |
| | | 167 | | /// |
| | | 168 | | /// IMPORTANT: This implementation mirrors |
| | | 169 | | /// <c>System.Text.Json.SourceGeneration.RoslynExtensions.GetCompatibleGenericBaseTypes</c> |
| | | 170 | | /// in gen/Helpers/RoslynExtensions.cs. Any change to the enumeration order or matching |
| | | 171 | | /// rules MUST be applied on both sides to keep reflection and source-gen behaviour in sync. |
| | | 172 | | /// </summary> |
| | | 173 | | [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", |
| | | 174 | | Justification = "The derived type was supplied via [JsonDerivedType] by the user, so its interface " + |
| | | 175 | | "metadata is rooted at the attribute usage site and survives trimming. Callers are " + |
| | | 176 | | "additionally annotated [RequiresUnreferencedCode] to flow this requirement outward.")] |
| | | 177 | | public static IEnumerable<Type> GetMatchingGenericBaseTypes(this Type type, Type baseTypeDefinition) |
| | 0 | 178 | | { |
| | 0 | 179 | | Debug.Assert(baseTypeDefinition.IsGenericTypeDefinition); |
| | | 180 | | |
| | 0 | 181 | | if (baseTypeDefinition.IsInterface) |
| | 0 | 182 | | { |
| | 0 | 183 | | foreach (Type iface in type.GetInterfaces()) |
| | 0 | 184 | | { |
| | 0 | 185 | | if (iface.IsGenericType && iface.GetGenericTypeDefinition() == baseTypeDefinition) |
| | 0 | 186 | | { |
| | 0 | 187 | | yield return iface; |
| | 0 | 188 | | } |
| | 0 | 189 | | } |
| | | 190 | | |
| | | 191 | | // Note: do NOT yield break here. Type.GetInterfaces() does not include `type` |
| | | 192 | | // itself, so when `type` IS the interface we're looking for, the fall-through |
| | | 193 | | // to the BaseType walk below picks it up via the self-check on the first |
| | | 194 | | // iteration (Type.BaseType returns null for interfaces, so the loop |
| | | 195 | | // terminates immediately). |
| | 0 | 196 | | } |
| | | 197 | | |
| | 0 | 198 | | for (Type? current = type; current is not null; current = current.BaseType) |
| | 0 | 199 | | { |
| | 0 | 200 | | if (current.IsGenericType && current.GetGenericTypeDefinition() == baseTypeDefinition) |
| | 0 | 201 | | { |
| | 0 | 202 | | yield return current; |
| | 0 | 203 | | yield break; |
| | | 204 | | } |
| | 0 | 205 | | } |
| | 0 | 206 | | } |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Attempts to unify a <paramref name="pattern"/> type (which may contain generic |
| | | 210 | | /// parameter references) with a <paramref name="target"/> type, recording bindings in |
| | | 211 | | /// <paramref name="substitution"/>. Returns <see langword="true"/> if the pattern matches |
| | | 212 | | /// the target under some extension of the current substitution. |
| | | 213 | | /// |
| | | 214 | | /// IMPORTANT: This implementation MIRRORS |
| | | 215 | | /// <c>System.Text.Json.SourceGeneration.RoslynExtensions.TryUnifyWith</c> in |
| | | 216 | | /// gen/Helpers/RoslynExtensions.cs. Any structural change (e.g. new type-kind handling, |
| | | 217 | | /// refined array/pointer rules) MUST be applied on both sides to keep reflection and |
| | | 218 | | /// source-gen behaviour in sync. The two implementations are exercised by: |
| | | 219 | | /// * tests/.../PolymorphicTests.CustomTypeHierarchies.cs (reflection) |
| | | 220 | | /// * tests/.../JsonSourceGeneratorDiagnosticsTests.cs (source-gen) |
| | | 221 | | /// |
| | | 222 | | /// Known intentional asymmetries with the source-gen mirror: |
| | | 223 | | /// * This implementation distinguishes SZ arrays (<c>T[]</c>) from rank-1 |
| | | 224 | | /// multi-dimensional arrays (<c>T[*]</c>) via <c>Type.IsSZArray</c> on .NET. Roslyn |
| | | 225 | | /// surfaces both as <c>IArrayTypeSymbol</c> with <c>Rank == 1</c>, and C# |
| | | 226 | | /// <c>typeof()</c> attribute syntax only produces SZ arrays, so the source-gen |
| | | 227 | | /// mirror has no equivalent check. |
| | | 228 | | /// * This implementation has a branch for <c>Type.IsByRef</c>; Roslyn never surfaces |
| | | 229 | | /// ref types as generic arguments, so the source-gen mirror has no equivalent. |
| | | 230 | | /// </summary> |
| | | 231 | | public static bool TryUnifyWith(this Type pattern, Type target, IDictionary<Type, Type> substitution) |
| | 0 | 232 | | { |
| | 0 | 233 | | if (pattern.IsGenericParameter) |
| | 0 | 234 | | { |
| | 0 | 235 | | if (substitution.TryGetValue(pattern, out Type? existing)) |
| | 0 | 236 | | { |
| | 0 | 237 | | return existing == target; |
| | | 238 | | } |
| | | 239 | | |
| | 0 | 240 | | substitution[pattern] = target; |
| | 0 | 241 | | return true; |
| | | 242 | | } |
| | | 243 | | |
| | 0 | 244 | | if (pattern.IsArray) |
| | 0 | 245 | | { |
| | 0 | 246 | | if (!target.IsArray) |
| | 0 | 247 | | { |
| | 0 | 248 | | return false; |
| | | 249 | | } |
| | | 250 | | |
| | 0 | 251 | | if (pattern.GetArrayRank() != target.GetArrayRank()) |
| | 0 | 252 | | { |
| | 0 | 253 | | return false; |
| | | 254 | | } |
| | | 255 | | |
| | | 256 | | // Distinguish single-dim zero-based arrays (T[]) from non-SZ rank-1 arrays (T[*]). |
| | | 257 | | #if NET |
| | 0 | 258 | | if (pattern.IsSZArray != target.IsSZArray) |
| | 0 | 259 | | { |
| | 0 | 260 | | return false; |
| | | 261 | | } |
| | | 262 | | #endif |
| | | 263 | | |
| | 0 | 264 | | return pattern.GetElementType()!.TryUnifyWith(target.GetElementType()!, substitution); |
| | | 265 | | } |
| | | 266 | | |
| | 0 | 267 | | if (pattern.IsPointer) |
| | 0 | 268 | | { |
| | 0 | 269 | | if (!target.IsPointer) |
| | 0 | 270 | | { |
| | 0 | 271 | | return false; |
| | | 272 | | } |
| | | 273 | | |
| | 0 | 274 | | return pattern.GetElementType()!.TryUnifyWith(target.GetElementType()!, substitution); |
| | | 275 | | } |
| | | 276 | | |
| | 0 | 277 | | if (pattern.IsByRef) |
| | 0 | 278 | | { |
| | 0 | 279 | | if (!target.IsByRef) |
| | 0 | 280 | | { |
| | 0 | 281 | | return false; |
| | | 282 | | } |
| | | 283 | | |
| | 0 | 284 | | return pattern.GetElementType()!.TryUnifyWith(target.GetElementType()!, substitution); |
| | | 285 | | } |
| | | 286 | | |
| | 0 | 287 | | if (pattern.IsGenericType) |
| | 0 | 288 | | { |
| | 0 | 289 | | if (!target.IsGenericType || pattern.GetGenericTypeDefinition() != target.GetGenericTypeDefinition()) |
| | 0 | 290 | | { |
| | 0 | 291 | | return false; |
| | | 292 | | } |
| | | 293 | | |
| | 0 | 294 | | Type[] patternArgs = pattern.GetGenericArguments(); |
| | 0 | 295 | | Type[] targetArgs = target.GetGenericArguments(); |
| | 0 | 296 | | if (patternArgs.Length != targetArgs.Length) |
| | 0 | 297 | | { |
| | 0 | 298 | | return false; |
| | | 299 | | } |
| | | 300 | | |
| | 0 | 301 | | for (int i = 0; i < patternArgs.Length; i++) |
| | 0 | 302 | | { |
| | 0 | 303 | | if (!patternArgs[i].TryUnifyWith(targetArgs[i], substitution)) |
| | 0 | 304 | | { |
| | 0 | 305 | | return false; |
| | | 306 | | } |
| | 0 | 307 | | } |
| | | 308 | | |
| | 0 | 309 | | return true; |
| | | 310 | | } |
| | | 311 | | |
| | 0 | 312 | | return pattern == target; |
| | 0 | 313 | | } |
| | | 314 | | |
| | | 315 | | // The following is a line-by-line port of the Roslyn C# compiler's own accessibility comparison — the |
| | | 316 | | // logic it runs to report the "inconsistent accessibility" diagnostics (CS0050/CS0060 and friends). An |
| | | 317 | | // inferred closed-hierarchy derived type is kept only when it is at least as visible as the base it is |
| | | 318 | | // registered under; otherwise there are call sites that can reference the base but not the derived type. |
| | | 319 | | // Rather than invent an accessibility metric (which would risk drifting from the language as new |
| | | 320 | | // modifiers are added), we reproduce the compiler's algorithm verbatim, using its terminology, so it |
| | | 321 | | // tracks C# accessibility as it evolves. The reflection resolver has no Roslyn Compilation, so the |
| | | 322 | | // algorithm is reproduced here over System.Type; gen/Helpers/RoslynExtensions.cs mirrors it over ISymbol. |
| | | 323 | | // |
| | | 324 | | // Ported from dotnet/roslyn @ 121e7dc868d26be12b9c3fb52b7b9d2ae41a1ac2: |
| | | 325 | | // IsAtLeastAsVisibleAs / FindTypeLessVisibleThan / IsAsRestrictive: |
| | | 326 | | // https://github.com/dotnet/roslyn/blob/121e7dc868d26be12b9c3fb52b7b9d2ae41a1ac2/src/Compilers/CSharp/Porta |
| | | 327 | | // IsAccessibleViaInheritance: |
| | | 328 | | // https://github.com/dotnet/roslyn/blob/121e7dc868d26be12b9c3fb52b7b9d2ae41a1ac2/src/Compilers/CSharp/Porta |
| | | 329 | | // HasInternalAccessTo: |
| | | 330 | | // https://github.com/dotnet/roslyn/blob/121e7dc868d26be12b9c3fb52b7b9d2ae41a1ac2/src/Compilers/CSharp/Porta |
| | | 331 | | |
| | | 332 | | /// <summary> |
| | | 333 | | /// Determines whether <paramref name="type"/> is at least as visible as <paramref name="sym"/>. Port of |
| | | 334 | | /// Roslyn's <c>TypeSymbolExtensions.IsAtLeastAsVisibleAs</c>; because a closed hierarchy relates two |
| | | 335 | | /// named types, the compound-type traversal (<c>FindTypeLessVisibleThan</c>/<c>Symbol.VisitType</c>) |
| | | 336 | | /// reduces to the single <c>IsAsRestrictive</c> check. |
| | | 337 | | /// </summary> |
| | | 338 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 339 | | public static bool IsAtLeastAsVisibleAs(this Type type, Type sym) |
| | 0 | 340 | | { |
| | 0 | 341 | | return IsAsRestrictive(type, sym); |
| | | 342 | | |
| | | 343 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 344 | | static bool IsAsRestrictive(Type s1, Type sym2) |
| | 0 | 345 | | { |
| | 0 | 346 | | Accessibility acc1 = GetDeclaredAccessibility(s1); |
| | | 347 | | |
| | 0 | 348 | | if (acc1 == Accessibility.Public) |
| | 0 | 349 | | { |
| | 0 | 350 | | return true; |
| | | 351 | | } |
| | | 352 | | |
| | 0 | 353 | | for (Type? s2 = sym2; s2 is not null; s2 = s2.DeclaringType) |
| | 0 | 354 | | { |
| | 0 | 355 | | Accessibility acc2 = GetDeclaredAccessibility(s2); |
| | | 356 | | |
| | 0 | 357 | | switch (acc1) |
| | | 358 | | { |
| | | 359 | | case Accessibility.Internal: |
| | | 360 | | // If s2 is private or internal, and is in an assembly that gives s1's assembly internal |
| | | 361 | | // access, then this is at least as restrictive as s1's internal. |
| | 0 | 362 | | if (acc2 is Accessibility.Private or Accessibility.Internal or Accessibility.ProtectedAndInt |
| | 0 | 363 | | HasInternalAccessTo(s2.Assembly, s1.Assembly)) |
| | 0 | 364 | | { |
| | 0 | 365 | | return true; |
| | | 366 | | } |
| | | 367 | | |
| | 0 | 368 | | break; |
| | | 369 | | |
| | | 370 | | case Accessibility.ProtectedAndInternal: |
| | | 371 | | // Since s1 is private protected, s2 must be more restrictive than both internal and |
| | | 372 | | // protected. Do the "internal" test first (as above); if it passes, fall through to the |
| | | 373 | | // "protected" test. |
| | 0 | 374 | | if (acc2 is Accessibility.Private or Accessibility.Internal or Accessibility.ProtectedAndInt |
| | 0 | 375 | | HasInternalAccessTo(s2.Assembly, s1.Assembly)) |
| | 0 | 376 | | { |
| | 0 | 377 | | goto case Accessibility.Protected; |
| | | 378 | | } |
| | | 379 | | |
| | 0 | 380 | | break; |
| | | 381 | | |
| | | 382 | | case Accessibility.Protected: |
| | 0 | 383 | | { |
| | 0 | 384 | | Type? parent1 = s1.DeclaringType; |
| | | 385 | | |
| | 0 | 386 | | if (parent1 is null) |
| | 0 | 387 | | { |
| | | 388 | | // not helpful |
| | 0 | 389 | | } |
| | 0 | 390 | | else if (acc2 == Accessibility.Private) |
| | 0 | 391 | | { |
| | | 392 | | // if s2 is private and within s1's parent or within a subclass of s1's parent, |
| | | 393 | | // then this is at least as restrictive as s1's protected. |
| | 0 | 394 | | for (Type? parent2 = s2.DeclaringType; parent2 is not null; parent2 = parent2.DeclaringT |
| | 0 | 395 | | { |
| | 0 | 396 | | if (IsAccessibleViaInheritance(parent1, parent2)) |
| | 0 | 397 | | { |
| | 0 | 398 | | return true; |
| | | 399 | | } |
| | 0 | 400 | | } |
| | 0 | 401 | | } |
| | 0 | 402 | | else if (acc2 is Accessibility.Protected or Accessibility.ProtectedAndInternal) |
| | 0 | 403 | | { |
| | | 404 | | // if s2 is protected, and its parent is a subclass of (or the same as) s1's |
| | | 405 | | // parent, then this is at least as restrictive as s1's protected. |
| | 0 | 406 | | Type? parent2 = s2.DeclaringType; |
| | 0 | 407 | | if (parent2 is not null && IsAccessibleViaInheritance(parent1, parent2)) |
| | 0 | 408 | | { |
| | 0 | 409 | | return true; |
| | | 410 | | } |
| | 0 | 411 | | } |
| | | 412 | | |
| | 0 | 413 | | break; |
| | | 414 | | } |
| | | 415 | | |
| | | 416 | | case Accessibility.ProtectedOrInternal: |
| | 0 | 417 | | { |
| | 0 | 418 | | Type? parent1 = s1.DeclaringType; |
| | | 419 | | |
| | 0 | 420 | | if (parent1 is null) |
| | 0 | 421 | | { |
| | 0 | 422 | | break; |
| | | 423 | | } |
| | | 424 | | |
| | 0 | 425 | | switch (acc2) |
| | | 426 | | { |
| | | 427 | | case Accessibility.Private: |
| | | 428 | | // if s2 is private and within a subclass of s1's parent, or within the same |
| | | 429 | | // assembly as s1, then this is at least as restrictive as s1's protected internal. |
| | 0 | 430 | | if (HasInternalAccessTo(s2.Assembly, s1.Assembly)) |
| | 0 | 431 | | { |
| | 0 | 432 | | return true; |
| | | 433 | | } |
| | | 434 | | |
| | 0 | 435 | | for (Type? parent2 = s2.DeclaringType; parent2 is not null; parent2 = parent2.Declar |
| | 0 | 436 | | { |
| | 0 | 437 | | if (IsAccessibleViaInheritance(parent1, parent2)) |
| | 0 | 438 | | { |
| | 0 | 439 | | return true; |
| | | 440 | | } |
| | 0 | 441 | | } |
| | | 442 | | |
| | 0 | 443 | | break; |
| | | 444 | | |
| | | 445 | | case Accessibility.Internal: |
| | | 446 | | // If s2 is in an assembly that gives s1's assembly internal access, then this |
| | | 447 | | // is more restrictive than s1's protected internal. |
| | 0 | 448 | | if (HasInternalAccessTo(s2.Assembly, s1.Assembly)) |
| | 0 | 449 | | { |
| | 0 | 450 | | return true; |
| | | 451 | | } |
| | | 452 | | |
| | 0 | 453 | | break; |
| | | 454 | | |
| | | 455 | | case Accessibility.Protected: |
| | | 456 | | // if s2 is protected, and its parent is a subclass of (or the same as) s1's |
| | | 457 | | // parent, then this is at least as restrictive as s1's protected internal. |
| | 0 | 458 | | if (s2.DeclaringType is Type protectedParent2 && IsAccessibleViaInheritance(parent1, |
| | 0 | 459 | | { |
| | 0 | 460 | | return true; |
| | | 461 | | } |
| | | 462 | | |
| | 0 | 463 | | break; |
| | | 464 | | |
| | | 465 | | case Accessibility.ProtectedAndInternal: |
| | | 466 | | // if s2 is private protected, and its parent is a subclass of (or the same as) |
| | | 467 | | // s1's parent, or it is in the same assembly as s1, then this is at least as |
| | | 468 | | // restrictive as s1's protected internal. |
| | 0 | 469 | | if (HasInternalAccessTo(s2.Assembly, s1.Assembly) || |
| | 0 | 470 | | (s2.DeclaringType is Type privateProtectedParent2 && IsAccessibleViaInheritance( |
| | 0 | 471 | | { |
| | 0 | 472 | | return true; |
| | | 473 | | } |
| | | 474 | | |
| | 0 | 475 | | break; |
| | | 476 | | |
| | | 477 | | case Accessibility.ProtectedOrInternal: |
| | | 478 | | // if s2 is protected internal, and its parent is a subclass of (or the same as) |
| | | 479 | | // s1's parent, and it is in the same assembly as s1, then this is at least as |
| | | 480 | | // restrictive as s1's protected internal. |
| | 0 | 481 | | if (HasInternalAccessTo(s2.Assembly, s1.Assembly) && |
| | 0 | 482 | | s2.DeclaringType is Type protectedOrInternalParent2 && IsAccessibleViaInheritanc |
| | 0 | 483 | | { |
| | 0 | 484 | | return true; |
| | | 485 | | } |
| | | 486 | | |
| | 0 | 487 | | break; |
| | | 488 | | } |
| | | 489 | | |
| | 0 | 490 | | break; |
| | | 491 | | } |
| | | 492 | | |
| | | 493 | | case Accessibility.Private: |
| | 0 | 494 | | if (acc2 == Accessibility.Private) |
| | 0 | 495 | | { |
| | | 496 | | // if s2 is private, and it is within s1's parent, then this is at least as |
| | | 497 | | // restrictive as s1's private. |
| | 0 | 498 | | Type? parent1 = s1.DeclaringType; |
| | | 499 | | |
| | 0 | 500 | | if (parent1 is null) |
| | 0 | 501 | | { |
| | 0 | 502 | | break; |
| | | 503 | | } |
| | | 504 | | |
| | 0 | 505 | | Type parent1OriginalDefinition = OriginalDefinition(parent1); |
| | 0 | 506 | | for (Type? parent2 = s2.DeclaringType; parent2 is not null; parent2 = parent2.DeclaringT |
| | 0 | 507 | | { |
| | 0 | 508 | | if (ReferenceEquals(OriginalDefinition(parent2), parent1OriginalDefinition)) |
| | 0 | 509 | | { |
| | 0 | 510 | | return true; |
| | | 511 | | } |
| | 0 | 512 | | } |
| | 0 | 513 | | } |
| | | 514 | | |
| | 0 | 515 | | break; |
| | | 516 | | } |
| | 0 | 517 | | } |
| | | 518 | | |
| | 0 | 519 | | return false; |
| | 0 | 520 | | } |
| | | 521 | | |
| | | 522 | | [RequiresUnreferencedCode(JsonSerializer.SerializationUnreferencedCodeMessage)] |
| | | 523 | | static bool IsAccessibleViaInheritance(Type superType, Type subType) |
| | 0 | 524 | | { |
| | 0 | 525 | | Type originalSuperType = OriginalDefinition(superType); |
| | 0 | 526 | | for (Type? current = subType; current is not null; current = current.BaseType) |
| | 0 | 527 | | { |
| | 0 | 528 | | if (ReferenceEquals(OriginalDefinition(current), originalSuperType)) |
| | 0 | 529 | | { |
| | 0 | 530 | | return true; |
| | | 531 | | } |
| | 0 | 532 | | } |
| | | 533 | | |
| | 0 | 534 | | if (originalSuperType.IsInterface) |
| | 0 | 535 | | { |
| | 0 | 536 | | foreach (Type current in subType.GetInterfaces()) |
| | 0 | 537 | | { |
| | 0 | 538 | | if (ReferenceEquals(OriginalDefinition(current), originalSuperType)) |
| | 0 | 539 | | { |
| | 0 | 540 | | return true; |
| | | 541 | | } |
| | 0 | 542 | | } |
| | 0 | 543 | | } |
| | | 544 | | |
| | 0 | 545 | | return false; |
| | 0 | 546 | | } |
| | | 547 | | |
| | | 548 | | static bool HasInternalAccessTo(Assembly fromAssembly, Assembly toAssembly) |
| | 0 | 549 | | { |
| | 0 | 550 | | if (fromAssembly == toAssembly) |
| | 0 | 551 | | { |
| | 0 | 552 | | return true; |
| | | 553 | | } |
| | | 554 | | |
| | | 555 | | // Reflection analog of Roslyn's AreInternalsVisibleToThisAssembly. Closed hierarchies are compiled |
| | | 556 | | // into a single assembly, so this branch only matters for the general faithfulness of the port; the |
| | | 557 | | // friend assembly is matched by simple name (the runtime already enforced strong-name identity when |
| | | 558 | | // it loaded the types). |
| | 0 | 559 | | string? fromName = fromAssembly.GetName().Name; |
| | 0 | 560 | | foreach (CustomAttributeData attribute in toAssembly.GetCustomAttributesData()) |
| | 0 | 561 | | { |
| | 0 | 562 | | if (attribute.AttributeType == typeof(InternalsVisibleToAttribute) && |
| | 0 | 563 | | attribute.ConstructorArguments.Count > 0 && |
| | 0 | 564 | | attribute.ConstructorArguments[0].Value is string friendName) |
| | 0 | 565 | | { |
| | 0 | 566 | | int comma = friendName.IndexOf(','); |
| | 0 | 567 | | string friendSimpleName = comma < 0 ? friendName : friendName.Substring(0, comma); |
| | 0 | 568 | | if (string.Equals(friendSimpleName, fromName, StringComparison.OrdinalIgnoreCase)) |
| | 0 | 569 | | { |
| | 0 | 570 | | return true; |
| | | 571 | | } |
| | 0 | 572 | | } |
| | 0 | 573 | | } |
| | | 574 | | |
| | 0 | 575 | | return false; |
| | 0 | 576 | | } |
| | | 577 | | |
| | | 578 | | static Type OriginalDefinition(Type type) => |
| | 0 | 579 | | type.IsGenericType && !type.IsGenericTypeDefinition ? type.GetGenericTypeDefinition() : type; |
| | | 580 | | |
| | | 581 | | static Accessibility GetDeclaredAccessibility(Type type) |
| | 0 | 582 | | { |
| | 0 | 583 | | if (type.IsPublic || type.IsNestedPublic) |
| | 0 | 584 | | { |
| | 0 | 585 | | return Accessibility.Public; |
| | | 586 | | } |
| | | 587 | | |
| | 0 | 588 | | if (type.IsNestedFamORAssem) |
| | 0 | 589 | | { |
| | 0 | 590 | | return Accessibility.ProtectedOrInternal; // protected internal |
| | | 591 | | } |
| | | 592 | | |
| | 0 | 593 | | if (type.IsNestedFamily) |
| | 0 | 594 | | { |
| | 0 | 595 | | return Accessibility.Protected; |
| | | 596 | | } |
| | | 597 | | |
| | 0 | 598 | | if (type.IsNestedFamANDAssem) |
| | 0 | 599 | | { |
| | 0 | 600 | | return Accessibility.ProtectedAndInternal; // private protected |
| | | 601 | | } |
| | | 602 | | |
| | 0 | 603 | | if (type.IsNestedPrivate) |
| | 0 | 604 | | { |
| | 0 | 605 | | return Accessibility.Private; |
| | | 606 | | } |
| | | 607 | | |
| | | 608 | | // Top-level non-public (IsNotPublic) and nested assembly (IsNestedAssembly) are both 'internal'. |
| | 0 | 609 | | return Accessibility.Internal; |
| | 0 | 610 | | } |
| | 0 | 611 | | } |
| | | 612 | | |
| | | 613 | | /// <summary> |
| | | 614 | | /// Mirrors the members of Roslyn's <see cref="T:Microsoft.CodeAnalysis.Accessibility"/> that a C# type |
| | | 615 | | /// declaration can have, so the ported accessibility comparison uses the compiler's terminology. |
| | | 616 | | /// </summary> |
| | | 617 | | private enum Accessibility |
| | | 618 | | { |
| | | 619 | | Private, |
| | | 620 | | ProtectedAndInternal, // private protected |
| | | 621 | | Protected, |
| | | 622 | | Internal, |
| | | 623 | | ProtectedOrInternal, // protected internal |
| | | 624 | | Public, |
| | | 625 | | } |
| | | 626 | | } |
| | | 627 | | } |
| | | 628 | | |