public abstract partial class MetadataAssemblyResolver
{
protected MetadataAssemblyResolver() { }
- public abstract System.Reflection.Assembly Resolve(System.Reflection.MetadataLoadContext context, System.Reflection.AssemblyName assemblyName);
+ public abstract System.Reflection.Assembly? Resolve(System.Reflection.MetadataLoadContext context, System.Reflection.AssemblyName assemblyName);
}
public sealed partial class MetadataLoadContext : System.IDisposable
{
- public MetadataLoadContext(System.Reflection.MetadataAssemblyResolver resolver, string coreAssemblyName = null) { }
- public System.Reflection.Assembly CoreAssembly { get { throw null; } }
+ public MetadataLoadContext(System.Reflection.MetadataAssemblyResolver resolver, string? coreAssemblyName = null) { }
+ public System.Reflection.Assembly? CoreAssembly { get { throw null; } }
public void Dispose() { }
public System.Collections.Generic.IEnumerable<System.Reflection.Assembly> GetAssemblies() { throw null; }
public System.Reflection.Assembly LoadFromAssemblyName(System.Reflection.AssemblyName assemblyName) { throw null; }
public partial class PathAssemblyResolver : System.Reflection.MetadataAssemblyResolver
{
public PathAssemblyResolver(System.Collections.Generic.IEnumerable<string> assemblyPaths) { }
- public override System.Reflection.Assembly Resolve(System.Reflection.MetadataLoadContext context, System.Reflection.AssemblyName assemblyName) { throw null; }
+ public override System.Reflection.Assembly? Resolve(System.Reflection.MetadataLoadContext context, System.Reflection.AssemblyName assemblyName) { throw null; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configurations>netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System.Reflection.MetadataLoadContext.cs" />
<NoWarn>$(NoWarn);CS1573</NoWarn>
<!-- Only the netcoreapp version supports the new reflection apis (IsSZArray, etc.) -->
<Configurations>$(NetCoreAppCurrent)-Debug;$(NetCoreAppCurrent)-Release;netcoreapp3.0-Debug;netcoreapp3.0-Release;netstandard2.0-Debug;netstandard2.0-Release</Configurations>
+ <Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Compile Include="System\CoreRtBridge.cs" />
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Reflection;
using System.Reflection.TypeLoading;
using CultureInfo = System.Globalization.CultureInfo;
internal sealed partial class DefaultBinder : Binder
{
private readonly MetadataLoadContext _loader;
- private readonly Type _objectType;
+ private readonly Type? _objectType;
internal DefaultBinder(MetadataLoadContext loader)
{
// The most specific match will be selected.
//
public sealed override MethodBase BindToMethod(
- BindingFlags bindingAttr, MethodBase[] match, ref object[] args,
- ParameterModifier[] modifiers, CultureInfo cultureInfo, string[] names, out object state) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ BindingFlags bindingAttr, MethodBase[] match, ref object?[] args,
+ ParameterModifier[]? modifiers, CultureInfo? cultureInfo, string[]? names, out object state) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
// Given a set of fields that match the base criteria, select a field.
// if value is null then we have no way to select a field
- public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo cultureInfo) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? cultureInfo) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
// Given a set of methods that match the base criteria, select a method based upon an array of types.
// This method should return null if no method matches the criteria.
- public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
+ public sealed override MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers)
{
int i;
int j;
if (pCls == _objectType)
continue;
- Type type = types[j];
+ Type? type = types[j];
if (type.IsSignatureType())
{
if (!(candidates[i] is MethodInfo methodInfo))
}
// Given a set of properties that match the base criteria, select one.
- public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType,
- Type[] indexes, ParameterModifier[] modifiers)
+ public sealed override PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType,
+ Type[]? indexes, ParameterModifier[]? modifiers)
{
// Allow a null indexes array. But if it is not null, every element must be non-null as well.
if (indexes != null)
paramOrder[i] = i;
for (i = 1; i < curIdx; i++)
{
+ Debug.Assert(returnType != null);
int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType, returnType);
if (newMin == 0 && indexes != null)
newMin = FindMostSpecific(
// The default binder doesn't support any change type functionality.
// This is because the default is built into the low level invoke code.
- public override object ChangeType(object value, Type type, CultureInfo cultureInfo) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public override object ChangeType(object value, Type type, CultureInfo? cultureInfo) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override void ReorderArgumentArray(ref object[] args, object state) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override void ReorderArgumentArray(ref object?[] args, object state) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
- public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
+ public static MethodBase? ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[]? modifiers)
{
if (match == null)
throw new ArgumentNullException(nameof(match));
// Return any exact bindings that may exist. (This method is not defined on the
// Binder and is used by RuntimeType.)
- public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers)
+ public static PropertyInfo? ExactPropertyBinding(PropertyInfo[] match, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
if (match == null)
throw new ArgumentNullException(nameof(match));
- PropertyInfo bestMatch = null;
+ PropertyInfo? bestMatch = null;
int typesLength = (types != null) ? types.Length : 0;
for (int i = 0; i < match.Length; i++)
{
Type pCls = par[j].ParameterType;
// If the classes exactly match continue
- if (pCls != types[j])
+ if (pCls != types![j])
break;
}
if (j < typesLength)
return bestMatch;
}
- private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1,
- ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2,
- Type[] types, object[] args)
+ private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type? paramArrayType1,
+ ParameterInfo[] p2, int[] paramOrder2, Type? paramArrayType2,
+ Type[] types, object[]? args)
{
// A method using params is always less specific than one not using params
if (paramArrayType1 != null && paramArrayType2 == null) return 2;
{
if (c1.IsByRef && c2.IsByRef)
{
- c1 = c1.GetElementType();
- c2 = c2.GetElementType();
+ c1 = c1.GetElementType()!;
+ c2 = c2.GetElementType()!;
}
else if (c1.IsByRef)
{
if (c1.GetElementType() == c2)
return 2;
- c1 = c1.GetElementType();
+ c1 = c1.GetElementType()!;
}
else
{
if (c2.GetElementType() == c1)
return 1;
- c2 = c2.GetElementType();
+ c2 = c2.GetElementType()!;
}
}
}
}
- private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1,
- MethodBase m2, int[] paramOrder2, Type paramArrayType2,
- Type[] types, object[] args)
+ private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type? paramArrayType1,
+ MethodBase m2, int[] paramOrder2, Type? paramArrayType2,
+ Type[] types, object[]? args)
{
// Find the most specific method based on the parameters.
int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1,
if (CompareMethodSig(m1, m2))
{
// Determine the depth of the declaring types for both methods.
- int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType);
- int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType);
+ int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType!);
+ int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType!);
// The most derived method is the most specific one.
if (hierarchyDepth1 == hierarchyDepth2)
// Check to see if the fields have the same name.
if (cur1.Name == cur2.Name)
{
- int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
- int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
+ int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType!);
+ int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType!);
if (hierarchyDepth1 == hierarchyDepth2)
{
{
int depth = 0;
- Type currentType = t;
+ Type? currentType = t;
do
{
depth++;
return depth;
}
- internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches)
+ internal static MethodBase? FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches)
{
int deepestHierarchy = 0;
- MethodBase methWithDeepestHierarchy = null;
+ MethodBase? methWithDeepestHierarchy = null;
for (int i = 0; i < cMatches; i++)
{
// Calculate the depth of the hierarchy of the declaring type of the
// current method.
- int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType);
+ int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType!);
// The two methods have the same name, signature, and hierarchy depth.
// This can only happen if at least one is vararg or generic.
/// The MetadataLoadContext cannot consume assemblies from other MetadataLoadContexts or other type providers (such as the underlying runtime's own Reflection system.)
/// If a handler returns such an assembly, the MetadataLoadContext throws a FileLoadException.
/// </remarks>
- public abstract Assembly Resolve(MetadataLoadContext context, AssemblyName assemblyName);
+ public abstract Assembly? Resolve(MetadataLoadContext context, AssemblyName assemblyName);
}
}
/// <param name="coreAssemblyName">
/// The name of the assembly that contains the core types such as System.Object. Typically, this would be "mscorlib".
/// </param>
- public MetadataLoadContext(MetadataAssemblyResolver resolver, string coreAssemblyName = null)
+ public MetadataLoadContext(MetadataAssemblyResolver resolver, string? coreAssemblyName = null)
{
if (resolver == null)
throw new ArgumentNullException(nameof(resolver));
/// type, the necessary constructor or any of the parameter types of the constructor, the MetadataLoadContext will not throw. It will omit the pseudo-custom
/// attribute from the list of returned attributes.
/// </summary>
- public Assembly CoreAssembly
+ public Assembly? CoreAssembly
{
get
{
private static readonly string[] s_CoreNames = { "mscorlib", "System.Runtime", "netstandard" };
// Cache loaded coreAssembly and core types.
- internal RoAssembly TryGetCoreAssembly(string coreAssemblyName, out Exception e)
+ internal RoAssembly? TryGetCoreAssembly(string? coreAssemblyName, out Exception? e)
{
e = null;
Debug.Assert(_coreAssembly == null);
return _coreAssembly;
}
- private RoAssembly TryGetDefaultCoreAssembly(out Exception e)
+ private RoAssembly? TryGetDefaultCoreAssembly(out Exception? e)
{
foreach (string coreName in s_CoreNames)
{
RoAssemblyName roAssemblyName = new AssemblyName(coreName).ToRoAssemblyName();
- RoAssembly roAssembly = TryResolveAssembly(roAssemblyName, out e);
+ RoAssembly? roAssembly = TryResolveAssembly(roAssemblyName, out e);
// Stop on the first core assembly we find
if (roAssembly != null)
return null;
}
- private RoAssembly _coreAssembly = null;
+ private RoAssembly? _coreAssembly = null;
/// <summary>
/// Returns a lazily created and cached Type instance corresponding to the indicated core type. This method throws
internal RoType GetCoreType(CoreType coreType)
{
CoreTypes coreTypes = GetAllFoundCoreTypes();
- RoType t = TryGetCoreType(coreType);
- return t ?? throw coreTypes.GetException(coreType);
+ RoType? t = TryGetCoreType(coreType);
+ return t ?? throw coreTypes.GetException(coreType)!;
}
/// <summary>
/// if the core assembly name wasn't supplied, the core assembly could not be loaded for some reason or if the specified
/// type does not exist in the core assembly.
/// </summary>
- internal RoType TryGetCoreType(CoreType coreType)
+ internal RoType? TryGetCoreType(CoreType coreType)
{
CoreTypes coreTypes = GetAllFoundCoreTypes();
return coreTypes[coreType];
// one reason, we have to instance it per MetadataLoadContext.
//
internal Binder GetDefaultBinder() => _lazyDefaultBinder ?? (_lazyDefaultBinder = new DefaultBinder(this));
- private volatile Binder _lazyDefaultBinder;
+ private volatile Binder? _lazyDefaultBinder;
}
}
ConcurrentBag<IDisposable> disposables = _disposables;
if (disposables != null)
{
- _disposables = null;
+ _disposables = null!;
foreach (IDisposable disposable in disposables)
{
// Latch known constructors of pseudo-CustomAttribute types.
public sealed partial class MetadataLoadContext
{
- internal ConstructorInfo TryGetFieldOffsetCtor() => _lazyFieldOffset ?? (_lazyFieldOffset = TryGetConstructor(CoreType.FieldOffsetAttribute, CoreType.Int32));
- private volatile ConstructorInfo _lazyFieldOffset;
+ internal ConstructorInfo? TryGetFieldOffsetCtor() => _lazyFieldOffset ?? (_lazyFieldOffset = TryGetConstructor(CoreType.FieldOffsetAttribute, CoreType.Int32));
+ private volatile ConstructorInfo? _lazyFieldOffset;
- internal ConstructorInfo TryGetInCtor() => _lazyIn ?? (_lazyIn = TryGetConstructor(CoreType.InAttribute));
- private volatile ConstructorInfo _lazyIn;
+ internal ConstructorInfo? TryGetInCtor() => _lazyIn ?? (_lazyIn = TryGetConstructor(CoreType.InAttribute));
+ private volatile ConstructorInfo? _lazyIn;
- internal ConstructorInfo TryGetOutCtor() => _lazyOut ?? (_lazyOut = TryGetConstructor(CoreType.OutAttribute));
- private volatile ConstructorInfo _lazyOut;
+ internal ConstructorInfo? TryGetOutCtor() => _lazyOut ?? (_lazyOut = TryGetConstructor(CoreType.OutAttribute));
+ private volatile ConstructorInfo? _lazyOut;
- internal ConstructorInfo TryGetOptionalCtor() => _lazyOptional ?? (_lazyOptional = TryGetConstructor(CoreType.OptionalAttribute));
- private volatile ConstructorInfo _lazyOptional;
+ internal ConstructorInfo? TryGetOptionalCtor() => _lazyOptional ?? (_lazyOptional = TryGetConstructor(CoreType.OptionalAttribute));
+ private volatile ConstructorInfo? _lazyOptional;
- internal ConstructorInfo TryGetPreserveSigCtor() => _lazyPreserveSig ?? (_lazyPreserveSig = TryGetConstructor(CoreType.PreserveSigAttribute));
- private volatile ConstructorInfo _lazyPreserveSig;
+ internal ConstructorInfo? TryGetPreserveSigCtor() => _lazyPreserveSig ?? (_lazyPreserveSig = TryGetConstructor(CoreType.PreserveSigAttribute));
+ private volatile ConstructorInfo? _lazyPreserveSig;
- internal ConstructorInfo TryGetComImportCtor() => _lazyComImport ?? (_lazyComImport = TryGetConstructor(CoreType.ComImportAttribute));
- private volatile ConstructorInfo _lazyComImport;
+ internal ConstructorInfo? TryGetComImportCtor() => _lazyComImport ?? (_lazyComImport = TryGetConstructor(CoreType.ComImportAttribute));
+ private volatile ConstructorInfo? _lazyComImport;
- internal ConstructorInfo TryGetDllImportCtor() => _lazyDllImport ?? (_lazyDllImport = TryGetConstructor(CoreType.DllImportAttribute, CoreType.String));
- private volatile ConstructorInfo _lazyDllImport;
+ internal ConstructorInfo? TryGetDllImportCtor() => _lazyDllImport ?? (_lazyDllImport = TryGetConstructor(CoreType.DllImportAttribute, CoreType.String));
+ private volatile ConstructorInfo? _lazyDllImport;
- internal ConstructorInfo TryGetMarshalAsCtor() => _lazyMarshalAs ?? (_lazyMarshalAs = TryGetConstructor(CoreType.MarshalAsAttribute, CoreType.UnmanagedType));
- private volatile ConstructorInfo _lazyMarshalAs;
+ internal ConstructorInfo? TryGetMarshalAsCtor() => _lazyMarshalAs ?? (_lazyMarshalAs = TryGetConstructor(CoreType.MarshalAsAttribute, CoreType.UnmanagedType));
+ private volatile ConstructorInfo? _lazyMarshalAs;
- private ConstructorInfo TryGetConstructor(CoreType attributeCoreType, params CoreType[] parameterCoreTypes)
+ private ConstructorInfo? TryGetConstructor(CoreType attributeCoreType, params CoreType[] parameterCoreTypes)
{
int count = parameterCoreTypes.Length;
- Type attributeType = TryGetCoreType(attributeCoreType);
+ Type? attributeType = TryGetCoreType(attributeCoreType);
if (attributeType == null)
return null;
- Type[] parameterTypes = new Type[count];
+ Type?[] parameterTypes = new Type[count];
for (int i = 0; i < count; i++)
{
if ((parameterTypes[i] = TryGetCoreType(parameterCoreTypes[i])) == null)
}
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
- return attributeType.GetConstructor(bf, null, parameterTypes, null);
+ return attributeType.GetConstructor(bf, null, parameterTypes!, null);
}
}
}
private RoAssembly LoadFromStreamCore(Stream peStream)
{
PEReader peReader = new PEReader(peStream);
- PEReader peReaderToDispose = peReader; // Ensure peReader is disposed immediately if we throw an exception before we're done.
+ PEReader? peReaderToDispose = peReader; // Ensure peReader is disposed immediately if we throw an exception before we're done.
try
{
if (!peReader.HasMetadata)
byte[] pkt = defNameData.PublicKeyToken ?? Array.Empty<byte>();
if (pkt.Length == 0 && defNameData.PublicKey != null && defNameData.PublicKey.Length != 0)
{
- pkt = defNameData.PublicKey.ComputePublicKeyToken();
+ pkt = defNameData.PublicKey.ComputePublicKeyToken()!;
}
RoAssemblyName defName = new RoAssemblyName(defNameData.Name, defNameData.Version, defNameData.CultureName, pkt, defNameData.Flags);
{
Debug.Assert(refName != null);
- RoAssembly assembly = TryResolveAssembly(refName, out Exception e);
- return assembly ?? throw e;
+ RoAssembly? assembly = TryResolveAssembly(refName, out Exception? e);
+ return assembly ?? throw e!;
}
- internal RoAssembly TryResolveAssembly(RoAssemblyName refName, out Exception e)
+ internal RoAssembly? TryResolveAssembly(RoAssemblyName refName, out Exception? e)
{
e = null;
{
Debug.Assert(refName != null);
- if (_binds.TryGetValue(refName, out RoAssembly prior))
+ if (_binds.TryGetValue(refName, out RoAssembly? prior))
return prior;
RoAssembly assembly = TryFindAssemblyByCallingResolveHandler(refName);
{
Debug.Assert(refName != null);
- Assembly assembly = resolver?.Resolve(this, refName.ToAssemblyName());
+ Assembly? assembly = resolver?.Resolve(this, refName.ToAssemblyName());
if (assembly == null)
return new RoExceptionAssembly(new FileNotFoundException(SR.Format(SR.FileNotFoundAssembly, refName.FullName)));
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
if (file.Length == 0)
throw new ArgumentException(SR.Format(SR.Arg_InvalidPath, path), nameof(assemblyPaths));
- List<string> paths;
+ List<string>? paths;
if (!_fileToPaths.TryGetValue(file, out paths))
{
_fileToPaths.Add(file, paths = new List<string>());
}
}
- public override Assembly Resolve(MetadataLoadContext context, AssemblyName assemblyName)
+ public override Assembly? Resolve(MetadataLoadContext context, AssemblyName assemblyName)
{
- Assembly candidateWithSamePkt = null;
- Assembly candidateIgnoringPkt = null;
- if (_fileToPaths.TryGetValue(assemblyName.Name, out List<string> paths))
+ Debug.Assert(assemblyName.Name != null);
+ Assembly? candidateWithSamePkt = null;
+ Assembly? candidateIgnoringPkt = null;
+ if (_fileToPaths.TryGetValue(assemblyName.Name, out List<string>? paths))
{
ReadOnlySpan<byte> pktFromName = assemblyName.GetPublicKeyToken();
return typeInfo.DeclaredConstructors;
}
- public sealed override IEnumerable<ConstructorInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<ConstructorInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
Debug.Assert(reflectedType.Equals(type)); // Constructor queries are always performed as if BindingFlags.DeclaredOnly are set so the reflectedType should always be the declaring type.
return type.GetConstructorsCore(filter);
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType;
namespace System.Reflection.Runtime.BindingFlagSupport
return typeInfo.DeclaredEvents;
}
- public sealed override IEnumerable<EventInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<EventInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
return type.GetEventsCore(filter, reflectedType);
}
public sealed override void GetMemberAttributes(EventInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
- MethodInfo accessorMethod = GetAccessorMethod(member);
+ MethodInfo? accessorMethod = GetAccessorMethod(member);
if (accessorMethod == null)
{
// If we got here, this is a inherited EventInfo that only had private accessors and is now refusing to give them out
private MethodInfo GetAccessorMethod(EventInfo e)
{
- MethodInfo accessor = e.AddMethod;
+ MethodInfo? accessor = e.AddMethod;
+ Debug.Assert(accessor != null);
return accessor;
}
}
return typeInfo.DeclaredFields;
}
- public sealed override IEnumerable<FieldInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<FieldInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
return type.GetFieldsCore(filter, reflectedType);
}
// Returns all of the directly declared members on the given TypeInfo whose name matches filter. If filter is null,
// returns all directly declared members.
//
- public abstract IEnumerable<M> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType);
+ public abstract IEnumerable<M> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType);
//
// Policy to decide whether a member is considered "virtual", "virtual new" and what its member visibility is.
if (t1.IsArray && (t1.GetArrayRank() != t2.GetArrayRank()))
return false;
- return GenericMethodAwareAreParameterTypesEqual(t1.GetElementType(), t2.GetElementType());
+ return GenericMethodAwareAreParameterTypesEqual(t1.GetElementType()!, t2.GetElementType()!);
}
if (t1.IsConstructedGenericType)
//
// This is a singleton class one for each MemberInfo category: Return the appropriate one.
//
- public static readonly MemberPolicies<M> Default;
+ public static readonly MemberPolicies<M> Default = null!;
//
// This returns a fixed value from 0 to MemberIndex.Count-1 with each possible type of M
return typeInfo.DeclaredMethods;
}
- public sealed override IEnumerable<MethodInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<MethodInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
return type.GetMethodsCore(filter, reflectedType);
}
public sealed override bool ImplicitlyOverrides(MethodInfo baseMember, MethodInfo derivedMember)
{
- return AreNamesAndSignaturesEqual(baseMember, derivedMember);
+ return AreNamesAndSignaturesEqual(baseMember!, derivedMember!);
}
//
return typeInfo.DeclaredNestedTypes;
}
- public sealed override IEnumerable<Type> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<Type> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
Debug.Assert(reflectedType.Equals(type)); // NestedType queries are always performed as if BindingFlags.DeclaredOnly are set so the reflectedType should always be the declaring type.
return type.GetNestedTypesCore(filter);
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType;
namespace System.Reflection.Runtime.BindingFlagSupport
return typeInfo.DeclaredProperties;
}
- public sealed override IEnumerable<PropertyInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter filter, RuntimeTypeInfo reflectedType)
+ public sealed override IEnumerable<PropertyInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType)
{
return type.GetPropertiesCore(filter, reflectedType);
}
public sealed override void GetMemberAttributes(PropertyInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot)
{
- MethodInfo accessorMethod = GetAccessorMethod(member);
+ MethodInfo? accessorMethod = GetAccessorMethod(member);
if (accessorMethod == null)
{
// If we got here, this is a inherited PropertyInfo that only had private accessors and is now refusing to give them out
//
public sealed override bool IsSuppressedByMoreDerivedMember(PropertyInfo member, PropertyInfo[] priorMembers, int startIndex, int endIndex)
{
- MethodInfo baseAccessor = GetAccessorMethod(member);
+ MethodInfo baseAccessor = GetAccessorMethod(member)!;
for (int i = startIndex; i < endIndex; i++)
{
PropertyInfo prior = priorMembers[i];
- MethodInfo derivedAccessor = GetAccessorMethod(prior);
+ MethodInfo derivedAccessor = GetAccessorMethod(prior)!;
if (!AreNamesAndSignaturesEqual(baseAccessor, derivedAccessor))
continue;
if (derivedAccessor.IsStatic != baseAccessor.IsStatic)
private MethodInfo GetAccessorMethod(PropertyInfo property)
{
- MethodInfo accessor = property.GetMethod;
+ MethodInfo? accessor = property.GetMethod;
if (accessor == null)
{
accessor = property.SetMethod;
+ Debug.Assert(accessor != null);
}
return accessor;
ImmediateTypeOnly = immediateTypeOnly;
}
- private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo typeThatBlockedBrowsing)
+ private QueriedMemberList(int totalCount, int declaredOnlyCount, M[] members, BindingFlags[] allFlagsThatMustMatch, RuntimeTypeInfo? typeThatBlockedBrowsing)
{
_totalCount = totalCount;
_declaredOnlyCount = declaredOnlyCount;
//
// Filter by name and visibility from the ReflectedType.
//
- public static QueriedMemberList<M> Create(RuntimeTypeInfo type, string filter, bool ignoreCase, bool immediateTypeOnly)
+ public static QueriedMemberList<M> Create(RuntimeTypeInfo type, string? filter, bool ignoreCase, bool immediateTypeOnly)
{
RuntimeTypeInfo reflectedType = type;
MemberPolicies<M> policies = MemberPolicies<M>.Default;
- NameFilter nameFilter;
+ NameFilter? nameFilter;
if (filter == null)
nameFilter = null;
else if (ignoreCase)
inBaseClass = true;
}
- type = type.BaseType.CastToRuntimeTypeInfo();
+ type = type.BaseType!.CastToRuntimeTypeInfo();
if (type != null && !type.CanBrowseWithoutMissingMetadataExceptions())
{
// If we got here, one of the base classes is missing metadata. We don't want to throw a MissingMetadataException now because we may be
private int _declaredOnlyCount; // # of entries for members only in the most derived class.
private M[] _members; // Length is equal to or greater than _totalCount. Entries beyond _totalCount contain null or garbage and should be read.
private BindingFlags[] _allFlagsThatMustMatch; // Length will be equal to _members.Length
- private RuntimeTypeInfo _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata.
+ private RuntimeTypeInfo? _typeThatBlockedBrowsing; // If non-null, one of the base classes was missing metadata.
private const int Grow = 64;
}
}
public bool MoveNext()
{
- while (++_index < _unfilteredCount && !_queriedMembers.Matches(_index, _bindingAttr))
+ while (++_index < _unfilteredCount && !_queriedMembers!.Matches(_index, _bindingAttr))
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
- return _queriedMembers[_index];
+ return _queriedMembers![_index];
}
}
private int _index;
private readonly int _unfilteredCount;
private readonly BindingFlags _bindingAttr;
- private readonly QueriedMemberList<M> _queriedMembers;
+ private readonly QueriedMemberList<M>? _queriedMembers;
}
}
}
/// <summary>
/// Returns a single member, null or throws AmbigousMatchException, for the Type.Get*(string name,...) family of apis.
/// </summary>
- public M Disambiguate()
+ public M? Disambiguate()
{
if (_queriedMembers == null)
return null; // This is an uninitialized QueryResult<M>, which is supported and represents a 0-length list of matches.
int unfilteredCount = UnfilteredCount;
- M match = null;
+ M? match = null;
for (int i = 0; i < unfilteredCount; i++)
{
if (_queriedMembers.Matches(i, _bindingAttr))
// Assuming the policy says it's ok to ignore the ambiguity, we're to resolve in favor of the member
// declared by the most derived type. Since QueriedMemberLists are sorted in order of decreasing derivation,
// that means we let the first match win - unless, of course, they're both the "most derived member".
- if (match.DeclaringType.Equals(challenger.DeclaringType))
+ if (match.DeclaringType!.Equals(challenger.DeclaringType))
throw new AmbiguousMatchException();
MemberPolicies<M> policies = MemberPolicies<M>.Default;
return match;
}
- private int UnfilteredCount => ((_bindingAttr & BindingFlags.DeclaredOnly) != 0) ? _queriedMembers.DeclaredOnlyCount : _queriedMembers.TotalCount;
+ private int UnfilteredCount => ((_bindingAttr & BindingFlags.DeclaredOnly) != 0) ? _queriedMembers!.DeclaredOnlyCount : _queriedMembers!.TotalCount;
private readonly BindingFlags _bindingAttr;
private int _lazyCount; // Intentionally not marking as volatile. QueryResult is for short-term use within a single method call - no aspiration to be thread-safe.
- private QueriedMemberList<M> _queriedMembers;
+ private QueriedMemberList<M>? _queriedMembers;
}
}
// - MethodImpls ignored. (I didn't say it made sense, this is just how the .NET Framework api we're porting behaves.)
// - Implemented interfaces ignores. (I didn't say it made sense, this is just how the .NET Framework api we're porting behaves.)
//
- public static M GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo
+ public static M? GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo
{
MemberPolicies<M> policies = MemberPolicies<M>.Default;
policies.GetMemberAttributes(member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot);
return null;
}
string name = member.Name;
- TypeInfo typeInfo = member.DeclaringType.GetTypeInfo();
+ TypeInfo typeInfo = member.DeclaringType!.GetTypeInfo();
while (true)
{
- Type baseType = typeInfo.BaseType;
+ Type? baseType = typeInfo.BaseType;
if (baseType == null)
{
return null;
get
{
Debug.Assert(index < Count);
- return (_items != null) ? _items[index] : _item;
+ return (_items != null) ? _items[index] : _item!;
}
}
if (_count == 0)
return Array.Empty<T>();
if (_count == 1)
- return new T[1] { _item };
+ return new T[1] { _item! };
Array.Resize(ref _items, _count);
if (_count == 1)
{
- array[index] = _item;
+ array[index] = _item!;
return;
}
- Array.Copy(_items, 0, array, index, _count);
+ Array.Copy(_items!, 0, array, index, _count);
}
public int Count
if (_capacity < 2)
_capacity = 4;
_items = new T[_capacity];
- _items[0] = _item;
+ _items[0] = _item!;
}
else if (_capacity == _count)
{
_capacity = newCapacity;
}
- _items[_count] = item;
+ _items![_count] = item;
}
_count++;
}
- private T[] _items;
- private T _item;
+ private T[]? _items;
+ private T? _item;
private int _count;
private int _capacity;
#if DEBUG
if (pattern.IsSZArray())
{
- return actual.IsSZArray() && pattern.GetElementType().MatchesExactly(actual.GetElementType());
+ return actual.IsSZArray() && pattern.GetElementType()!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsVariableBoundArray())
{
- return actual.IsVariableBoundArray() && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.GetElementType().MatchesExactly(actual.GetElementType());
+ return actual.IsVariableBoundArray() && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.GetElementType()!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsByRef)
{
- return actual.IsByRef && pattern.GetElementType().MatchesExactly(actual.GetElementType());
+ return actual.IsByRef && pattern.GetElementType()!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsPointer)
{
- return actual.IsPointer && pattern.GetElementType().MatchesExactly(actual.GetElementType());
+ return actual.IsPointer && pattern.GetElementType()!.MatchesExactly(actual.GetElementType()!);
}
else if (pattern.IsConstructedGenericType)
{
/// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch
/// the null and continue its search for a better candidate.
/// </summary>
- internal static Type TryResolveAgainstGenericMethod(this Type signatureType, MethodInfo genericMethod)
+ internal static Type? TryResolveAgainstGenericMethod(this Type signatureType, MethodInfo genericMethod)
{
Debug.Assert(signatureType.IsSignatureType());
return signatureType.TryResolve(genericMethod.GetGenericArguments());
}
- private static Type TryResolve(this Type signatureType, Type[] genericMethodParameters)
+ private static Type? TryResolve(this Type signatureType, Type[] genericMethodParameters)
{
Debug.Assert(signatureType.IsSignatureType());
if (signatureType.IsSZArray())
{
- return signatureType.GetElementType().TryResolve(genericMethodParameters)?.TryMakeArrayType();
+ return signatureType.GetElementType()!.TryResolve(genericMethodParameters)?.TryMakeArrayType();
}
else if (signatureType.IsVariableBoundArray())
{
- return signatureType.GetElementType().TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank());
+ return signatureType.GetElementType()!.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank());
}
else if (signatureType.IsByRef)
{
- return signatureType.GetElementType().TryResolve(genericMethodParameters)?.TryMakeByRefType();
+ return signatureType.GetElementType()!.TryResolve(genericMethodParameters)?.TryMakeByRefType();
}
else if (signatureType.IsPointer)
{
- return signatureType.GetElementType().TryResolve(genericMethodParameters)?.TryMakePointerType();
+ return signatureType.GetElementType()!.TryResolve(genericMethodParameters)?.TryMakePointerType();
}
else if (signatureType.IsConstructedGenericType)
{
Type[] genericTypeArguments = signatureType.GenericTypeArguments;
int count = genericTypeArguments.Length;
- Type[] newGenericTypeArguments = new Type[count];
+ Type?[] newGenericTypeArguments = new Type[count];
for (int i = 0; i < count; i++)
{
Type genericTypeArgument = genericTypeArguments[i];
newGenericTypeArguments[i] = genericTypeArgument;
}
}
- return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments);
+ return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments!);
}
else if (signatureType.IsGenericMethodParameter())
{
}
}
- private static Type TryMakeArrayType(this Type type)
+ private static Type? TryMakeArrayType(this Type type)
{
try
{
}
}
- private static Type TryMakeArrayType(this Type type, int rank)
+ private static Type? TryMakeArrayType(this Type type, int rank)
{
try
{
}
}
- private static Type TryMakeByRefType(this Type type)
+ private static Type? TryMakeByRefType(this Type type)
{
try
{
}
}
- private static Type TryMakePointerType(this Type type)
+ private static Type? TryMakePointerType(this Type type)
{
try
{
}
}
- private static Type TryMakeGenericType(this Type type, Type[] instantiation)
+ private static Type? TryMakeGenericType(this Type type, Type[] instantiation)
{
try
{
if (internalManifestResourceInfo.ResourceLocation == ResourceLocation.ContainedInAnotherAssembly)
{
// Must get resource info from other assembly, and OR in the contained in another assembly information
- ManifestResourceInfo underlyingManifestResourceInfo = internalManifestResourceInfo.ReferencedAssembly.GetManifestResourceInfo(resourceName);
+ ManifestResourceInfo underlyingManifestResourceInfo = internalManifestResourceInfo.ReferencedAssembly.GetManifestResourceInfo(resourceName)!;
internalManifestResourceInfo.FileName = underlyingManifestResourceInfo.FileName;
internalManifestResourceInfo.ResourceLocation = underlyingManifestResourceInfo.ResourceLocation | ResourceLocation.ContainedInAnotherAssembly;
if (underlyingManifestResourceInfo.ReferencedAssembly != null)
return resourceNames;
}
- public sealed override Stream GetManifestResourceStream(string name)
+ public sealed override Stream? GetManifestResourceStream(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
/// </summary>
internal sealed partial class EcmaAssembly
{
- public sealed override event ModuleResolveEventHandler ModuleResolve;
+ public sealed override event ModuleResolveEventHandler? ModuleResolve;
protected sealed override RoModule LoadModule(string moduleName, bool containsMetadata)
{
- FileStream peStream = FindModuleNextToAssembly(moduleName);
+ FileStream? peStream = FindModuleNextToAssembly(moduleName);
if (peStream != null)
return CreateModule(peStream, containsMetadata);
- Module moduleFromEvent = ModuleResolve?.Invoke(this, new ResolveEventArgs(moduleName));
+ Module? moduleFromEvent = ModuleResolve?.Invoke(this, new ResolveEventArgs(moduleName));
if (moduleFromEvent != null)
{
if (!(moduleFromEvent is RoModule roModuleFromEvent && roModuleFromEvent.Loader == Loader))
throw new FileNotFoundException(SR.Format(SR.FileNotFoundModule, moduleName));
}
- private FileStream FindModuleNextToAssembly(string moduleName)
+ private FileStream? FindModuleNextToAssembly(string moduleName)
{
Assembly containingAssembly = this;
string location = containingAssembly.Location;
if (location == null || location.Length == 0)
return null;
- string directoryPath = Path.GetDirectoryName(location);
- string modulePath = Path.Combine(directoryPath, moduleName);
+ string? directoryPath = Path.GetDirectoryName(location);
+ string modulePath = Path.Combine(directoryPath!, moduleName);
if (File.Exists(modulePath))
return File.OpenRead(modulePath);
internal sealed override RoModule GetRoManifestModule() => _manifestModule;
internal EcmaModule GetEcmaManifestModule() => _manifestModule;
- public sealed override MethodInfo EntryPoint => GetEcmaManifestModule().ComputeEntryPoint(fileRefEntryPointAllowed: true);
+ public sealed override MethodInfo? EntryPoint => GetEcmaManifestModule().ComputeEntryPoint(fileRefEntryPointAllowed: true);
public sealed override string ImageRuntimeVersion => Reader.MetadataVersion;
public sealed override bool IsDynamic => false;
AssemblyNameFlags flags = ar.Flags.ToAssemblyNameFlags();
data.Flags = flags;
data.Name = ar.Name.GetString(reader);
- data.Version = ar.Version.AdjustForUnspecifiedVersionComponents();
+ data.Version = ar.Version.AdjustForUnspecifiedVersionComponents()!;
data.CultureName = ar.Culture.GetStringOrNull(reader) ?? string.Empty;
if ((flags & AssemblyNameFlags.PublicKey) != 0)
{
public sealed override Type[] GetForwardedTypes()
{
List<Type> types = new List<Type>();
- List<Exception> exceptions = null;
+ List<Exception>? exceptions = null;
IterateTypeForwards(
delegate (RoAssembly redirectedAssembly, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name)
{
- Type type = null;
- Exception exception = null;
+ Type? type = null;
+ Exception? exception = null;
if (redirectedAssembly is RoExceptionAssembly exceptionAssembly)
{
exception = exceptionAssembly.Exception;
else
{
// GetTypeCore() will follow any further type-forwards if needed.
- type = redirectedAssembly.GetTypeCore(ns, name, ignoreCase: false, out Exception e);
+ type = redirectedAssembly.GetTypeCore(ns, name, ignoreCase: false, out Exception? e);
if (type == null)
{
exception = e;
{
exceptions = new List<Exception>();
}
- exceptions.Add(exception);
+ exceptions.Add(exception!);
}
}
);
/// </summary>
internal abstract partial class RoAssembly
{
- public sealed override Module GetModule(string name) => GetRoModule(name);
+ public sealed override Module? GetModule(string name) => GetRoModule(name);
public sealed override Module[] GetModules(bool getResourceModules) => ComputeRoModules(getResourceModules).CloneArray<Module>();
- public sealed override FileStream GetFile(string name)
+ public sealed override FileStream? GetFile(string name)
{
- Module m = GetModule(name);
+ Module? m = GetModule(name);
if (m == null)
return null;
return new FileStream(m.FullyQualifiedName, FileMode.Open, FileAccess.Read, FileShare.Read);
};
for (int i = 0; i < _loadedModules.Length; i++)
{
- RoModule module = Volatile.Read(ref _loadedModules[i]);
+ RoModule? module = Volatile.Read(ref _loadedModules[i]);
if (module != null && (getResourceModules || !module.IsResource()))
modules.Add(module);
}
return modules.ToArray();
}
- public abstract override event ModuleResolveEventHandler ModuleResolve;
+ public abstract override event ModuleResolveEventHandler? ModuleResolve;
- internal RoModule GetRoModule(string name)
+ internal RoModule? GetRoModule(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
int loadedModulesIndex = afi.RowIndex - 1;
string moduleName = afi.Name;
- RoModule prior = Volatile.Read(ref _loadedModules[loadedModulesIndex]);
+ RoModule? prior = Volatile.Read(ref _loadedModules[loadedModulesIndex]);
if (prior != null)
return prior;
return modules.ToArray();
}
- public sealed override Module LoadModule(string moduleName, byte[] rawModule, byte[] rawSymbolStore)
+ public sealed override Module LoadModule(string moduleName, byte[]? rawModule, byte[]? rawSymbolStore)
{
if (moduleName == null)
throw new ArgumentNullException(nameof(moduleName));
/// </summary>
internal abstract partial class RoAssembly : LeveledAssembly
{
- private readonly RoModule[] _loadedModules; // Any loaded modules indexed by [rid - 1]. Does NOT include the manifest module.
+ private readonly RoModule?[] _loadedModules; // Any loaded modules indexed by [rid - 1]. Does NOT include the manifest module.
protected RoAssembly(MetadataLoadContext loader, int assemblyFileCount)
: base()
public sealed override AssemblyName GetName(bool copiedName) => GetAssemblyNameDataNoCopy().CreateAssemblyName();
internal AssemblyNameData GetAssemblyNameDataNoCopy() => _lazyAssemblyNameData ?? (_lazyAssemblyNameData = ComputeNameData());
protected abstract AssemblyNameData ComputeNameData();
- private volatile AssemblyNameData _lazyAssemblyNameData;
+ private volatile AssemblyNameData? _lazyAssemblyNameData;
public sealed override string FullName => _lazyFullName ?? (_lazyFullName = GetName().FullName);
- private volatile string _lazyFullName;
+ private volatile string? _lazyFullName;
// Location and codebase
public abstract override string Location { get; }
// Apis to retrieved types physically defined in this module.
public sealed override Type[] GetTypes() => IsSingleModule ? ManifestModule.GetTypes() : base.GetTypes();
- public sealed override IEnumerable<TypeInfo> DefinedTypes => GetDefinedRoTypes();
+ public sealed override IEnumerable<TypeInfo> DefinedTypes => GetDefinedRoTypes()!;
- private IEnumerable<RoType> GetDefinedRoTypes() => IsSingleModule ? GetRoManifestModule().GetDefinedRoTypes() : MultiModuleGetDefinedRoTypes();
+ private IEnumerable<RoType>? GetDefinedRoTypes() => IsSingleModule ? GetRoManifestModule().GetDefinedRoTypes() : MultiModuleGetDefinedRoTypes();
private IEnumerable<RoType> MultiModuleGetDefinedRoTypes()
{
foreach (RoModule module in ComputeRoModules(getResourceModules: false))
{
- foreach (RoType t in module.GetDefinedRoTypes())
+ foreach (RoType t in module.GetDefinedRoTypes()!)
{
yield return t;
}
{
get
{
- foreach (RoType type in GetDefinedRoTypes())
+ foreach (RoType type in GetDefinedRoTypes()!)
{
if (type.IsVisibleOutsideAssembly())
yield return type;
}
// Api to retrieve types by name. Retrieves both types physically defined in this module and types this assembly forwards from another assembly.
- public sealed override Type GetType(string name, bool throwOnError, bool ignoreCase)
+ public sealed override Type? GetType(string name, bool throwOnError, bool ignoreCase)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
/// If a type is not contained or forwarded from the assembly, this method returns null (does not throw.)
/// This supports the "throwOnError: false" behavior of Assembly.GetType(string, bool).
/// </summary>
- internal RoDefinitionType GetTypeCore(string ns, string name, bool ignoreCase, out Exception e) => GetTypeCore(ns.ToUtf8(), name.ToUtf8(), ignoreCase, out e);
- internal RoDefinitionType GetTypeCore(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, bool ignoreCase, out Exception e)
+ internal RoDefinitionType? GetTypeCore(string ns, string name, bool ignoreCase, out Exception? e) => GetTypeCore(ns.ToUtf8(), name.ToUtf8(), ignoreCase, out e);
+ internal RoDefinitionType? GetTypeCore(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, bool ignoreCase, out Exception? e)
{
- RoDefinitionType result = GetRoManifestModule().GetTypeCore(ns, name, ignoreCase, out e);
+ RoDefinitionType? result = GetRoManifestModule().GetTypeCore(ns, name, ignoreCase, out e);
if (IsSingleModule || result != null)
return result;
private AssemblyNameData[] GetReferencedAssembliesNoCopy() => _lazyAssemblyReferences ?? (_lazyAssemblyReferences = ComputeAssemblyReferences());
protected abstract AssemblyNameData[] ComputeAssemblyReferences();
- private volatile AssemblyNameData[] _lazyAssemblyReferences;
+ private volatile AssemblyNameData[]? _lazyAssemblyReferences;
// Miscellaneous properties
public sealed override bool ReflectionOnly => true;
public sealed override long HostContext => 0;
public abstract override string ImageRuntimeVersion { get; }
public abstract override bool IsDynamic { get; }
- public abstract override MethodInfo EntryPoint { get; }
+ public abstract override MethodInfo? EntryPoint { get; }
// Manifest resource support.
public abstract override ManifestResourceInfo GetManifestResourceInfo(string resourceName);
public abstract override string[] GetManifestResourceNames();
- public abstract override Stream GetManifestResourceStream(string name);
- public sealed override Stream GetManifestResourceStream(Type type, string name)
+ public abstract override Stream? GetManifestResourceStream(string name);
+ public sealed override Stream? GetManifestResourceStream(Type type, string name)
{
StringBuilder sb = new StringBuilder();
if (type == null)
}
else
{
- string ns = type.Namespace;
+ string? ns = type.Namespace;
if (ns != null)
{
sb.Append(ns);
// Satellite assemblies
public sealed override Assembly GetSatelliteAssembly(CultureInfo culture) => throw new NotSupportedException(SR.NotSupported_SatelliteAssembly);
- public sealed override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) => throw new NotSupportedException(SR.NotSupported_SatelliteAssembly);
+ public sealed override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) => throw new NotSupportedException(SR.NotSupported_SatelliteAssembly);
// Operations that are invalid for ReflectionOnly objects.
public sealed override object[] GetCustomAttributes(bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
// Compat quirk: Why ArgumentException instead of InvalidOperationException?
- public sealed override object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes) => throw new ArgumentException(SR.Arg_ReflectionOnlyInvoke);
+ public sealed override object CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) => throw new ArgumentException(SR.Arg_ReflectionOnlyInvoke);
internal MetadataLoadContext Loader { get; }
}
// of files that have to be edited whenever RoAssembly adds or removes an abstract method rather than to imply any meaningful commonality.
internal abstract class RoStubAssembly : RoAssembly
{
- internal RoStubAssembly() : base(null, 0) { }
- public sealed override string Location => throw null;
- public sealed override MethodInfo EntryPoint => throw null;
- public sealed override string ImageRuntimeVersion => throw null;
- public sealed override bool IsDynamic => throw null;
- public sealed override event ModuleResolveEventHandler ModuleResolve { add { throw null; } remove { throw null; } }
- public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null;
- public sealed override ManifestResourceInfo GetManifestResourceInfo(string resourceName) => throw null;
- public sealed override string[] GetManifestResourceNames() => throw null;
- public sealed override Stream GetManifestResourceStream(string name) => throw null;
- protected sealed override AssemblyNameData[] ComputeAssemblyReferences() => throw null;
- protected sealed override AssemblyNameData ComputeNameData() => throw null;
- internal sealed override RoModule GetRoManifestModule() => throw null;
- protected sealed override void IterateTypeForwards(TypeForwardHandler handler) => throw null;
- protected sealed override RoModule LoadModule(string moduleName, bool containsMetadata) => throw null;
- protected sealed override IEnumerable<AssemblyFileInfo> GetAssemblyFileInfosFromManifest(bool includeManifestModule, bool includeResourceModules) => throw null;
- protected sealed override RoModule CreateModule(Stream peStream, bool containsMetadata) => throw null;
+ internal RoStubAssembly() : base(null!, 0) { }
+ public sealed override string Location => throw null!;
+ public sealed override MethodInfo EntryPoint => throw null!;
+ public sealed override string ImageRuntimeVersion => throw null!;
+ public sealed override bool IsDynamic => throw null!;
+ public sealed override event ModuleResolveEventHandler? ModuleResolve { add { throw null!; } remove { throw null!; } }
+ public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null!;
+ public sealed override ManifestResourceInfo GetManifestResourceInfo(string resourceName) => throw null!;
+ public sealed override string[] GetManifestResourceNames() => throw null!;
+ public sealed override Stream GetManifestResourceStream(string name) => throw null!;
+ protected sealed override AssemblyNameData[] ComputeAssemblyReferences() => throw null!;
+ protected sealed override AssemblyNameData ComputeNameData() => throw null!;
+ internal sealed override RoModule GetRoManifestModule() => throw null!;
+ protected sealed override void IterateTypeForwards(TypeForwardHandler handler) => throw null!;
+ protected sealed override RoModule LoadModule(string moduleName, bool containsMetadata) => throw null!;
+ protected sealed override IEnumerable<AssemblyFileInfo> GetAssemblyFileInfosFromManifest(bool includeManifestModule, bool includeResourceModules) => throw null!;
+ protected sealed override RoModule CreateModule(Stream peStream, bool containsMetadata) => throw null!;
}
}
{
protected RoConstructor() { }
- public abstract override bool Equals(object obj);
+ public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public sealed override Type DeclaringType => GetRoDeclaringType();
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
public sealed override Module Module => GetRoModule();
internal abstract RoModule GetRoModule();
private volatile MethodImplAttributes _lazyMethodImplAttributes = MethodImplAttributesSentinel;
public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags;
- public abstract override MethodBody GetMethodBody();
+ public abstract override MethodBody? GetMethodBody();
public sealed override bool ContainsGenericParameters => GetRoDeclaringType().ContainsGenericParameters;
private MethodSig<RoParameter> MethodSig => _lazyMethodSig ?? (_lazyMethodSig = ComputeMethodSig());
protected abstract MethodSig<RoParameter> ComputeMethodSig();
- private volatile MethodSig<RoParameter> _lazyMethodSig;
+ private volatile MethodSig<RoParameter>? _lazyMethodSig;
private MethodSig<RoType> CustomModifiers => _lazyCustomModifiers ?? (_lazyCustomModifiers = ComputeCustomModifiers());
protected abstract MethodSig<RoType> ComputeCustomModifiers();
- private volatile MethodSig<RoType> _lazyCustomModifiers;
+ private volatile MethodSig<RoType>? _lazyCustomModifiers;
public sealed override string ToString() => Loader.GetDisposedString() ?? this.ToString(ComputeMethodSigStrings());
protected abstract MethodSig<string> ComputeMethodSigStrings();
public sealed override bool IsSecurityTransparent => throw new InvalidOperationException(SR.InvalidOperation_IsSecurity);
// Not valid in a ReflectionOnly context
- public sealed override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
- public sealed override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
+ public sealed override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
+ public sealed override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
public sealed override RuntimeMethodHandle MethodHandle => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
MethodBase IRoMethodBase.MethodBase => this;
protected sealed override CallingConventions ComputeCallingConvention() => _decoder.ComputeCallingConvention();
protected sealed override MethodImplAttributes ComputeMethodImplementationFlags() => _decoder.ComputeMethodImplementationFlags();
protected sealed override MethodSig<RoParameter> ComputeMethodSig() => _decoder.SpecializeMethodSig(this);
- public sealed override MethodBody GetMethodBody() => _decoder.SpecializeMethodBody(this);
+ public sealed override MethodBody? GetMethodBody() => _decoder.SpecializeMethodBody(this);
protected sealed override MethodSig<string> ComputeMethodSigStrings() => _decoder.SpecializeMethodSigStrings(TypeContext);
protected sealed override MethodSig<RoType> ComputeCustomModifiers() => _decoder.SpecializeCustomModifiers(TypeContext);
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoDefinitionConstructor<TMethodDecoder> other))
return false;
return sig;
}
- public sealed override MethodBody GetMethodBody() => null;
+ public sealed override MethodBody? GetMethodBody() => null;
protected sealed override MethodSig<string> ComputeMethodSigStrings()
{
protected sealed override MethodSig<RoType> ComputeCustomModifiers() => new MethodSig<RoType>(_parameterTypes.Length);
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoSyntheticConstructor other))
return false;
/// <summary>
/// Helper for creating a CustomAttributeNamedArgument.
/// </summary>
- public static CustomAttributeNamedArgument ToCustomAttributeNamedArgument(this Type attributeType, string name, Type argumentType, object value)
+ public static CustomAttributeNamedArgument ToCustomAttributeNamedArgument(this Type attributeType, string name, Type? argumentType, object? value)
{
MemberInfo[] members = attributeType.GetMember(name, MemberTypes.Field | MemberTypes.Property, BindingFlags.Public | BindingFlags.Instance);
if (members.Length == 0)
if (members.Length > 1)
throw new AmbiguousMatchException();
- return new CustomAttributeNamedArgument(members[0], new CustomAttributeTypedArgument(argumentType, value));
+ return new CustomAttributeNamedArgument(members[0], new CustomAttributeTypedArgument(argumentType!, value));
}
/// <summary>
private static CustomAttributeTypedArgument CloneForApiReturn(this CustomAttributeTypedArgument cat)
{
Type type = cat.ArgumentType;
- object value = cat.Value;
+ object? value = cat.Value;
if (!(value is IList<CustomAttributeTypedArgument> cats))
return cat;
/// Convert MarshalAsAttribute data into CustomAttributeData form. Returns null if the core assembly cannot be loaded or if the necessary
/// types aren't in the core assembly.
/// </summary>
- public static CustomAttributeData TryComputeMarshalAsCustomAttributeData(Func<MarshalAsAttribute> marshalAsAttributeComputer, MetadataLoadContext loader)
+ public static CustomAttributeData? TryComputeMarshalAsCustomAttributeData(Func<MarshalAsAttribute> marshalAsAttributeComputer, MetadataLoadContext loader)
{
// Make sure all the necessary framework types exist in this MetadataLoadContext's core assembly. If one doesn't, skip.
CoreTypes ct = loader.GetAllFoundCoreTypes();
ct[CoreType.Int16] == null ||
ct[CoreType.Int32] == null)
return null;
- ConstructorInfo ci = loader.TryGetMarshalAsCtor();
+ ConstructorInfo? ci = loader.TryGetMarshalAsCtor();
if (ci == null)
return null;
MarshalAsAttribute ma = marshalAsAttributeComputer();
- Type attributeType = ci.DeclaringType;
+ Type attributeType = ci.DeclaringType!;
- CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.UnmanagedType], (int)(ma.Value)) };
+ CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.UnmanagedType]!, (int)(ma.Value)) };
List<CustomAttributeNamedArgument> cans = new List<CustomAttributeNamedArgument>();
cans.AddRange(new CustomAttributeNamedArgument[]
{
private readonly CustomAttributeHandle _handle;
private readonly EcmaModule _module;
- private volatile IList<CustomAttributeTypedArgument<RoType>> _lazyFixedArguments;
- private volatile IList<CustomAttributeNamedArgument<RoType>> _lazyNamedArguments;
+ private volatile IList<CustomAttributeTypedArgument<RoType>>? _lazyFixedArguments;
+ private volatile IList<CustomAttributeNamedArgument<RoType>>? _lazyNamedArguments;
internal EcmaCustomAttributeData(CustomAttributeHandle handle, EcmaModule module)
{
if (_lazyFixedArguments == null)
LoadArguments();
- return _lazyFixedArguments.ToApiForm();
+ return _lazyFixedArguments!.ToApiForm();
}
}
if (_lazyNamedArguments == null)
LoadArguments();
- return _lazyNamedArguments.ToApiForm(AttributeType);
+ return _lazyNamedArguments!.ToApiForm(AttributeType);
}
}
Type[] parameterTypes = sig.ParameterTypes.ToArray();
Type declaringType = mr.Parent.ResolveTypeDefRefOrSpec(_module, typeContext);
const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
- ConstructorInfo ci = declaringType.GetConstructor(bf, null, parameterTypes, null);
+ ConstructorInfo? ci = declaringType.GetConstructor(bf, null, parameterTypes, null);
if (ci == null)
throw new MissingMethodException(SR.Format(SR.MissingCustomAttributeConstructor, declaringType));
return ci;
return !handles.FindCustomAttributeByName(ns, name, module).IsNil;
}
- public static CustomAttributeData TryFindCustomAttribute(this CustomAttributeHandleCollection handles, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, EcmaModule module)
+ public static CustomAttributeData? TryFindCustomAttribute(this CustomAttributeHandleCollection handles, ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, EcmaModule module)
{
CustomAttributeHandle handle = handles.FindCustomAttributeByName(ns, name, module);
if (handle.IsNil)
/// </summary>
public static CustomAttributeTypedArgument ToApiForm(this CustomAttributeTypedArgument<RoType> catg) => ToApiForm(catg.Type, catg.Value);
- private static CustomAttributeTypedArgument ToApiForm(Type type, object value)
+ private static CustomAttributeTypedArgument ToApiForm(Type type, object? value)
{
if (!(value is IList<CustomAttributeTypedArgument<RoType>> catgs))
{
/// </summary>
public static CustomAttributeNamedArgument ToApiForm(this CustomAttributeNamedArgument<RoType> cang, Type attributeType)
{
- MemberInfo member;
+ MemberInfo? member;
switch (cang.Kind)
{
case CustomAttributeNamedArgumentKind.Field:
- member = attributeType.GetField(cang.Name, BindingFlags.Public | BindingFlags.Instance);
+ member = attributeType.GetField(cang.Name!, BindingFlags.Public | BindingFlags.Instance);
break;
case CustomAttributeNamedArgumentKind.Property:
- member = attributeType.GetProperty(cang.Name, BindingFlags.Public | BindingFlags.Instance);
+ member = attributeType.GetProperty(cang.Name!, BindingFlags.Public | BindingFlags.Instance);
break;
default:
throw new BadImageFormatException();
}
- return new CustomAttributeNamedArgument(member, ToApiForm(cang.Type, cang.Value));
+ return new CustomAttributeNamedArgument(member!, ToApiForm(cang.Type, cang.Value));
}
//
if (br.RemainingBytes == 0)
break;
- string udtName = br.ReadSerializedString();
- ma.SafeArrayUserDefinedSubType = Helpers.LoadTypeFromAssemblyQualifiedName(udtName, module.GetRoAssembly(), ignoreCase: false, throwOnError: false);
+ string? udtName = br.ReadSerializedString();
+ ma.SafeArrayUserDefinedSubType = Helpers.LoadTypeFromAssemblyQualifiedName(udtName!, module.GetRoAssembly(), ignoreCase: false, throwOnError: false);
break;
case UnmanagedType.LPArray:
if (br.RemainingBytes == 0)
break;
ma.MarshalType = br.ReadSerializedString();
- ma.MarshalTypeRef = Helpers.LoadTypeFromAssemblyQualifiedName(ma.MarshalType, module.GetRoAssembly(), ignoreCase: false, throwOnError: false);
+ ma.MarshalTypeRef = Helpers.LoadTypeFromAssemblyQualifiedName(ma.MarshalType!, module.GetRoAssembly(), ignoreCase: false, throwOnError: false);
if (br.RemainingBytes == 0)
break;
{
protected RoCustomAttributeData() { }
- public sealed override Type AttributeType => _lazyAttributeType ?? (_lazyAttributeType = ComputeAttributeType());
- protected abstract Type ComputeAttributeType();
- private volatile Type _lazyAttributeType;
+ public sealed override Type AttributeType => _lazyAttributeType ?? (_lazyAttributeType = ComputeAttributeType())!;
+ protected abstract Type? ComputeAttributeType();
+ private volatile Type? _lazyAttributeType;
public sealed override ConstructorInfo Constructor => _lazyConstructorInfo ?? (_lazyConstructorInfo = ComputeConstructor());
protected abstract ConstructorInfo ComputeConstructor();
- private volatile ConstructorInfo _lazyConstructorInfo;
+ private volatile ConstructorInfo? _lazyConstructorInfo;
public abstract override IList<CustomAttributeTypedArgument> ConstructorArguments { get; }
public abstract override IList<CustomAttributeNamedArgument> NamedArguments { get; }
internal sealed class RoPseudoCustomAttributeData : RoCustomAttributeData
{
private readonly ConstructorInfo _constructor;
- private readonly Func<CustomAttributeArguments> _argumentsPromise;
+ private readonly Func<CustomAttributeArguments>? _argumentsPromise;
- private volatile IList<CustomAttributeTypedArgument> _lazyFixedArguments;
- private volatile IList<CustomAttributeNamedArgument> _lazyNamedArguments;
+ private volatile IList<CustomAttributeTypedArgument>? _lazyFixedArguments;
+ private volatile IList<CustomAttributeNamedArgument>? _lazyNamedArguments;
//
// For complex custom attributes, use this overload to defer the work of constructing the argument lists until needed.
_argumentsPromise = argumentsPromise;
}
- internal RoPseudoCustomAttributeData(ConstructorInfo constructor, IList<CustomAttributeTypedArgument> fixedArguments = null, IList<CustomAttributeNamedArgument> namedArguments = null)
+ internal RoPseudoCustomAttributeData(ConstructorInfo constructor, IList<CustomAttributeTypedArgument>? fixedArguments = null, IList<CustomAttributeNamedArgument>? namedArguments = null)
{
_constructor = constructor;
_lazyFixedArguments = fixedArguments ?? Array.Empty<CustomAttributeTypedArgument>();
private IList<CustomAttributeTypedArgument> GetLatchedFixedArguments() => _lazyFixedArguments ?? LazilyComputeArguments().FixedArguments;
private IList<CustomAttributeNamedArgument> GetLatchedNamedArguments() => _lazyNamedArguments ?? LazilyComputeArguments().NamedArguments;
- protected sealed override Type ComputeAttributeType() => _constructor.DeclaringType;
+ protected sealed override Type? ComputeAttributeType() => _constructor.DeclaringType;
protected sealed override ConstructorInfo ComputeConstructor() => _constructor;
private CustomAttributeArguments LazilyComputeArguments()
{
- CustomAttributeArguments ca = _argumentsPromise();
+ CustomAttributeArguments ca = _argumentsPromise!();
_lazyFixedArguments = ca.FixedArguments;
_lazyNamedArguments = ca.NamedArguments;
return ca;
public sealed override int MetadataToken => _handle.GetToken();
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is EcmaEvent other))
return false;
public sealed override string ToString()
{
- string disposedString = Loader.GetDisposedString();
+ string? disposedString = Loader.GetDisposedString();
if (disposedString != null)
return disposedString;
return sb.ToString();
}
- protected sealed override RoMethod ComputeEventAddMethod() => EventDefinition.GetAccessors().Adder.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
- protected sealed override RoMethod ComputeEventRemoveMethod() => EventDefinition.GetAccessors().Remover.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
- protected sealed override RoMethod ComputeEventRaiseMethod() => EventDefinition.GetAccessors().Raiser.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
+ protected sealed override RoMethod? ComputeEventAddMethod() => EventDefinition.GetAccessors().Adder.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
+ protected sealed override RoMethod? ComputeEventRemoveMethod() => EventDefinition.GetAccessors().Remover.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
+ protected sealed override RoMethod? ComputeEventRaiseMethod() => EventDefinition.GetAccessors().Raiser.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
private MetadataReader Reader => _module.Reader;
private MetadataLoadContext Loader => GetRoModule().Loader;
_reflectedType = reflectedType;
}
- public abstract override bool Equals(object obj);
+ public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public abstract override string ToString();
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
public sealed override Module Module => GetRoModule();
internal abstract RoModule GetRoModule();
public sealed override Type EventHandlerType => _lazyEventType ?? (_lazyEventType = ComputeEventHandlerType());
protected abstract Type ComputeEventHandlerType();
- private volatile Type _lazyEventType;
+ private volatile Type? _lazyEventType;
- private MethodInfo GetRoAddMethod() => (_lazyAdder == Sentinels.RoMethod) ? (_lazyAdder = ComputeEventAddMethod()?.FilterInheritedAccessor()) : _lazyAdder;
- private MethodInfo GetRoRemoveMethod() => (_lazyRemover == Sentinels.RoMethod) ? (_lazyRemover = ComputeEventRemoveMethod()?.FilterInheritedAccessor()) : _lazyRemover;
- private MethodInfo GetRoRaiseMethod() => (_lazyRaiser == Sentinels.RoMethod) ? (_lazyRaiser = ComputeEventRaiseMethod()?.FilterInheritedAccessor()) : _lazyRaiser;
+ private MethodInfo? GetRoAddMethod() => (_lazyAdder == Sentinels.RoMethod) ? (_lazyAdder = ComputeEventAddMethod()?.FilterInheritedAccessor()) : _lazyAdder;
+ private MethodInfo? GetRoRemoveMethod() => (_lazyRemover == Sentinels.RoMethod) ? (_lazyRemover = ComputeEventRemoveMethod()?.FilterInheritedAccessor()) : _lazyRemover;
+ private MethodInfo? GetRoRaiseMethod() => (_lazyRaiser == Sentinels.RoMethod) ? (_lazyRaiser = ComputeEventRaiseMethod()?.FilterInheritedAccessor()) : _lazyRaiser;
- public sealed override MethodInfo GetAddMethod(bool nonPublic) => GetRoAddMethod()?.FilterAccessor(nonPublic);
- public sealed override MethodInfo GetRemoveMethod(bool nonPublic) => GetRoRemoveMethod()?.FilterAccessor(nonPublic);
- public sealed override MethodInfo GetRaiseMethod(bool nonPublic) => GetRoRaiseMethod()?.FilterAccessor(nonPublic);
+ public sealed override MethodInfo? GetAddMethod(bool nonPublic) => GetRoAddMethod()?.FilterAccessor(nonPublic);
+ public sealed override MethodInfo? GetRemoveMethod(bool nonPublic) => GetRoRemoveMethod()?.FilterAccessor(nonPublic);
+ public sealed override MethodInfo? GetRaiseMethod(bool nonPublic) => GetRoRaiseMethod()?.FilterAccessor(nonPublic);
- protected abstract RoMethod ComputeEventAddMethod();
- protected abstract RoMethod ComputeEventRemoveMethod();
- protected abstract RoMethod ComputeEventRaiseMethod();
+ protected abstract RoMethod? ComputeEventAddMethod();
+ protected abstract RoMethod? ComputeEventRemoveMethod();
+ protected abstract RoMethod? ComputeEventRaiseMethod();
- private volatile RoMethod _lazyAdder = Sentinels.RoMethod;
- private volatile RoMethod _lazyRemover = Sentinels.RoMethod;
- private volatile RoMethod _lazyRaiser = Sentinels.RoMethod;
+ private volatile RoMethod? _lazyAdder = Sentinels.RoMethod;
+ private volatile RoMethod? _lazyRemover = Sentinels.RoMethod;
+ private volatile RoMethod? _lazyRaiser = Sentinels.RoMethod;
public abstract override MethodInfo[] GetOtherMethods(bool nonPublic);
public sealed override object[] GetCustomAttributes(bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override void AddEventHandler(object target, Delegate handler) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override void RemoveEventHandler(object target, Delegate handler) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override void AddEventHandler(object? target, Delegate? handler) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override void RemoveEventHandler(object? target, Delegate? handler) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
private MetadataLoadContext Loader => GetRoModule().Loader;
internal TypeContext TypeContext => _declaringType.Instantiation.ToTypeContext();
public sealed override int MetadataToken => _handle.GetToken();
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is EcmaField other))
return false;
private Type[] GetCustomModifiers(bool isRequired)
{
- RoType type = FieldDefinition.DecodeSignature(new EcmaModifiedTypeProvider(_module), TypeContext);
+ RoType type = FieldDefinition.DecodeSignature(new EcmaModifiedTypeProvider(_module), TypeContext)!;
return type.ExtractCustomModifiers(isRequired);
}
- protected sealed override object ComputeRawConstantValue() => FieldDefinition.GetDefaultValue().ToRawObject(Reader);
+ protected sealed override object? ComputeRawConstantValue() => FieldDefinition.GetDefaultValue().ToRawObject(Reader);
public sealed override string ToString()
{
- string disposedString = Loader.GetDisposedString();
+ string? disposedString = Loader.GetDisposedString();
if (disposedString != null)
return disposedString;
_reflectedType = reflectedType;
}
- public abstract override bool Equals(object obj);
+ public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public abstract override string ToString();
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
public sealed override Module Module => GetRoModule();
internal abstract RoModule GetRoModule();
if (_declaringType.IsExplicitLayout)
{
- ConstructorInfo ci = Loader.TryGetFieldOffsetCtor();
+ ConstructorInfo? ci = Loader.TryGetFieldOffsetCtor();
if (ci != null)
{
int offset = GetExplicitFieldOffset();
if (0 != (Attributes & FieldAttributes.HasFieldMarshal))
{
- CustomAttributeData cad = CustomAttributeHelpers.TryComputeMarshalAsCustomAttributeData(ComputeMarshalAsAttribute, Loader);
+ CustomAttributeData? cad = CustomAttributeHelpers.TryComputeMarshalAsCustomAttributeData(ComputeMarshalAsAttribute, Loader);
if (cad != null)
yield return cad;
}
public sealed override Type FieldType => _lazyFieldType ?? (_lazyFieldType = ComputeFieldType());
protected abstract Type ComputeFieldType();
- private volatile Type _lazyFieldType;
+ private volatile Type? _lazyFieldType;
- public sealed override object GetRawConstantValue() => IsLiteral ? ComputeRawConstantValue() : throw new InvalidOperationException();
- protected abstract object ComputeRawConstantValue();
+ public sealed override object? GetRawConstantValue() => IsLiteral ? ComputeRawConstantValue() : throw new InvalidOperationException();
+ protected abstract object? ComputeRawConstantValue();
public abstract override Type[] GetOptionalCustomModifiers();
public abstract override Type[] GetRequiredCustomModifiers();
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override RuntimeFieldHandle FieldHandle => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override object GetValue(object obj) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override object GetValue(object? obj) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override object GetValueDirect(TypedReference obj) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override void SetValueDirect(TypedReference obj, object value) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
private MetadataLoadContext Loader => GetRoModule().Loader;
internal sealed class AssemblyNameData
{
public AssemblyNameFlags Flags;
- public string Name;
- public Version Version;
- public string CultureName;
- public byte[] PublicKey;
- public byte[] PublicKeyToken;
+ public string? Name;
+ public Version? Version;
+ public string? CultureName;
+ public byte[]? PublicKey;
+ public byte[]? PublicKeyToken;
public AssemblyContentType ContentType;
public AssemblyHashAlgorithm HashAlgorithm;
public ProcessorArchitecture ProcessorArchitecture;
}
}
- Type toElementTypeInfo = toTypeInfo.GetElementType();
- Type fromElementTypeInfo = fromTypeInfo.GetElementType();
+ Type toElementTypeInfo = toTypeInfo.GetElementType()!;
+ Type fromElementTypeInfo = fromTypeInfo.GetElementType()!;
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (!toTypeInfo.IsByRef)
return false;
- Type toElementTypeInfo = toTypeInfo.GetElementType();
- Type fromElementTypeInfo = fromTypeInfo.GetElementType();
+ Type toElementTypeInfo = toTypeInfo.GetElementType()!;
+ Type fromElementTypeInfo = fromTypeInfo.GetElementType()!;
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
if (!toTypeInfo.IsPointer)
return false;
- Type toElementTypeInfo = toTypeInfo.GetElementType();
- Type fromElementTypeInfo = fromTypeInfo.GetElementType();
+ Type toElementTypeInfo = toTypeInfo.GetElementType()!;
+ Type fromElementTypeInfo = fromTypeInfo.GetElementType()!;
return fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes);
}
Type walk = fromTypeInfo;
while (true)
{
- Type baseType = walk.BaseType;
+ Type? baseType = walk.BaseType;
if (baseType == null)
return false;
walk = baseType;
Type toElementTypeInfo = toTypeGenericTypeArguments[0];
Type toTypeGenericTypeDefinition = toTypeInfo.GetGenericTypeDefinition();
- Type fromElementTypeInfo = fromTypeInfo.GetElementType();
+ Type? fromElementTypeInfo = fromTypeInfo.GetElementType();
foreach (Type ifc in fromTypeInfo.GetInterfaces())
{
if (ifc.IsConstructedGenericType)
Type ifcGenericTypeDefinition = ifc.GetGenericTypeDefinition();
if (ifcGenericTypeDefinition.Equals(toTypeGenericTypeDefinition))
{
- if (fromElementTypeInfo.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes))
+ if (fromElementTypeInfo!.IsElementTypeCompatibleWith(toElementTypeInfo, coreTypes))
return true;
}
}
/// </summary>
internal sealed class CoreTypes
{
- private readonly RoType[] _coreTypes;
- private readonly Exception[] _exceptions;
+ private readonly RoType?[] _coreTypes;
+ private readonly Exception?[] _exceptions;
- internal CoreTypes(MetadataLoadContext loader, string coreAssemblyName)
+ internal CoreTypes(MetadataLoadContext loader, string? coreAssemblyName)
{
int numCoreTypes = (int)CoreType.NumCoreTypes;
- RoType[] coreTypes = new RoType[numCoreTypes];
- Exception[] exceptions = new Exception[numCoreTypes];
- RoAssembly coreAssembly = loader.TryGetCoreAssembly(coreAssemblyName, out Exception e);
+ RoType?[] coreTypes = new RoType[numCoreTypes];
+ Exception?[] exceptions = new Exception[numCoreTypes];
+ RoAssembly? coreAssembly = loader.TryGetCoreAssembly(coreAssemblyName, out Exception? e);
if (coreAssembly == null)
{
// If the core assembly was not found, don't continue.
- throw e;
+ throw e!;
}
else
{
for (int i = 0; i < numCoreTypes; i++)
{
((CoreType)i).GetFullName(out byte[] ns, out byte[] name);
- RoType type = coreAssembly.GetTypeCore(ns, name, ignoreCase: false, out e);
+ RoType? type = coreAssembly.GetTypeCore(ns, name, ignoreCase: false, out e);
coreTypes[i] = type;
if (type == null)
{
/// <summary>
/// Returns null if the specific core type did not exist or could not be loaded. Call GetException(coreType) to get detailed info.
/// </summary>
- public RoType this[CoreType coreType] => _coreTypes[(int)coreType];
- public Exception GetException(CoreType coreType) => _exceptions[(int)coreType];
+ public RoType? this[CoreType coreType] => _coreTypes[(int)coreType];
+ public Exception? GetException(CoreType coreType) => _exceptions[(int)coreType];
}
}
{
internal static class EcmaDefaultValueProcessing
{
- public static object ToRawObject(this ConstantHandle constantHandle, MetadataReader metadataReader)
+ public static object? ToRawObject(this ConstantHandle constantHandle, MetadataReader metadataReader)
{
if (constantHandle.IsNil)
throw new BadImageFormatException();
throw new BadImageFormatException();
}
- public static bool TryFindRawDefaultValueFromCustomAttributes(this CustomAttributeHandleCollection handles, EcmaModule module, out object rawDefaultValue)
+ public static bool TryFindRawDefaultValueFromCustomAttributes(this CustomAttributeHandleCollection handles, EcmaModule module, out object? rawDefaultValue)
{
rawDefaultValue = default;
if (cats[0].ArgumentType != ct[CoreType.Int64])
return false;
- long ticks = (long)(cats[0].Value);
+ long ticks = (long)(cats[0].Value!);
rawDefaultValue = new DateTimeConstantAttribute(ticks).Value;
return true;
}
cats[1].ArgumentType != ct[CoreType.Byte])
return false;
- byte scale = (byte)cats[0].Value;
- byte sign = (byte)cats[1].Value;
+ byte scale = (byte)cats[0].Value!;
+ byte sign = (byte)cats[1].Value!;
if (cats[2].ArgumentType == ct[CoreType.Int32] && cats[3].ArgumentType == ct[CoreType.Int32] && cats[4].ArgumentType == ct[CoreType.Int32])
{
- int hi = (int)cats[2].Value;
- int mid = (int)cats[3].Value;
- int lo = (int)cats[4].Value;
+ int hi = (int)cats[2].Value!;
+ int mid = (int)cats[3].Value!;
+ int lo = (int)cats[4].Value!;
rawDefaultValue = new DecimalConstantAttribute(scale, sign, hi, mid, lo).Value;
return true;
}
if (cats[2].ArgumentType == ct[CoreType.UInt32] && cats[3].ArgumentType == ct[CoreType.UInt32] && cats[4].ArgumentType == ct[CoreType.UInt32])
{
- uint hi = (uint)cats[2].Value;
- uint mid = (uint)cats[3].Value;
- uint lo = (uint)cats[4].Value;
+ uint hi = (uint)cats[2].Value!;
+ uint mid = (uint)cats[3].Value!;
+ uint lo = (uint)cats[4].Value!;
rawDefaultValue = new DecimalConstantAttribute(scale, sign, hi, mid, lo).Value;
return true;
}
{
AssemblyReference a = h.GetAssemblyReference(reader);
string name = a.Name.GetString(reader);
- Version version = a.Version.AdjustForUnspecifiedVersionComponents();
- string culture = a.Culture.GetStringOrNull(reader);
- byte[] pkOrPkt = a.PublicKeyOrToken.GetBlobBytes(reader);
+ Version? version = a.Version.AdjustForUnspecifiedVersionComponents();
+ string? culture = a.Culture.GetStringOrNull(reader);
+ byte[]? pkOrPkt = a.PublicKeyOrToken.GetBlobBytes(reader);
AssemblyFlags flags = a.Flags;
AssemblyNameFlags assemblyNameFlags = Helpers.ConvertAssemblyFlagsToAssemblyNameFlags(flags);
if ((flags & AssemblyFlags.PublicKey) != 0)
return new ReadOnlySpan<byte>(br.CurrentPointer, br.Length);
}
- public static RoMethod ToMethodOrNull(this MethodDefinitionHandle handle, RoInstantiationProviderType declaringType, Type reflectedType)
+ public static RoMethod? ToMethodOrNull(this MethodDefinitionHandle handle, RoInstantiationProviderType declaringType, Type reflectedType)
{
if (handle.IsNil)
return null;
//
// Pragmatically speaking, searching the entire assembly should get us the same result and avoids writing a significant
// code path that will get almost no test coverage as this is an obscure case not produced by mainstream tools..
- RoDefinitionType type = module.GetEcmaAssembly().GetTypeCore(ns, name, ignoreCase: false, out Exception e);
+ RoDefinitionType? type = module.GetEcmaAssembly().GetTypeCore(ns, name, ignoreCase: false, out Exception? e);
if (type == null)
- throw e;
+ throw e!;
return type;
}
{
AssemblyReferenceHandle arh = (AssemblyReferenceHandle)scope;
RoAssembly assembly = arh.ResolveAssembly(module);
- RoDefinitionType type = assembly.GetTypeCore(ns, name, ignoreCase: false, out Exception e);
+ RoDefinitionType? type = assembly.GetTypeCore(ns, name, ignoreCase: false, out Exception? e);
if (type == null)
- throw e;
+ throw e!;
return type;
}
case HandleKind.TypeReference:
{
RoDefinitionType outerType = ((TypeReferenceHandle)scope).ResolveTypeRef(module);
- RoDefinitionType nestedType = outerType.GetNestedTypeCore(name);
+ RoDefinitionType? nestedType = outerType.GetNestedTypeCore(name);
return nestedType ?? throw new TypeLoadException(SR.Format(SR.Format(SR.TypeNotFound, outerType.ToString() + "[]", outerType.Assembly.FullName)));
}
case HandleKind.ModuleDefinition:
{
- RoDefinitionType type = module.GetTypeCore(ns, name, ignoreCase: false, out Exception e);
+ RoDefinitionType? type = module.GetTypeCore(ns, name, ignoreCase: false, out Exception? e);
if (type == null)
- throw e;
+ throw e!;
return type;
}
case HandleKind.ModuleReference:
{
string moduleName = ((ModuleReferenceHandle)scope).GetModuleReference(module.Reader).Name.GetString(module.Reader);
- RoModule targetModule = module.GetRoAssembly().GetRoModule(moduleName);
+ RoModule? targetModule = module.GetRoAssembly().GetRoModule(moduleName);
if (targetModule == null)
throw new BadImageFormatException(SR.Format(SR.BadImageFormat_TypeRefModuleNotInManifest, module.Assembly.FullName, $"0x{handle.GetToken():x8}"));
- RoDefinitionType type = targetModule.GetTypeCore(ns, name, ignoreCase: false, out Exception e);
+ RoDefinitionType? type = targetModule.GetTypeCore(ns, name, ignoreCase: false, out Exception? e);
if (type == null)
- throw e;
+ throw e!;
return type;
}
public static RoAssembly ResolveAssembly(this AssemblyReferenceHandle handle, EcmaModule module)
{
- RoAssembly assembly = handle.TryResolveAssembly(module, out Exception e);
+ RoAssembly? assembly = handle.TryResolveAssembly(module, out Exception? e);
if (assembly == null)
- throw e;
+ throw e!;
return assembly;
}
- public static RoAssembly TryResolveAssembly(this AssemblyReferenceHandle handle, EcmaModule module, out Exception e)
+ public static RoAssembly? TryResolveAssembly(this AssemblyReferenceHandle handle, EcmaModule module, out Exception? e)
{
e = null;
RoAssembly assembly = handle.ResolveToAssemblyOrExceptionAssembly(module);
public static int GetToken(this StandaloneSignatureHandle handle) => MetadataTokens.GetToken(handle);
public static int GetToken(this AssemblyFileHandle handle) => MetadataTokens.GetToken(handle);
- public static string GetStringOrNull(this StringHandle handle, MetadataReader reader) => handle.IsNil ? null : reader.GetString(handle);
+ public static string? GetStringOrNull(this StringHandle handle, MetadataReader reader) => handle.IsNil ? null : reader.GetString(handle);
public static bool Equals(this StringHandle handle, string value, MetadataReader reader) => reader.StringComparer.Equals(handle, value, ignoreCase: false);
internal sealed class MetadataTable<T, C>
where T : class
{
- private readonly T[] _table;
+ private readonly T?[] _table;
public MetadataTable(int count)
{
Count = count;
- _table = new T[count];
+ _table = new T?[count];
}
public T GetOrAdd(EntityHandle handle, C context, Func<EntityHandle, C, T> factory)
Debug.Assert(factory != null);
int index = handle.GetToken().GetTokenRowNumber() - 1;
- T[] table = _table;
- T result = Volatile.Read(ref table[index]);
+ T?[] table = _table;
+ T? result = Volatile.Read(ref table[index]);
if (result != null)
return result;
T newValue = factory(handle, context);
/// <summary>
/// Return a read-only enumeration of the table (safe to hand back to app code.)
/// </summary>
- public IEnumerable<T> EnumerateValues(int skip = 0)
+ public IEnumerable<T?> EnumerateValues(int skip = 0)
{
for (int i = skip; i < _table.Length; i++)
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Text;
namespace System.Reflection.TypeLoading
{
internal static class Helpers
{
- public static T[] CloneArray<T>(this T[] original)
+ [return: NotNullIfNotNull("original")]
+ public static T[]? CloneArray<T>(this T[]? original)
{
if (original == null)
return null;
public static int GetTokenRowNumber(this int token) => token & 0x00ffffff;
- public static RoMethod FilterInheritedAccessor(this RoMethod accessor)
+ public static RoMethod? FilterInheritedAccessor(this RoMethod accessor)
{
if (accessor.ReflectedType == accessor.DeclaringType)
return accessor;
return accessor;
}
- public static MethodInfo FilterAccessor(this MethodInfo accessor, bool nonPublic)
+ public static MethodInfo? FilterAccessor(this MethodInfo accessor, bool nonPublic)
{
if (nonPublic)
return accessor;
/// <summary>
/// For AssemblyReferences, convert "unspecified" components from the ECMA format (0xffff) to the in-memory System.Version format (0xffffffff).
/// </summary>
- public static Version AdjustForUnspecifiedVersionComponents(this Version v)
+ public static Version? AdjustForUnspecifiedVersionComponents(this Version v)
{
int mask =
((v.Revision == ushort.MaxValue) ? 0b0001 : 0) |
};
}
- public static byte[] ComputePublicKeyToken(this byte[] pkt)
+ public static byte[]? ComputePublicKeyToken(this byte[] pkt)
{
// @TODO - https://github.com/dotnet/corefxlab/issues/2447 - This is not the best way to compute the PKT as AssemblyName
// throws if the PK isn't a valid PK blob. That's not something we should block a metadata inspection tool for so we
sb.Append(' ');
sb.Append(roMethodBase.MethodBase.Name);
- Type[] genericMethodArguments = typeContext.GenericMethodArguments;
+ Type[]? genericMethodArguments = typeContext.GenericMethodArguments;
int count = genericMethodArguments == null ? 0 : genericMethodArguments.Length;
if (count != 0)
{
{
if (gpi != 0)
sb.Append(',');
- sb.Append(genericMethodArguments[gpi].ToString());
+ sb.Append(genericMethodArguments![gpi].ToString());
}
sb.Append(']');
}
return true;
}
- public static RoType LoadTypeFromAssemblyQualifiedName(string name, RoAssembly defaultAssembly, bool ignoreCase, bool throwOnError)
+ public static RoType? LoadTypeFromAssemblyQualifiedName(string name, RoAssembly defaultAssembly, bool ignoreCase, bool throwOnError)
{
if (!name.TypeNameContainsTypeParserMetacharacters())
{
// Fast-path: the type contains none of the parser metacharacters nor the escape character. Just treat as plain old type name.
name.SplitTypeName(out string ns, out string simpleName);
- RoType type = defaultAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase, out Exception e);
+ RoType? type = defaultAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase, out Exception? e);
if (type != null)
return type;
if (throwOnError)
- throw e;
+ throw e!;
}
MetadataLoadContext loader = defaultAssembly.Loader;
return loader.LoadFromAssemblyName(assemblyName);
};
- Func<Assembly, string, bool, Type> typeResolver =
- delegate (Assembly assembly, string fullName, bool ignoreCase2)
+ Func<Assembly?, string, bool, Type?> typeResolver =
+ delegate (Assembly? assembly, string fullName, bool ignoreCase2)
{
if (assembly == null)
assembly = defaultAssembly;
fullName = fullName.UnescapeTypeNameIdentifier();
fullName.SplitTypeName(out string ns, out string simpleName);
- Type type = roAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase2, out Exception e);
+ Type? type = roAssembly.GetTypeCore(ns, simpleName, ignoreCase: ignoreCase2, out Exception? e);
if (type != null)
return type;
if (throwOnError)
- throw e;
+ throw e!;
return null;
};
- return (RoType)Type.GetType(name, assemblyResolver: assemblyResolver, typeResolver: typeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase);
+ return (RoType?)Type.GetType(name, assemblyResolver: assemblyResolver, typeResolver: typeResolver, throwOnError: throwOnError, ignoreCase: ignoreCase);
}
public static Type[] ExtractCustomModifiers(this RoType type, bool isRequired)
return true;
if (visibility == TypeAttributes.NestedPublic)
- return type.DeclaringType.IsVisibleOutsideAssembly();
+ return type.DeclaringType!.IsVisibleOutsideAssembly();
return false;
}
// AssemblyName's PKT property getters do NOT copy the array before giving it out. Make our own copy
// as the original is wide open to tampering by anyone.
- byte[] pkt = assemblyName.GetPublicKeyToken().CloneArray();
+ byte[]? pkt = assemblyName.GetPublicKeyToken().CloneArray();
return new RoAssemblyName(assemblyName.Name, assemblyName.Version, assemblyName.CultureName, pkt, assemblyName.Flags);
}
//
// public sealed override string ToString() => Loader.GetDisposedString() ?? <your real ToString() code>;"
//
- public static string GetDisposedString(this MetadataLoadContext loader) => loader.IsDisposed ? SR.MetadataLoadContextDisposed : null;
+ public static string? GetDisposedString(this MetadataLoadContext loader) => loader.IsDisposed ? SR.MetadataLoadContextDisposed : null;
public static TypeContext ToTypeContext(this RoType[] instantiation) => new TypeContext(instantiation, null);
}
// that it's far shorter than "ParametersAndReturnType".
internal sealed class MethodSig<T>
{
- public T Return { get; private set; }
+ public T Return { get; private set; } = default!;
public T[] Parameters { get; }
public MethodSig(int parameterCount)
private static readonly Version s_Version0000 = new Version(0, 0, 0, 0);
- public RoAssemblyName(string name, Version version, string cultureName, byte[] publicKeyToken, AssemblyNameFlags flags)
+ public RoAssemblyName(string? name, Version? version, string? cultureName, byte[]? publicKeyToken, AssemblyNameFlags flags)
{
// We forcefully normalize the representation so that Equality is dependable and fast.
Debug.Assert(name != null);
return true;
}
- public sealed override bool Equals(object obj) => obj is RoAssemblyName other && Equals(other);
+ public sealed override bool Equals(object? obj) => obj is RoAssemblyName other && Equals(other);
public sealed override int GetHashCode() => Name.GetHashCode();
public sealed override string ToString() => FullName;
private sealed class SentinelMethod : RoMethod
{
internal SentinelMethod() : base(Sentinels.RoType) { }
- internal sealed override RoType GetRoDeclaringType() => throw null;
- internal sealed override RoModule GetRoModule() => throw null;
- public sealed override int MetadataToken => throw null;
- public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null;
- public sealed override bool IsConstructedGenericMethod => throw null;
- public sealed override bool IsGenericMethodDefinition => throw null;
- public sealed override bool Equals(object obj) => throw null;
- public sealed override MethodInfo GetGenericMethodDefinition() => throw null;
- public sealed override int GetHashCode() => throw null;
- public sealed override MethodBody GetMethodBody() => throw null;
- public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) => throw null;
- protected sealed override MethodAttributes ComputeAttributes() => throw null;
- protected sealed override CallingConventions ComputeCallingConvention() => throw null;
- protected sealed override RoType[] ComputeGenericArgumentsOrParameters() => throw null;
- protected sealed override MethodImplAttributes ComputeMethodImplementationFlags() => throw null;
- protected sealed override MethodSig<RoParameter> ComputeMethodSig() => throw null;
- protected sealed override MethodSig<RoType> ComputeCustomModifiers() => throw null;
- protected sealed override MethodSig<string> ComputeMethodSigStrings() => throw null;
- protected sealed override string ComputeName() => throw null;
- internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => throw null;
- internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null;
- public sealed override TypeContext TypeContext => throw null;
+ internal sealed override RoType GetRoDeclaringType() => throw null!;
+ internal sealed override RoModule GetRoModule() => throw null!;
+ public sealed override int MetadataToken => throw null!;
+ public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null!;
+ public sealed override bool IsConstructedGenericMethod => throw null!;
+ public sealed override bool IsGenericMethodDefinition => throw null!;
+ public sealed override bool Equals(object? obj) => throw null!;
+ public sealed override MethodInfo GetGenericMethodDefinition() => throw null!;
+ public sealed override int GetHashCode() => throw null!;
+ public sealed override MethodBody GetMethodBody() => throw null!;
+ public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) => throw null!;
+ protected sealed override MethodAttributes ComputeAttributes() => throw null!;
+ protected sealed override CallingConventions ComputeCallingConvention() => throw null!;
+ protected sealed override RoType[] ComputeGenericArgumentsOrParameters() => throw null!;
+ protected sealed override MethodImplAttributes ComputeMethodImplementationFlags() => throw null!;
+ protected sealed override MethodSig<RoParameter> ComputeMethodSig() => throw null!;
+ protected sealed override MethodSig<RoType> ComputeCustomModifiers() => throw null!;
+ protected sealed override MethodSig<string> ComputeMethodSigStrings() => throw null!;
+ protected sealed override string ComputeName() => throw null!;
+ internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => throw null!;
+ internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null!;
+ public sealed override TypeContext TypeContext => throw null!;
}
}
}
//
internal readonly struct TypeContext
{
- internal TypeContext(RoType[] genericTypeArguments, RoType[] genericMethodArguments)
+ internal TypeContext(RoType[] genericTypeArguments, RoType[]? genericMethodArguments)
{
GenericTypeArguments = genericTypeArguments;
GenericMethodArguments = genericMethodArguments;
}
public RoType[] GenericTypeArguments { get; }
- public RoType[] GenericMethodArguments { get; }
+ public RoType[]? GenericMethodArguments { get; }
- public RoType GetGenericTypeArgumentOrNull(int index)
+ public RoType? GetGenericTypeArgumentOrNull(int index)
{
if (GenericTypeArguments == null || ((uint)index) >= GenericTypeArguments.Length)
return null;
return GenericTypeArguments[index];
}
- public RoType GetGenericMethodArgumentOrNull(int index)
+ public RoType? GetGenericMethodArgumentOrNull(int index)
{
if (GenericMethodArguments == null || ((uint)index) >= GenericMethodArguments.Length)
return null;
public sealed override int MaxStackSize => Block.MaxStack;
public sealed override int LocalSignatureMetadataToken => Block.LocalSignature.GetToken();
- protected sealed override byte[] ComputeIL() => Block.GetILBytes();
+ protected sealed override byte[]? ComputeIL() => Block.GetILBytes();
public sealed override IList<LocalVariableInfo> LocalVariables
{
for (int i = 0; i < count; i++)
{
EntityHandle catchTypeHandle = regions[i].CatchType;
- RoType catchType = catchTypeHandle.IsNil ? null : catchTypeHandle.ResolveTypeDefRefOrSpec(GetEcmaModule(), TypeContext);
+ RoType? catchType = catchTypeHandle.IsNil ? null : catchTypeHandle.ResolveTypeDefRefOrSpec(GetEcmaModule(), TypeContext);
clauses[i] = new RoExceptionHandlingClause(
catchType: catchType,
flags: regions[i].Kind.ToExceptionHandlingClauseOptions(),
return results;
}
- public MethodBody SpecializeMethodBody(IRoMethodBase owner)
+ public MethodBody? SpecializeMethodBody(IRoMethodBase owner)
{
int rva = MethodDefinition.RelativeVirtualAddress;
if (rva == 0)
MethodSig<RoParameter> SpecializeMethodSig(IRoMethodBase member);
MethodSig<RoType> SpecializeCustomModifiers(in TypeContext typeContext);
- MethodBody SpecializeMethodBody(IRoMethodBase owner);
+ MethodBody? SpecializeMethodBody(IRoMethodBase owner);
MethodSig<string> SpecializeMethodSigStrings(in TypeContext typeContext);
}
}
{
internal sealed partial class RoExceptionHandlingClause : ExceptionHandlingClause
{
- private readonly Type _catchType;
+ private readonly Type? _catchType;
private readonly ExceptionHandlingClauseOptions _flags;
private readonly int _filterOffset;
private readonly int _tryOffset;
private readonly int _handlerOffset;
private readonly int _handlerLength;
- internal RoExceptionHandlingClause(Type catchType, ExceptionHandlingClauseOptions flags, int filterOffset, int tryOffset, int tryLength, int handlerOffset, int handlerLength)
+ internal RoExceptionHandlingClause(Type? catchType, ExceptionHandlingClauseOptions flags, int filterOffset, int tryOffset, int tryLength, int handlerOffset, int handlerLength)
{
_catchType = catchType;
_flags = flags;
_handlerLength = handlerLength;
}
- public sealed override Type CatchType => _flags == ExceptionHandlingClauseOptions.Clause ? _catchType : throw new InvalidOperationException(SR.NotAClause);
+ public sealed override Type? CatchType => _flags == ExceptionHandlingClauseOptions.Clause ? _catchType : throw new InvalidOperationException(SR.NotAClause);
public sealed override ExceptionHandlingClauseOptions Flags => _flags;
public sealed override int FilterOffset => _flags == ExceptionHandlingClauseOptions.Filter ? _filterOffset : throw new InvalidOperationException(SR.NotAFilter);
public sealed override int HandlerOffset => _handlerOffset;
public abstract override int LocalSignatureMetadataToken { get; }
// Unlike most apis, this one does not copy the byte array.
- public sealed override byte[] GetILAsByteArray() => _lazyIL ?? (_lazyIL = ComputeIL());
- protected abstract byte[] ComputeIL();
- private volatile byte[] _lazyIL;
+ public sealed override byte[]? GetILAsByteArray() => _lazyIL ?? (_lazyIL = ComputeIL());
+ protected abstract byte[]? ComputeIL();
+ private volatile byte[]? _lazyIL;
public abstract override IList<LocalVariableInfo> LocalVariables { get; }
public abstract override IList<ExceptionHandlingClause> ExceptionHandlingClauses { get; }
protected sealed override MethodSig<RoParameter> ComputeMethodSig() => _genericMethodDefinition.SpecializeMethodSig(this);
protected sealed override MethodSig<RoType> ComputeCustomModifiers() => _genericMethodDefinition.SpecializeCustomModifiers(TypeContext);
- public sealed override MethodBody GetMethodBody() => _genericMethodDefinition.SpecializeMethodBody(this);
+ public sealed override MethodBody? GetMethodBody() => _genericMethodDefinition.SpecializeMethodBody(this);
protected sealed override RoType[] ComputeGenericArgumentsOrParameters() => _genericMethodArguments;
public sealed override MethodInfo MakeGenericMethod(params Type[] typeArguments) => throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this));
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoConstructedGenericMethod other))
return false;
/// </summary>
internal sealed partial class RoDefinitionMethod<TMethodDecoder>
{
- private CustomAttributeData ComputeDllImportCustomAttributeDataIfAny()
+ private CustomAttributeData? ComputeDllImportCustomAttributeDataIfAny()
{
if ((Attributes & MethodAttributes.PinvokeImpl) == 0)
return null;
ct[CoreType.CharSet] == null ||
ct[CoreType.CallingConvention] == null)
return null;
- ConstructorInfo ctor = Loader.TryGetDllImportCtor();
+ ConstructorInfo? ctor = Loader.TryGetDllImportCtor();
if (ctor == null)
return null;
{
// The expensive work goes in here.
- Type attributeType = ctor.DeclaringType;
+ Type attributeType = ctor.DeclaringType!;
DllImportAttribute dia = _decoder.ComputeDllImportAttribute();
- CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.String], dia.Value) };
+ CustomAttributeTypedArgument[] cats = { new CustomAttributeTypedArgument(ct[CoreType.String]!, dia.Value) };
CustomAttributeNamedArgument[] cans =
{
attributeType.ToCustomAttributeNamedArgument(nameof(DllImportAttribute.EntryPoint), ct[CoreType.String], dia.EntryPoint),
internal abstract MethodSig<RoParameter> SpecializeMethodSig(IRoMethodBase member);
internal abstract MethodSig<RoType> SpecializeCustomModifiers(in TypeContext typeContext);
internal abstract MethodSig<string> SpecializeMethodSigStrings(in TypeContext typeContext);
- internal abstract MethodBody SpecializeMethodBody(IRoMethodBase owner);
+ internal abstract MethodBody? SpecializeMethodBody(IRoMethodBase owner);
}
/// <summary>
if ((MethodImplementationFlags & MethodImplAttributes.PreserveSig) != 0)
{
- ConstructorInfo ci = Loader.TryGetPreserveSigCtor();
+ ConstructorInfo? ci = Loader.TryGetPreserveSigCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
- CustomAttributeData dllImportCustomAttribute = ComputeDllImportCustomAttributeDataIfAny();
+ CustomAttributeData? dllImportCustomAttribute = ComputeDllImportCustomAttributeDataIfAny();
if (dllImportCustomAttribute != null)
yield return dllImportCustomAttribute;
}
protected sealed override CallingConventions ComputeCallingConvention() => _decoder.ComputeCallingConvention();
protected sealed override MethodImplAttributes ComputeMethodImplementationFlags() => _decoder.ComputeMethodImplementationFlags();
protected sealed override MethodSig<RoParameter> ComputeMethodSig() => _decoder.SpecializeMethodSig(this);
- public sealed override MethodBody GetMethodBody() => _decoder.SpecializeMethodBody(this);
+ public sealed override MethodBody? GetMethodBody() => _decoder.SpecializeMethodBody(this);
protected sealed override MethodSig<string> ComputeMethodSigStrings() => _decoder.SpecializeMethodSigStrings(TypeContext);
protected sealed override MethodSig<RoType> ComputeCustomModifiers() => _decoder.SpecializeCustomModifiers(TypeContext);
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoDefinitionMethod<TMethodDecoder> other))
return false;
internal sealed override MethodSig<RoParameter> SpecializeMethodSig(IRoMethodBase member) => _decoder.SpecializeMethodSig(member);
internal sealed override MethodSig<RoType> SpecializeCustomModifiers(in TypeContext typeContext) => _decoder.SpecializeCustomModifiers(typeContext);
internal sealed override MethodSig<string> SpecializeMethodSigStrings(in TypeContext typeContext) => _decoder.SpecializeMethodSigStrings(typeContext);
- internal sealed override MethodBody SpecializeMethodBody(IRoMethodBase owner) => _decoder.SpecializeMethodBody(owner);
+ internal sealed override MethodBody? SpecializeMethodBody(IRoMethodBase owner) => _decoder.SpecializeMethodBody(owner);
public sealed override TypeContext TypeContext => new TypeContext(_declaringType.Instantiation, GetGenericTypeParametersNoCopy());
}
_reflectedType = reflectedType;
}
- public abstract override bool Equals(object obj);
+ public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public sealed override Type DeclaringType => GetRoDeclaringType();
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
public sealed override Module Module => GetRoModule();
internal abstract RoModule GetRoModule();
private volatile MethodImplAttributes _lazyMethodImplAttributes = MethodImplAttributesSentinel;
public sealed override MethodImplAttributes GetMethodImplementationFlags() => MethodImplementationFlags;
- public abstract override MethodBody GetMethodBody();
+ public abstract override MethodBody? GetMethodBody();
public sealed override bool ContainsGenericParameters
{
private MethodSig<RoParameter> MethodSig => _lazyMethodSig ?? (_lazyMethodSig = ComputeMethodSig());
protected abstract MethodSig<RoParameter> ComputeMethodSig();
- private volatile MethodSig<RoParameter> _lazyMethodSig;
+ private volatile MethodSig<RoParameter>? _lazyMethodSig;
private MethodSig<RoType> CustomModifiers => _lazyCustomModifiers ?? (_lazyCustomModifiers = ComputeCustomModifiers());
protected abstract MethodSig<RoType> ComputeCustomModifiers();
- private volatile MethodSig<RoType> _lazyCustomModifiers;
+ private volatile MethodSig<RoType>? _lazyCustomModifiers;
public sealed override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter;
public sealed override Type ReturnType => ReturnParameter.ParameterType;
public sealed override Type[] GetGenericArguments() => GetGenericArgumentsOrParametersNoCopy().CloneArray<Type>();
internal RoType[] GetGenericArgumentsOrParametersNoCopy() => _lazyGenericArgumentsOrParameters ?? (_lazyGenericArgumentsOrParameters = ComputeGenericArgumentsOrParameters());
protected abstract RoType[] ComputeGenericArgumentsOrParameters();
- private volatile RoType[] _lazyGenericArgumentsOrParameters;
+ private volatile RoType[]? _lazyGenericArgumentsOrParameters;
internal abstract RoType[] GetGenericTypeParametersNoCopy();
internal abstract RoType[] GetGenericTypeArgumentsNoCopy();
public sealed override bool IsSecurityTransparent => throw new InvalidOperationException(SR.InvalidOperation_IsSecurity);
// Not valid in a ReflectionOnly context
- public sealed override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
+ public sealed override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
public sealed override Delegate CreateDelegate(Type delegateType) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override Delegate CreateDelegate(Type delegateType, object target) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override Delegate CreateDelegate(Type delegateType, object? target) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override RuntimeMethodHandle MethodHandle => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
MethodBase IRoMethodBase.MethodBase => this;
return sig;
}
- public sealed override MethodBody GetMethodBody() => null;
+ public sealed override MethodBody? GetMethodBody() => null;
protected sealed override MethodSig<string> ComputeMethodSigStrings()
{
protected sealed override MethodSig<RoType> ComputeCustomModifiers() => new MethodSig<RoType>(_parameterTypes.Length);
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoSyntheticMethod other))
return false;
/// If a type is not contained or forwarded from the assembly, this method returns null (does not throw.)
/// This supports the "throwOnError: false" behavior of Module.GetType(string, bool).
/// </summary>
- protected sealed override RoDefinitionType GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception e)
+ protected sealed override RoDefinitionType? GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception? e)
{
MetadataReader reader = Reader;
if (!(et.Namespace.Equals(ns, reader)))
continue;
- RoAssembly assembly = ((AssemblyReferenceHandle)implementation).TryResolveAssembly(this, out e);
+ RoAssembly? assembly = ((AssemblyReferenceHandle)implementation).TryResolveAssembly(this, out e);
return assembly?.GetTypeCore(ns, name, ignoreCase: false, out e);
}
result.ResourceLocation = ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile;
PEReader pe = _guardedPEReader.PEReader;
- PEMemoryBlock resourceDirectory = pe.GetSectionData(pe.PEHeaders.CorHeader.ResourcesDirectory.RelativeVirtualAddress);
+ PEMemoryBlock resourceDirectory = pe.GetSectionData(pe.PEHeaders.CorHeader!.ResourcesDirectory.RelativeVirtualAddress);
BlobReader blobReader = resourceDirectory.GetReader((int)resource.Offset, resourceDirectory.Length - (int)resource.Offset);
uint length = blobReader.ReadUInt32();
result.PointerToResource = blobReader.CurrentPointer;
result.FileName = file.Name.GetString(reader);
if (file.ContainsMetadata)
{
- EcmaModule module = (EcmaModule)Assembly.GetModule(result.FileName);
+ EcmaModule? module = (EcmaModule?)Assembly.GetModule(result.FileName);
if (module == null)
throw new BadImageFormatException(SR.Format(SR.ManifestResourceInfoReferencedBadModule, result.FileName));
result = module.GetInternalManifestResourceInfo(resourceName);
_lazyTypeDefTable;
}
}
- private volatile MetadataTable<EcmaDefinitionType, EcmaModule> _lazyTypeDefTable;
+ private volatile MetadataTable<EcmaDefinitionType, EcmaModule>? _lazyTypeDefTable;
private void EnsureTypeDefTableFullyFilled()
{
_lazyTypeRefTable;
}
}
- private volatile MetadataTable<RoDefinitionType, EcmaModule> _lazyTypeRefTable;
+ private volatile MetadataTable<RoDefinitionType, EcmaModule>? _lazyTypeRefTable;
internal MetadataTable<EcmaGenericParameterType, EcmaModule> GenericParamTable
{
_lazyGenericParamTable;
}
}
- private volatile MetadataTable<EcmaGenericParameterType, EcmaModule> _lazyGenericParamTable;
+ private volatile MetadataTable<EcmaGenericParameterType, EcmaModule>? _lazyGenericParamTable;
internal MetadataTable<RoAssembly, EcmaModule> AssemblyRefTable
{
_lazyAssemblyRefTable;
}
}
- private volatile MetadataTable<RoAssembly, EcmaModule> _lazyAssemblyRefTable;
+ private volatile MetadataTable<RoAssembly, EcmaModule>? _lazyAssemblyRefTable;
private MetadataTable<T, EcmaModule> CreateTable<T>(TableIndex tableIndex) where T : class
{
public bool IsSystemType(RoType type) => type == Loader.TryGetCoreType(CoreType.Type);
public PrimitiveTypeCode GetUnderlyingEnumType(RoType type) => type.GetEnumUnderlyingPrimitiveTypeCode(Loader);
- public RoType GetTypeFromSerializedName(string name)
+ public RoType GetTypeFromSerializedName(string? name)
{
// Called when an attribute argument is of type System.Type ([MyAttribute(typeof(Foo))]
// Parse an assembly-qualified name as Assembly.GetType() does. If the assembly part is missing, search in _module (the
// module in which the custom attribute metadata was found.)
if (name == null)
- return null; // This gets hit if the custom attribute passes "(Type)null"
- return Helpers.LoadTypeFromAssemblyQualifiedName(name, GetRoAssembly(), ignoreCase: false, throwOnError: true);
+ return null!; // This gets hit if the custom attribute passes "(Type)null"
+ return Helpers.LoadTypeFromAssemblyQualifiedName(name, GetRoAssembly(), ignoreCase: false, throwOnError: true)!;
}
}
}
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => ModuleDefinition.GetCustomAttributes().ToTrueCustomAttributes(this);
- internal MethodInfo ComputeEntryPoint(bool fileRefEntryPointAllowed)
+ internal MethodInfo? ComputeEntryPoint(bool fileRefEntryPointAllowed)
{
PEHeaders peHeaders = PEReader.PEHeaders;
- CorHeader corHeader = peHeaders.CorHeader;
+ CorHeader corHeader = peHeaders.CorHeader!;
if ((corHeader.Flags & CorFlags.NativeEntryPoint) != 0)
return null;
MetadataReader reader = Reader;
string moduleName = ((AssemblyFileHandle)handle).GetAssemblyFile(reader).Name.GetString(reader);
- EcmaModule roModule = (EcmaModule)(Assembly.GetModule(moduleName));
- return roModule.ComputeEntryPoint(fileRefEntryPointAllowed: false);
+ EcmaModule? roModule = (EcmaModule?)(Assembly.GetModule(moduleName));
+ return roModule!.ComputeEntryPoint(fileRefEntryPointAllowed: false);
}
default:
public sealed override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
PEHeaders peHeaders = PEReader.PEHeaders;
- PEMagic peMagic = peHeaders.PEHeader.Magic;
+ PEMagic peMagic = peHeaders.PEHeader!.Magic;
Machine coffMachine = peHeaders.CoffHeader.Machine;
- CorFlags corFlags = peHeaders.CorHeader.Flags;
+ CorFlags corFlags = peHeaders.CorHeader!.Flags;
peKind = default;
if ((corFlags & CorFlags.ILOnly) != 0)
//
// Search for members on <Module> type.
//
- public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) => GetModuleType().GetField(name, bindingAttr);
+ public sealed override FieldInfo? GetField(string name, BindingFlags bindingAttr) => GetModuleType().GetField(name, bindingAttr);
public sealed override FieldInfo[] GetFields(BindingFlags bindingFlags) => GetModuleType().GetFields(bindingFlags);
public sealed override MethodInfo[] GetMethods(BindingFlags bindingFlags) => GetModuleType().GetMethods(bindingFlags);
- protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => GetModuleType().InternalGetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
+ protected sealed override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => GetModuleType().InternalGetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
private RoType GetModuleType() => ModuleTypeToken.ToTypeDefinitionHandle().ResolveTypeDef(this);
public sealed override Type[] GetTypes()
return TypeDefTable.ToArray<Type>(skip: 1); // 0x02000001 is the <Module> type which is always skipped by this api.
}
- internal sealed override IEnumerable<RoType> GetDefinedRoTypes()
+ internal sealed override IEnumerable<RoType>? GetDefinedRoTypes()
{
EnsureTypeDefTableFullyFilled();
- return TypeDefTable.EnumerateValues(skip: 1); // 0x02000001 is the <Module> type which is always skipped by this api.
+ return TypeDefTable.EnumerateValues(skip: 1)!; // 0x02000001 is the <Module> type which is always skipped by this api.
}
internal PEReader PEReader => _guardedPEReader.PEReader;
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
namespace System.Reflection.TypeLoading
_container = new Container(this);
}
- public bool TryGet(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, out RoDefinitionType type)
+ public bool TryGet(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, [NotNullWhen(true)] out RoDefinitionType? type)
{
return _container.TryGetValue(ns, name, hashCode, out type);
}
public RoDefinitionType GetOrAdd(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, RoDefinitionType type)
{
- bool found = _container.TryGetValue(ns, name, hashCode, out RoDefinitionType prior);
- if (found)
+ if ( _container.TryGetValue(ns, name, hashCode, out RoDefinitionType? prior))
return prior;
Monitor.Enter(_lock);
try
{
- if (_container.TryGetValue(ns, name, hashCode, out RoDefinitionType winner))
+ if (_container.TryGetValue(ns, name, hashCode, out RoDefinitionType? winner))
return winner;
if (!_container.HasCapacity)
_container.Resize(); // This overwrites the _container field.
_owner = owner;
}
- public bool TryGetValue(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, out RoDefinitionType value)
+ public bool TryGetValue(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, int hashCode, [NotNullWhen(true)] out RoDefinitionType? value)
{
// Lock acquistion NOT required.
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
- public abstract override FieldInfo GetField(string name, BindingFlags bindingAttr);
+ public abstract override FieldInfo? GetField(string name, BindingFlags bindingAttr);
public abstract override FieldInfo[] GetFields(BindingFlags bindingFlags);
public abstract override MethodInfo[] GetMethods(BindingFlags bindingFlags);
- protected abstract override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
+ protected abstract override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers);
public sealed override void GetObjectData(SerializationInfo info, StreamingContext context) => throw new NotSupportedException();
public abstract override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine);
public abstract override Type[] GetTypes();
- internal abstract IEnumerable<RoType> GetDefinedRoTypes();
+ internal abstract IEnumerable<RoType>? GetDefinedRoTypes();
public abstract override bool IsResource();
- public sealed override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
- public sealed override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
- public sealed override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
+ public sealed override FieldInfo ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
+ public sealed override MemberInfo ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
+ public sealed override MethodBase ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
public sealed override byte[] ResolveSignature(int metadataToken) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
public sealed override string ResolveString(int metadataToken) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
- public sealed override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
+ public sealed override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) => throw new NotSupportedException(SR.NotSupported_ResolvingTokens);
- public sealed override Type GetType(string className, bool throwOnError, bool ignoreCase)
+ public sealed override Type? GetType(string className, bool throwOnError, bool ignoreCase)
{
//
// This looks bogus and against the intended meaning of the api but it's pretty close to the .NET Framework behavior.
// *only* as long as it's a generic type argument, not the top level type. If you specify the name of a type in a
// different module as the top level type, this api returns null (even if throwOnError is specified as true!)
//
- Type type = Assembly.GetType(className, throwOnError: throwOnError, ignoreCase: ignoreCase);
+ Type type = Assembly.GetType(className, throwOnError: throwOnError, ignoreCase: ignoreCase)!;
if (type.Module != this)
{
// We should throw if throwOnError == true, but .NET Framework doesn't so we'll keep the same behavior for the few people using this.
/// If a type is not contained or forwarded from the module, this method returns null (does not throw.)
/// This supports the "throwOnError: false" behavior of Module.GetType(string, bool).
/// </summary>
- internal RoDefinitionType GetTypeCore(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, bool ignoreCase, out Exception e)
+ internal RoDefinitionType? GetTypeCore(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, bool ignoreCase, out Exception? e)
{
if (ignoreCase)
throw new NotSupportedException(SR.NotSupported_CaseInsensitive);
int hashCode = GetTypeCoreCache.ComputeHashCode(name);
- if (!_getTypeCoreCache.TryGet(ns, name, hashCode, out RoDefinitionType type))
+ if (!_getTypeCoreCache.TryGet(ns, name, hashCode, out RoDefinitionType? type))
{
type = GetTypeCoreNoCache(ns, name, out e) ?? new RoExceptionType(ns, name, e);
_getTypeCoreCache.GetOrAdd(ns, name, hashCode, type); // Type objects are unified independently of this cache so no need to check if we won the race to cache this Type
e = null;
return type;
}
- protected abstract RoDefinitionType GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception e);
+ protected abstract RoDefinitionType? GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception? e);
internal readonly GetTypeCoreCache _getTypeCoreCache = new GetTypeCoreCache();
internal MetadataLoadContext Loader => GetRoAssembly().Loader;
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => Array.Empty<CustomAttributeData>();
- public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) => null;
+ public sealed override FieldInfo? GetField(string name, BindingFlags bindingAttr) => null;
public sealed override FieldInfo[] GetFields(BindingFlags bindingFlags) => Array.Empty<FieldInfo>();
public sealed override MethodInfo[] GetMethods(BindingFlags bindingFlags) => Array.Empty<MethodInfo>();
- protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => null;
+ protected sealed override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => null;
public sealed override bool IsResource() => true;
public sealed override Type[] GetTypes() => Array.Empty<Type>();
- protected sealed override RoDefinitionType GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception e)
+ protected sealed override RoDefinitionType? GetTypeCoreNoCache(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, out Exception? e)
{
e = new TypeLoadException(SR.Format(SR.TypeNotFound, ns.ToUtf16().AppendTypeName(name.ToUtf16()), Assembly));
return null;
}
- internal sealed override IEnumerable<RoType> GetDefinedRoTypes() => null;
+ internal sealed override IEnumerable<RoType>? GetDefinedRoTypes() => null;
}
}
public sealed override int MetadataToken => _handle.GetToken();
- protected sealed override string ComputeName() => Parameter.Name.GetStringOrNull(Reader);
+ protected sealed override string? ComputeName() => Parameter.Name.GetStringOrNull(Reader);
protected sealed override ParameterAttributes ComputeAttributes() => Parameter.Attributes;
protected sealed override IEnumerable<CustomAttributeData> GetTrueCustomAttributes() => Parameter.GetCustomAttributes().ToTrueCustomAttributes(GetEcmaModule());
public sealed override bool HasDefaultValue => TryGetRawDefaultValue(out object _);
- public sealed override object RawDefaultValue
+ public sealed override object? RawDefaultValue
{
get
{
- if (TryGetRawDefaultValue(out object rawDefaultValue))
+ if (TryGetRawDefaultValue(out object? rawDefaultValue))
return rawDefaultValue;
return IsOptional ? (object)Missing.Value : (object)DBNull.Value;
}
}
- private bool TryGetRawDefaultValue(out object rawDefaultValue)
+ private bool TryGetRawDefaultValue(out object? rawDefaultValue)
{
rawDefaultValue = null;
MetadataReader reader = Reader;
Debug.Assert(parameterType != null);
}
- public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
- protected abstract string ComputeName();
- private volatile string _lazyName;
+ public sealed override string? Name => _lazyName ?? (_lazyName = ComputeName());
+ protected abstract string? ComputeName();
+ private volatile string? _lazyName;
public sealed override ParameterAttributes Attributes => (_lazyParameterAttributes == ParameterAttributesSentinel) ? (_lazyParameterAttributes = ComputeAttributes()) : _lazyParameterAttributes;
protected abstract ParameterAttributes ComputeAttributes();
ParameterAttributes attributes = Attributes;
if (0 != (attributes & ParameterAttributes.In))
{
- ConstructorInfo ci = Loader.TryGetInCtor();
+ ConstructorInfo? ci = Loader.TryGetInCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
if (0 != (attributes & ParameterAttributes.Out))
{
- ConstructorInfo ci = Loader.TryGetOutCtor();
+ ConstructorInfo? ci = Loader.TryGetOutCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
if (0 != (attributes & ParameterAttributes.Optional))
{
- ConstructorInfo ci = Loader.TryGetOptionalCtor();
+ ConstructorInfo? ci = Loader.TryGetOptionalCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
if (0 != (attributes & ParameterAttributes.HasFieldMarshal))
{
- CustomAttributeData cad = CustomAttributeHelpers.TryComputeMarshalAsCustomAttributeData(ComputeMarshalAsAttribute, Loader);
+ CustomAttributeData? cad = CustomAttributeHelpers.TryComputeMarshalAsCustomAttributeData(ComputeMarshalAsAttribute, Loader);
if (cad != null)
yield return cad;
}
protected abstract MarshalAsAttribute ComputeMarshalAsAttribute();
public abstract override bool HasDefaultValue { get; }
- public abstract override object RawDefaultValue { get; }
+ public abstract override object? RawDefaultValue { get; }
protected abstract IEnumerable<CustomAttributeData> GetTrueCustomAttributes();
public sealed override int Position => _position;
public abstract override int MetadataToken { get; }
- public abstract override string Name { get; }
+ public abstract override string? Name { get; }
public abstract override Type ParameterType { get; }
public abstract override ParameterAttributes Attributes { get; }
public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection();
public abstract override bool HasDefaultValue { get; }
public sealed override object DefaultValue => throw new InvalidOperationException(SR.Arg_ReflectionOnlyParameterDefaultValue);
- public abstract override object RawDefaultValue { get; }
+ public abstract override object? RawDefaultValue { get; }
public abstract override Type[] GetOptionalCustomModifiers();
public abstract override Type[] GetRequiredCustomModifiers();
public abstract override string ToString();
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is RoParameter other))
return false;
}
public sealed override int MetadataToken => _backingParameter.MetadataToken;
- public sealed override string Name => _backingParameter.Name;
+ public sealed override string? Name => _backingParameter.Name;
public sealed override Type ParameterType => _backingParameter.ParameterType;
public sealed override ParameterAttributes Attributes => _backingParameter.Attributes;
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => _backingParameter.CustomAttributes;
public sealed override bool HasDefaultValue => _backingParameter.HasDefaultValue;
- public sealed override object RawDefaultValue => _backingParameter.RawDefaultValue;
+ public sealed override object? RawDefaultValue => _backingParameter.RawDefaultValue;
public sealed override Type[] GetOptionalCustomModifiers() => _backingParameter.GetOptionalCustomModifiers();
public sealed override Type[] GetRequiredCustomModifiers() => _backingParameter.GetRequiredCustomModifiers();
public sealed override string ToString() => _backingParameter.ToString();
Debug.Assert(parameterType != null);
}
- public sealed override string Name => null;
+ public sealed override string? Name => null;
public sealed override ParameterAttributes Attributes => ParameterAttributes.None;
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => Array.Empty<CustomAttributeData>();
// Returning "null" matches the .NET Framework behavior, though this is inconsistent with the DBNull/Missing values
// returned by fat ParameterInfo's without default values.
- public sealed override object RawDefaultValue => null;
+ public sealed override object? RawDefaultValue => null;
}
}
public sealed override int MetadataToken => _handle.GetToken();
- public sealed override bool Equals(object obj)
+ public sealed override bool Equals(object? obj)
{
if (!(obj is EcmaProperty other))
return false;
protected sealed override PropertyAttributes ComputeAttributes() => PropertyDefinition.Attributes;
protected sealed override Type ComputePropertyType() => PropertyDefinition.DecodeSignature(_module, TypeContext).ReturnType;
- protected sealed override object ComputeRawConstantValue() => PropertyDefinition.GetDefaultValue().ToRawObject(Reader);
+ protected sealed override object? ComputeRawConstantValue() => PropertyDefinition.GetDefaultValue().ToRawObject(Reader);
public sealed override Type[] GetOptionalCustomModifiers() => GetCustomModifiers(isRequired: false);
public sealed override Type[] GetRequiredCustomModifiers() => GetCustomModifiers(isRequired: true);
public sealed override string ToString()
{
- string disposedString = Loader.GetDisposedString();
+ string? disposedString = Loader.GetDisposedString();
if (disposedString != null)
return disposedString;
return sb.ToString();
}
- protected sealed override RoMethod ComputeGetterMethod() => PropertyDefinition.GetAccessors().Getter.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
- protected sealed override RoMethod ComputeSetterMethod() => PropertyDefinition.GetAccessors().Setter.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
+ protected sealed override RoMethod? ComputeGetterMethod() => PropertyDefinition.GetAccessors().Getter.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
+ protected sealed override RoMethod? ComputeSetterMethod() => PropertyDefinition.GetAccessors().Setter.ToMethodOrNull(GetRoDeclaringType(), ReflectedType);
private MetadataReader Reader => _module.Reader;
private MetadataLoadContext Loader => GetRoModule().Loader;
_reflectedType = reflectedType;
}
- public abstract override bool Equals(object obj);
+ public abstract override bool Equals(object? obj);
public abstract override int GetHashCode();
public abstract override string ToString();
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
public sealed override Module Module => GetRoModule();
internal abstract RoModule GetRoModule();
public sealed override Type PropertyType => _lazyPropertyType ?? (_lazyPropertyType = ComputePropertyType());
protected abstract Type ComputePropertyType();
- private volatile Type _lazyPropertyType;
+ private volatile Type? _lazyPropertyType;
- public sealed override MethodInfo GetGetMethod(bool nonPublic) => GetRoGetMethod()?.FilterAccessor(nonPublic);
- public sealed override MethodInfo GetSetMethod(bool nonPublic) => GetRoSetMethod()?.FilterAccessor(nonPublic);
+ public sealed override MethodInfo? GetGetMethod(bool nonPublic) => GetRoGetMethod()?.FilterAccessor(nonPublic);
+ public sealed override MethodInfo? GetSetMethod(bool nonPublic) => GetRoSetMethod()?.FilterAccessor(nonPublic);
- private RoMethod GetRoGetMethod() => object.ReferenceEquals(_lazyGetter, Sentinels.RoMethod) ? (_lazyGetter = ComputeGetterMethod()?.FilterInheritedAccessor()) : _lazyGetter;
- private RoMethod GetRoSetMethod() => object.ReferenceEquals(_lazySetter, Sentinels.RoMethod) ? (_lazySetter = ComputeSetterMethod()?.FilterInheritedAccessor()) : _lazySetter;
+ private RoMethod? GetRoGetMethod() => object.ReferenceEquals(_lazyGetter, Sentinels.RoMethod) ? (_lazyGetter = ComputeGetterMethod()?.FilterInheritedAccessor()) : _lazyGetter;
+ private RoMethod? GetRoSetMethod() => object.ReferenceEquals(_lazySetter, Sentinels.RoMethod) ? (_lazySetter = ComputeSetterMethod()?.FilterInheritedAccessor()) : _lazySetter;
- protected abstract RoMethod ComputeGetterMethod();
- protected abstract RoMethod ComputeSetterMethod();
+ protected abstract RoMethod? ComputeGetterMethod();
+ protected abstract RoMethod? ComputeSetterMethod();
- private volatile RoMethod _lazyGetter = Sentinels.RoMethod;
- private volatile RoMethod _lazySetter = Sentinels.RoMethod;
+ private volatile RoMethod? _lazyGetter = Sentinels.RoMethod;
+ private volatile RoMethod? _lazySetter = Sentinels.RoMethod;
public sealed override bool CanRead => GetMethod != null;
public sealed override bool CanWrite => SetMethod != null;
public sealed override MethodInfo[] GetAccessors(bool nonPublic)
{
- MethodInfo getter = GetGetMethod(nonPublic);
- MethodInfo setter = GetSetMethod(nonPublic);
+ MethodInfo? getter = GetGetMethod(nonPublic);
+ MethodInfo? setter = GetSetMethod(nonPublic);
int count = 0;
if (getter != null)
private RoPropertyIndexParameter[] ComputeIndexParameters()
{
bool useGetter = CanRead;
- RoMethod accessor = (useGetter ? GetRoGetMethod() : GetRoSetMethod());
+ RoMethod? accessor = (useGetter ? GetRoGetMethod() : GetRoSetMethod());
if (accessor == null)
throw new BadImageFormatException(); // Property has neither a getter or setter.
RoParameter[] methodParameters = accessor.GetParametersNoCopy();
}
return indexParameters;
}
- private volatile RoPropertyIndexParameter[] _lazyIndexedParameters;
+ private volatile RoPropertyIndexParameter[]? _lazyIndexedParameters;
- public sealed override object GetRawConstantValue()
+ public sealed override object? GetRawConstantValue()
{
if ((Attributes & PropertyAttributes.HasDefault) == 0)
throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
return ComputeRawConstantValue();
}
- protected abstract object ComputeRawConstantValue();
+ protected abstract object? ComputeRawConstantValue();
public abstract override Type[] GetOptionalCustomModifiers();
public abstract override Type[] GetRequiredCustomModifiers();
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
public sealed override object GetConstantValue() => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
- public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override object GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
+ public sealed override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
internal TypeContext TypeContext => _declaringType.Instantiation.ToTypeContext();
}
{
public sealed override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) => Query<ConstructorInfo>(bindingAttr).ToArray();
- protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected sealed override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
Debug.Assert(types != null);
}
public sealed override EventInfo[] GetEvents(BindingFlags bindingAttr) => Query<EventInfo>(bindingAttr).ToArray();
- public sealed override EventInfo GetEvent(string name, BindingFlags bindingAttr) => Query<EventInfo>(name, bindingAttr).Disambiguate();
+ public sealed override EventInfo? GetEvent(string name, BindingFlags bindingAttr) => Query<EventInfo>(name, bindingAttr).Disambiguate();
public sealed override FieldInfo[] GetFields(BindingFlags bindingAttr) => Query<FieldInfo>(bindingAttr).ToArray();
- public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) => Query<FieldInfo>(name, bindingAttr).Disambiguate();
+ public sealed override FieldInfo? GetField(string name, BindingFlags bindingAttr) => Query<FieldInfo>(name, bindingAttr).Disambiguate();
public sealed override MethodInfo[] GetMethods(BindingFlags bindingAttr) => Query<MethodInfo>(bindingAttr).ToArray();
- protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected sealed override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodImplCommon(name, GenericParameterCountAny, bindingAttr, binder, callConvention, types, modifiers);
}
- protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ protected sealed override MethodInfo? GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers);
}
- private MethodInfo GetMethodImplCommon(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ private MethodInfo? GetMethodImplCommon(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
Debug.Assert(name != null);
}
public sealed override Type[] GetNestedTypes(BindingFlags bindingAttr) => Query<Type>(bindingAttr).ToArray();
- public sealed override Type GetNestedType(string name, BindingFlags bindingAttr) => Query<Type>(name, bindingAttr).Disambiguate();
+ public sealed override Type? GetNestedType(string name, BindingFlags bindingAttr) => Query<Type>(name, bindingAttr).Disambiguate();
public sealed override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => Query<PropertyInfo>(bindingAttr).ToArray();
- protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+ protected sealed override PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers)
{
Debug.Assert(name != null);
return Query<M>(name, bindingAttr, null);
}
- private QueryResult<M> Query<M>(string optionalName, BindingFlags bindingAttr, Func<M, bool> optionalPredicate) where M : MemberInfo
+ private QueryResult<M> Query<M>(string? optionalName, BindingFlags bindingAttr, Func<M, bool>? optionalPredicate) where M : MemberInfo
{
MemberPolicies<M> policies = MemberPolicies<M>.Default;
bindingAttr = policies.ModifyBindingFlags(bindingAttr);
private TypeComponentsCache Cache => _lazyCache ?? (_lazyCache = new TypeComponentsCache(this));
- private volatile TypeComponentsCache _lazyCache;
+ private volatile TypeComponentsCache? _lazyCache;
private const int GenericParameterCountAny = -1;
}
return GetMemberImpl(name, type, bindingAttr);
}
- private MemberInfo[] GetMemberImpl(string optionalNameOrPrefix, MemberTypes type, BindingFlags bindingAttr)
+ private MemberInfo[] GetMemberImpl(string? optionalNameOrPrefix, MemberTypes type, BindingFlags bindingAttr)
{
bool prefixSearch = optionalNameOrPrefix != null && optionalNameOrPrefix.EndsWith("*", StringComparison.Ordinal);
- string optionalName = prefixSearch ? null : optionalNameOrPrefix;
+ string? optionalName = prefixSearch ? null : optionalNameOrPrefix;
- Func<MemberInfo, bool> predicate = null;
+ Func<MemberInfo, bool>? predicate = null;
if (prefixSearch)
{
bool ignoreCase = (bindingAttr & BindingFlags.IgnoreCase) != 0;
StringComparison comparisonType = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
- string prefix = optionalNameOrPrefix.Substring(0, optionalNameOrPrefix.Length - 1);
+ string prefix = optionalNameOrPrefix!.Substring(0, optionalNameOrPrefix.Length - 1);
predicate = (member => member.Name.StartsWith(prefix, comparisonType));
}
- MemberInfo[] results;
+ MemberInfo[]? results;
if ((results = QuerySpecificMemberTypeIfRequested(type, optionalName, bindingAttr, predicate, MemberTypes.Method, out QueryResult<MethodInfo> methods)) != null)
return results;
return results;
}
- private M[] QuerySpecificMemberTypeIfRequested<M>(MemberTypes memberType, string optionalName, BindingFlags bindingAttr, Func<MemberInfo, bool> optionalPredicate, MemberTypes targetMemberType, out QueryResult<M> queryResult) where M : MemberInfo
+ private M[]? QuerySpecificMemberTypeIfRequested<M>(MemberTypes memberType, string? optionalName, BindingFlags bindingAttr, Func<MemberInfo, bool>? optionalPredicate, MemberTypes targetMemberType, out QueryResult<M> queryResult) where M : MemberInfo
{
if ((memberType & targetMemberType) == 0)
{
//
// - All GetConstructor() apis act as if BindingFlags.DeclaredOnly were specified. So the ReflectedType will always be the declaring type and so is not passed to this method.
//
- internal sealed override IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter filter, RoInstantiationProviderType declaringType)
+ internal sealed override IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter? filter, RoInstantiationProviderType declaringType)
{
MetadataReader reader = Reader;
foreach (MethodDefinitionHandle handle in TypeDefinition.GetMethods())
}
}
- internal sealed override IEnumerable<MethodInfo> SpecializeMethods(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType)
+ internal sealed override IEnumerable<MethodInfo> SpecializeMethods(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType)
{
MetadataReader reader = Reader;
foreach (MethodDefinitionHandle handle in TypeDefinition.GetMethods())
}
}
- internal sealed override IEnumerable<EventInfo> SpecializeEvents(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType)
+ internal sealed override IEnumerable<EventInfo> SpecializeEvents(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType)
{
MetadataReader reader = Reader;
foreach (EventDefinitionHandle handle in TypeDefinition.GetEvents())
}
}
- internal sealed override IEnumerable<FieldInfo> SpecializeFields(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType)
+ internal sealed override IEnumerable<FieldInfo> SpecializeFields(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType)
{
MetadataReader reader = Reader;
foreach (FieldDefinitionHandle handle in TypeDefinition.GetFields())
}
}
- internal sealed override IEnumerable<PropertyInfo> SpecializeProperties(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType)
+ internal sealed override IEnumerable<PropertyInfo> SpecializeProperties(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType)
{
MetadataReader reader = Reader;
foreach (PropertyDefinitionHandle handle in TypeDefinition.GetProperties())
}
}
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter)
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter)
{
MetadataReader reader = Reader;
foreach (TypeDefinitionHandle handle in TypeDefinition.GetNestedTypes())
}
}
- internal sealed override RoDefinitionType GetNestedTypeCore(ReadOnlySpan<byte> utf8Name)
+ internal sealed override RoDefinitionType? GetNestedTypeCore(ReadOnlySpan<byte> utf8Name)
{
- RoDefinitionType match = null;
+ RoDefinitionType? match = null;
MetadataReader reader = Reader;
foreach (TypeDefinitionHandle handle in TypeDefinition.GetNestedTypes())
{
internal sealed override RoModule GetRoModule() => _module;
internal EcmaModule GetEcmaModule() => _module;
- protected sealed override RoType ComputeDeclaringType()
+ protected sealed override RoType? ComputeDeclaringType()
{
if (!TypeDefinition.IsNested)
return null;
protected sealed override string ComputeName() => TypeDefinition.Name.GetString(Reader).EscapeTypeNameIdentifier();
- protected sealed override string ComputeNamespace()
+ protected sealed override string? ComputeNamespace()
{
- Type declaringType = DeclaringType;
+ Type? declaringType = DeclaringType;
if (declaringType != null)
return declaringType.Namespace;
return TypeDefinition.Namespace.GetStringOrNull(Reader)?.EscapeTypeNameIdentifier();
protected sealed override TypeAttributes ComputeAttributeFlags() => TypeDefinition.Attributes;
- internal sealed override RoType SpecializeBaseType(RoType[] instantiation)
+ internal sealed override RoType? SpecializeBaseType(RoType[] instantiation)
{
EntityHandle baseTypeHandle = TypeDefinition.BaseType;
if (baseTypeHandle.IsNil)
protected sealed override IEnumerable<CustomAttributeData> GetTrueCustomAttributes() => TypeDefinition.GetCustomAttributes().ToTrueCustomAttributes(GetEcmaModule());
internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => TypeDefinition.GetCustomAttributes().IsCustomAttributeDefined(ns, name, GetEcmaModule());
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => TypeDefinition.GetCustomAttributes().TryFindCustomAttribute(ns, name, GetEcmaModule());
+ internal sealed override CustomAttributeData? TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => TypeDefinition.GetCustomAttributes().TryFindCustomAttribute(ns, name, GetEcmaModule());
public sealed override int MetadataToken => _handle.GetToken();
}
return genericParameters;
}
- private volatile RoType[] _lazyGenericParameters;
+ private volatile RoType[]? _lazyGenericParameters;
protected internal sealed override RoType ComputeEnumUnderlyingType()
{
MetadataReader reader = Reader;
TypeContext typeContext = Instantiation.ToTypeContext();
- RoType underlyingType = null;
+ RoType? underlyingType = null;
foreach (FieldDefinitionHandle handle in TypeDefinition.GetFields())
{
FieldDefinition fd = handle.GetFieldDefinition(reader);
public sealed override MethodBase DeclaringMethod => GetRoDeclaringMethod();
private RoMethod GetRoDeclaringMethod() => _lazyDeclaringMethod ?? (_lazyDeclaringMethod = ComputeDeclaringMethod());
private RoMethod ComputeDeclaringMethod() => ((MethodDefinitionHandle)(GenericParameter.Parent)).ResolveMethod<RoMethod>(GetEcmaModule(), default);
- private volatile RoMethod _lazyDeclaringMethod;
+ private volatile RoMethod? _lazyDeclaringMethod;
protected sealed override TypeContext TypeContext => GetRoDeclaringMethod().TypeContext;
}
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => GenericParameter.GetCustomAttributes().ToTrueCustomAttributes(GetEcmaModule());
internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => GenericParameter.GetCustomAttributes().IsCustomAttributeDefined(ns, name, GetEcmaModule());
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => GenericParameter.GetCustomAttributes().TryFindCustomAttribute(ns, name, GetEcmaModule());
+ internal sealed override CustomAttributeData? TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => GenericParameter.GetCustomAttributes().TryFindCustomAttribute(ns, name, GetEcmaModule());
public sealed override int MetadataToken => Handle.GetToken();
return constraints;
}
- protected abstract override RoType ComputeDeclaringType();
- public abstract override MethodBase DeclaringMethod { get; }
+ protected abstract override RoType? ComputeDeclaringType();
+ public abstract override MethodBase? DeclaringMethod { get; }
internal GenericParameterHandle Handle { get; }
internal EcmaModule GetEcmaModule() => _ecmaModule;
public sealed override bool IsGenericTypeParameter => true;
public sealed override bool IsGenericMethodParameter => false;
- protected sealed override RoType ComputeDeclaringType()
+ protected sealed override RoType? ComputeDeclaringType()
{
TypeDefinitionHandle declaringTypeHandle = (TypeDefinitionHandle)(GenericParameter.Parent);
EcmaDefinitionType declaringType = declaringTypeHandle.ResolveTypeDef(GetEcmaModule());
return declaringType;
}
- public sealed override MethodBase DeclaringMethod => null;
+ public sealed override MethodBase? DeclaringMethod => null;
- protected sealed override TypeContext TypeContext => ((RoInstantiationProviderType)GetRoDeclaringType()).Instantiation.ToTypeContext();
+ protected sealed override TypeContext TypeContext => ((RoInstantiationProviderType)GetRoDeclaringType()!).Instantiation.ToTypeContext();
}
}
return true;
}
- public override bool Equals(object obj) => obj is Key other && Equals(other);
+ public override bool Equals(object? obj) => obj is Key other && Equals(other);
public override int GetHashCode() => ElementType.GetHashCode() ^ Rank.GetHashCode();
}
}
public sealed override int GetArrayRank() => _rank;
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => Loader.GetCoreType(CoreType.Array);
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk() => Loader.GetCoreType(CoreType.Array);
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces()
{
RoType[] typeArguments = { GetRoElementType() };
foreach (CoreType coreType in s_typesImplementedByArray)
{
- RoType ifc = Loader.TryGetCoreType(coreType);
+ RoType? ifc = Loader.TryGetCoreType(coreType);
if (ifc != null)
{
// All of our types are from a fixed list so we know they're supposed be generic interfaces taking one type parameter.
protected sealed override TypeAttributes ComputeAttributeFlags() => TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Serializable;
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter)
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter)
{
if (filter == null || filter.Matches(ConstructorInfo.ConstructorName))
{
}
yield return new RoSyntheticConstructor(this, uniquifier++, parameterTypes);
parameterCount++;
- elementType = elementType.GetRoElementType();
+ elementType = elementType.GetRoElementType()!;
}
}
}
}
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType)
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType)
{
int rank = _rank;
protected sealed override string Suffix => "&";
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => null;
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk() => null;
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => Array.Empty<RoType>();
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => Array.Empty<ConstructorInfo>();
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => Array.Empty<MethodInfo>();
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => Array.Empty<ConstructorInfo>();
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => Array.Empty<MethodInfo>();
}
}
return true;
}
- public override bool Equals(object obj) => obj is Key other && Equals(other);
+ public override bool Equals(object? obj) => obj is Key other && Equals(other);
public override int GetHashCode()
{
internal sealed override RoModule GetRoModule() => _genericTypeDefinition.GetRoModule();
protected sealed override string ComputeName() => _genericTypeDefinition.Name;
- protected sealed override string ComputeNamespace() => _genericTypeDefinition.Namespace;
+ protected sealed override string? ComputeNamespace() => _genericTypeDefinition.Namespace;
- protected sealed override string ComputeFullName()
+ protected sealed override string? ComputeFullName()
{
if (ContainsGenericParameters)
return null;
}
public sealed override MethodBase DeclaringMethod => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- protected sealed override RoType ComputeDeclaringType() => _genericTypeDefinition.GetRoDeclaringType();
+ protected sealed override RoType? ComputeDeclaringType() => _genericTypeDefinition.GetRoDeclaringType();
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => _genericTypeDefinition.SpecializeBaseType(Instantiation);
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk() => _genericTypeDefinition.SpecializeBaseType(Instantiation);
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => _genericTypeDefinition.SpecializeInterfaces(Instantiation);
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => _genericTypeDefinition.CustomAttributes;
internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => _genericTypeDefinition.IsCustomAttributeDefined(ns, name);
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => _genericTypeDefinition.TryFindCustomAttribute(ns, name);
+ internal sealed override CustomAttributeData? TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => _genericTypeDefinition.TryFindCustomAttribute(ns, name);
protected sealed override TypeAttributes ComputeAttributeFlags() => _genericTypeDefinition.Attributes;
protected sealed override TypeCode GetTypeCodeImpl() => Type.GetTypeCode(_genericTypeDefinition);
public sealed override int MetadataToken => _genericTypeDefinition.MetadataToken;
- internal sealed override RoType GetRoElementType() => null;
+ internal sealed override RoType? GetRoElementType() => null;
public sealed override Type GetGenericTypeDefinition() => _genericTypeDefinition;
internal sealed override RoType[] GetGenericTypeParametersNoCopy() => Array.Empty<RoType>();
public sealed override Type MakeGenericType(params Type[] typeArguments) => throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this));
public sealed override Guid GUID => _genericTypeDefinition.GUID;
- public sealed override StructLayoutAttribute StructLayoutAttribute => _genericTypeDefinition.StructLayoutAttribute;
+ public sealed override StructLayoutAttribute? StructLayoutAttribute => _genericTypeDefinition.StructLayoutAttribute;
protected internal sealed override RoType ComputeEnumUnderlyingType() => _genericTypeDefinition.ComputeEnumUnderlyingType(); // Easy to forget that generic enums do exist!
public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
public sealed override Type[] GetGenericParameterConstraints() => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
// Low level support for the BindingFlag-driven enumerator apis.
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => _genericTypeDefinition.SpecializeConstructors(filter, this);
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => _genericTypeDefinition.SpecializeMethods(filter, reflectedType, this);
- internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => _genericTypeDefinition.SpecializeEvents(filter, reflectedType, this);
- internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => _genericTypeDefinition.SpecializeFields(filter, reflectedType, this);
- internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => _genericTypeDefinition.SpecializeProperties(filter, reflectedType, this);
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter) => _genericTypeDefinition.GetNestedTypesCore(filter);
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => _genericTypeDefinition.SpecializeConstructors(filter, this);
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => _genericTypeDefinition.SpecializeMethods(filter, reflectedType, this);
+ internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType) => _genericTypeDefinition.SpecializeEvents(filter, reflectedType, this);
+ internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType) => _genericTypeDefinition.SpecializeFields(filter, reflectedType, this);
+ internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType) => _genericTypeDefinition.SpecializeProperties(filter, reflectedType, this);
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter) => _genericTypeDefinition.GetNestedTypesCore(filter);
internal sealed override RoType[] Instantiation => _genericTypeArguments;
}
string name = Name;
- Type declaringType = DeclaringType;
+ Type? declaringType = DeclaringType;
if (declaringType != null)
{
- string declaringTypeFullName = declaringType.FullName;
+ string? declaringTypeFullName = declaringType.FullName;
return declaringTypeFullName + "+" + name;
}
- string ns = Namespace;
+ string? ns = Namespace;
if (ns == null)
return name;
return ns + "." + name;
}
- public sealed override string ToString() => Loader.GetDisposedString() ?? FullName;
+ public sealed override string ToString() => Loader.GetDisposedString() ?? FullName!;
internal abstract int GetGenericParameterCount();
internal abstract override RoType[] GetGenericTypeParametersNoCopy();
if (0 != (Attributes & TypeAttributes.Import))
{
- ConstructorInfo ci = Loader.TryGetComImportCtor();
+ ConstructorInfo? ci = Loader.TryGetComImportCtor();
if (ci != null)
yield return new RoPseudoCustomAttributeData(ci);
}
public sealed override Type GetGenericTypeDefinition() => IsGenericTypeDefinition ? this : throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => SpecializeBaseType(Instantiation);
- internal abstract RoType SpecializeBaseType(RoType[] instantiation);
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk() => SpecializeBaseType(Instantiation);
+ internal abstract RoType? SpecializeBaseType(RoType[] instantiation);
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => SpecializeInterfaces(Instantiation);
internal abstract IEnumerable<RoType> SpecializeInterfaces(RoType[] instantiation);
{
get
{
- CustomAttributeData cad = TryFindCustomAttribute(Utf8Constants.SystemRuntimeInteropServices, Utf8Constants.GuidAttribute);
+ CustomAttributeData? cad = TryFindCustomAttribute(Utf8Constants.SystemRuntimeInteropServices, Utf8Constants.GuidAttribute);
if (cad == null)
return default;
IList<CustomAttributeTypedArgument> ctas = cad.ConstructorArguments;
}
}
- public sealed override StructLayoutAttribute StructLayoutAttribute
+ public sealed override StructLayoutAttribute? StructLayoutAttribute
{
get
{
return TypeCode.Object;
}
- internal sealed override RoType GetRoElementType() => null;
+ internal sealed override RoType? GetRoElementType() => null;
public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => Array.Empty<RoType>();
protected internal sealed override RoType[] GetGenericArgumentsNoCopy() => GetGenericTypeParametersNoCopy();
public sealed override Type[] GetGenericParameterConstraints() => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public sealed override MethodBase DeclaringMethod => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => SpecializeConstructors(filter, this);
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => SpecializeMethods(filter, reflectedType, this);
- internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => SpecializeEvents(filter, reflectedType, this);
- internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => SpecializeFields(filter, reflectedType, this);
- internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => SpecializeProperties(filter, reflectedType, this);
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => SpecializeConstructors(filter, this);
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => SpecializeMethods(filter, reflectedType, this);
+ internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType) => SpecializeEvents(filter, reflectedType, this);
+ internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType) => SpecializeFields(filter, reflectedType, this);
+ internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType) => SpecializeProperties(filter, reflectedType, this);
// Like CoreGetDeclared but allows specifying an alternate declaringType (which must be a generic instantiation of the true declaring type)
- internal abstract IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter filter, RoInstantiationProviderType declaringType);
- internal abstract IEnumerable<MethodInfo> SpecializeMethods(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
- internal abstract IEnumerable<EventInfo> SpecializeEvents(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
- internal abstract IEnumerable<FieldInfo> SpecializeFields(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
- internal abstract IEnumerable<PropertyInfo> SpecializeProperties(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType);
+ internal abstract IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter? filter, RoInstantiationProviderType declaringType);
+ internal abstract IEnumerable<MethodInfo> SpecializeMethods(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType);
+ internal abstract IEnumerable<EventInfo> SpecializeEvents(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType);
+ internal abstract IEnumerable<FieldInfo> SpecializeFields(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType);
+ internal abstract IEnumerable<PropertyInfo> SpecializeProperties(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType);
// Helpers for the typeref-resolution/name lookup logic.
internal abstract bool IsTypeNameEqual(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
- internal abstract RoDefinitionType GetNestedTypeCore(ReadOnlySpan<byte> utf8Name);
+ internal abstract RoDefinitionType? GetNestedTypeCore(ReadOnlySpan<byte> utf8Name);
internal sealed override RoType[] Instantiation => GetGenericTypeParametersNoCopy();
}
{
private readonly byte[] _ns;
private readonly byte[] _name;
- internal Exception Exception { get; }
+ internal Exception? Exception { get; }
- internal RoExceptionType(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, Exception exception)
+ internal RoExceptionType(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name, Exception? exception)
: base()
{
_ns = ns.ToArray();
internal sealed override bool IsTypeNameEqual(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => name.SequenceEqual(_name) && ns.SequenceEqual(_ns);
- public sealed override bool IsGenericTypeDefinition => throw null;
- public sealed override int MetadataToken => throw null;
- internal sealed override RoModule GetRoModule() => throw null;
- protected sealed override string ComputeName() => throw null;
- protected sealed override string ComputeNamespace() => throw null;
- protected sealed override TypeAttributes ComputeAttributeFlags() => throw null;
- protected sealed override RoType ComputeDeclaringType() => throw null;
- internal sealed override int GetGenericParameterCount() => throw null;
- internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null;
- internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null;
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null;
- protected sealed override IEnumerable<CustomAttributeData> GetTrueCustomAttributes() => throw null;
- protected sealed override void GetPackSizeAndSize(out int packSize, out int size) => throw null;
- protected internal sealed override RoType ComputeEnumUnderlyingType() => throw null;
- internal sealed override RoType SpecializeBaseType(RoType[] instantiation) => throw null;
- internal sealed override IEnumerable<RoType> SpecializeInterfaces(RoType[] instantiation) => throw null;
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter) => throw null;
- internal sealed override RoDefinitionType GetNestedTypeCore(ReadOnlySpan<byte> utf8Name) => throw null;
- internal sealed override IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter filter, RoInstantiationProviderType declaringType) => throw null;
- internal sealed override IEnumerable<MethodInfo> SpecializeMethods(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null;
- internal sealed override IEnumerable<EventInfo> SpecializeEvents(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null;
- internal sealed override IEnumerable<FieldInfo> SpecializeFields(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null;
- internal sealed override IEnumerable<PropertyInfo> SpecializeProperties(NameFilter filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null;
+ public sealed override bool IsGenericTypeDefinition => throw null!;
+ public sealed override int MetadataToken => throw null!;
+ internal sealed override RoModule GetRoModule() => throw null!;
+ protected sealed override string ComputeName() => throw null!;
+ protected sealed override string ComputeNamespace() => throw null!;
+ protected sealed override TypeAttributes ComputeAttributeFlags() => throw null!;
+ protected sealed override RoType ComputeDeclaringType() => throw null!;
+ internal sealed override int GetGenericParameterCount() => throw null!;
+ internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null!;
+ internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null!;
+ internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null!;
+ protected sealed override IEnumerable<CustomAttributeData> GetTrueCustomAttributes() => throw null!;
+ protected sealed override void GetPackSizeAndSize(out int packSize, out int size) => throw null!;
+ protected internal sealed override RoType ComputeEnumUnderlyingType() => throw null!;
+ internal sealed override RoType SpecializeBaseType(RoType[] instantiation) => throw null!;
+ internal sealed override IEnumerable<RoType> SpecializeInterfaces(RoType[] instantiation) => throw null!;
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter) => throw null!;
+ internal sealed override RoDefinitionType GetNestedTypeCore(ReadOnlySpan<byte> utf8Name) => throw null!;
+ internal sealed override IEnumerable<ConstructorInfo> SpecializeConstructors(NameFilter? filter, RoInstantiationProviderType declaringType) => throw null!;
+ internal sealed override IEnumerable<MethodInfo> SpecializeMethods(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null!;
+ internal sealed override IEnumerable<EventInfo> SpecializeEvents(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null!;
+ internal sealed override IEnumerable<FieldInfo> SpecializeFields(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null!;
+ internal sealed override IEnumerable<PropertyInfo> SpecializeProperties(NameFilter? filter, Type reflectedType, RoInstantiationProviderType declaringType) => throw null!;
}
}
public sealed override bool IsGenericParameter => true;
public sealed override bool ContainsGenericParameters => true;
- protected sealed override string ComputeNamespace() => DeclaringType.Namespace;
- protected sealed override string ComputeFullName() => null;
+ protected sealed override string? ComputeNamespace() => DeclaringType!.Namespace;
+ protected sealed override string? ComputeFullName() => null;
public sealed override string ToString() => Loader.GetDisposedString() ?? Name;
protected sealed override TypeAttributes ComputeAttributeFlags() => TypeAttributes.Public;
protected sealed override TypeCode GetTypeCodeImpl() => TypeCode.Object;
- internal sealed override RoType GetRoElementType() => null;
+ internal sealed override RoType? GetRoElementType() => null;
public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
public sealed override Type GetGenericTypeDefinition() => throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
public sealed override Type[] GetGenericParameterConstraints() => GetGenericParameterConstraintsNoCopy().CloneArray<Type>();
private RoType[] GetGenericParameterConstraintsNoCopy() => _lazyConstraints ?? (_lazyConstraints = ComputeGenericParameterConstraints());
protected abstract RoType[] ComputeGenericParameterConstraints();
- private volatile RoType[] _lazyConstraints;
+ private volatile RoType[]? _lazyConstraints;
public sealed override Guid GUID => Guid.Empty;
- public sealed override StructLayoutAttribute StructLayoutAttribute => null;
+ public sealed override StructLayoutAttribute? StructLayoutAttribute => null;
protected internal sealed override RoType ComputeEnumUnderlyingType() => throw new ArgumentException(SR.Arg_MustBeEnum);
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk()
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk()
{
RoType[] constraints = GetGenericParameterConstraintsNoCopy();
foreach (RoType constraint in constraints)
}
// Low level support for the BindingFlag-driven enumerator apis.
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => Array.Empty<ConstructorInfo>();
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => Array.Empty<MethodInfo>();
- internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => Array.Empty<EventInfo>();
- internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => Array.Empty<FieldInfo>();
- internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => Array.Empty<PropertyInfo>();
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter) => Array.Empty<RoType>();
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => Array.Empty<ConstructorInfo>();
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => Array.Empty<MethodInfo>();
+ internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType) => Array.Empty<EventInfo>();
+ internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType) => Array.Empty<FieldInfo>();
+ internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType) => Array.Empty<PropertyInfo>();
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter) => Array.Empty<RoType>();
}
}
internal sealed override RoModule GetRoModule() => _elementType.GetRoModule();
protected sealed override string ComputeName() => _elementType.Name + Suffix;
- protected sealed override string ComputeNamespace() => _elementType.Namespace;
- protected sealed override string ComputeFullName()
+ protected sealed override string? ComputeNamespace() => _elementType.Namespace;
+ protected sealed override string? ComputeFullName()
{
- string fullName = _elementType.FullName;
+ string? fullName = _elementType.FullName;
return fullName == null ? null : fullName + Suffix;
}
public sealed override string ToString() => _elementType.ToString() + Suffix;
public sealed override MethodBase DeclaringMethod => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
- protected sealed override RoType ComputeDeclaringType() => null;
+ protected sealed override RoType? ComputeDeclaringType() => null;
public sealed override IEnumerable<CustomAttributeData> CustomAttributes => Array.Empty<CustomAttributeData>();
internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => false;
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => null;
+ internal sealed override CustomAttributeData? TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => null;
public sealed override int MetadataToken => 0x02000000; // nil TypeDef token
public sealed override Type[] GetGenericParameterConstraints() => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public sealed override Guid GUID => Guid.Empty;
- public sealed override StructLayoutAttribute StructLayoutAttribute => null;
+ public sealed override StructLayoutAttribute? StructLayoutAttribute => null;
protected internal sealed override RoType ComputeEnumUnderlyingType() => throw new ArgumentException(SR.Arg_MustBeEnum);
protected abstract string Suffix { get; }
// Low level support for the BindingFlag-driven enumerator apis.
- internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => Array.Empty<EventInfo>();
- internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => Array.Empty<FieldInfo>();
- internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => Array.Empty<PropertyInfo>();
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter) => Array.Empty<RoType>();
+ internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType) => Array.Empty<EventInfo>();
+ internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType) => Array.Empty<FieldInfo>();
+ internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType) => Array.Empty<PropertyInfo>();
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter) => Array.Empty<RoType>();
}
}
protected sealed override string Suffix => "*";
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => null;
+ protected sealed override RoType? ComputeBaseTypeWithoutDesktopQuirk() => null;
protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => Array.Empty<RoType>();
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => Array.Empty<ConstructorInfo>();
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => Array.Empty<MethodInfo>();
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => Array.Empty<ConstructorInfo>();
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => Array.Empty<MethodInfo>();
}
}
{
protected RoStubType() : base() { }
- public sealed override bool IsTypeDefinition => throw null;
- public sealed override bool IsGenericTypeDefinition => throw null;
- protected sealed override bool HasElementTypeImpl() => throw null;
- protected sealed override bool IsArrayImpl() => throw null;
- public sealed override bool IsSZArray => throw null;
- public sealed override bool IsVariableBoundArray => throw null;
- protected sealed override bool IsByRefImpl() => throw null;
- protected sealed override bool IsPointerImpl() => throw null;
- public sealed override bool IsConstructedGenericType => throw null;
- public sealed override bool IsGenericParameter => throw null;
- public sealed override bool IsGenericTypeParameter => throw null;
- public sealed override bool IsGenericMethodParameter => throw null;
- public sealed override bool ContainsGenericParameters => throw null;
-
- internal sealed override RoModule GetRoModule() => throw null;
-
- public sealed override int GetArrayRank() => throw null;
-
- protected sealed override string ComputeName() => throw null;
- protected sealed override string ComputeNamespace() => throw null;
- protected sealed override string ComputeFullName() => throw null;
-
- protected sealed override TypeAttributes ComputeAttributeFlags() => throw null;
- protected sealed override TypeCode GetTypeCodeImpl() => throw null;
+ public sealed override bool IsTypeDefinition => throw null!;
+ public sealed override bool IsGenericTypeDefinition => throw null!;
+ protected sealed override bool HasElementTypeImpl() => throw null!;
+ protected sealed override bool IsArrayImpl() => throw null!;
+ public sealed override bool IsSZArray => throw null!;
+ public sealed override bool IsVariableBoundArray => throw null!;
+ protected sealed override bool IsByRefImpl() => throw null!;
+ protected sealed override bool IsPointerImpl() => throw null!;
+ public sealed override bool IsConstructedGenericType => throw null!;
+ public sealed override bool IsGenericParameter => throw null!;
+ public sealed override bool IsGenericTypeParameter => throw null!;
+ public sealed override bool IsGenericMethodParameter => throw null!;
+ public sealed override bool ContainsGenericParameters => throw null!;
+
+ internal sealed override RoModule GetRoModule() => throw null!;
+
+ public sealed override int GetArrayRank() => throw null!;
+
+ protected sealed override string ComputeName() => throw null!;
+ protected sealed override string ComputeNamespace() => throw null!;
+ protected sealed override string ComputeFullName() => throw null!;
+
+ protected sealed override TypeAttributes ComputeAttributeFlags() => throw null!;
+ protected sealed override TypeCode GetTypeCodeImpl() => throw null!;
public sealed override string ToString() => GetType().ToString();
- public sealed override MethodBase DeclaringMethod => throw null;
- protected sealed override RoType ComputeDeclaringType() => throw null;
+ public sealed override MethodBase DeclaringMethod => throw null!;
+ protected sealed override RoType ComputeDeclaringType() => throw null!;
- public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null;
- internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null;
- internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null;
+ public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw null!;
+ internal sealed override bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null!;
+ internal sealed override CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name) => throw null!;
- public sealed override int MetadataToken => throw null;
+ public sealed override int MetadataToken => throw null!;
- internal sealed override RoType GetRoElementType() => throw null;
+ internal sealed override RoType GetRoElementType() => throw null!;
- public sealed override Type GetGenericTypeDefinition() => throw null;
- internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null;
- internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => throw null;
- protected internal sealed override RoType[] GetGenericArgumentsNoCopy() => throw null;
- public sealed override Type MakeGenericType(params Type[] typeArguments) => throw null;
+ public sealed override Type GetGenericTypeDefinition() => throw null!;
+ internal sealed override RoType[] GetGenericTypeParametersNoCopy() => throw null!;
+ internal sealed override RoType[] GetGenericTypeArgumentsNoCopy() => throw null!;
+ protected internal sealed override RoType[] GetGenericArgumentsNoCopy() => throw null!;
+ public sealed override Type MakeGenericType(params Type[] typeArguments) => throw null!;
- public sealed override GenericParameterAttributes GenericParameterAttributes => throw null;
- public sealed override int GenericParameterPosition => throw null;
- public sealed override Type[] GetGenericParameterConstraints() => throw null;
+ public sealed override GenericParameterAttributes GenericParameterAttributes => throw null!;
+ public sealed override int GenericParameterPosition => throw null!;
+ public sealed override Type[] GetGenericParameterConstraints() => throw null!;
- public sealed override Guid GUID => throw null;
- public sealed override StructLayoutAttribute StructLayoutAttribute => throw null;
- protected internal sealed override RoType ComputeEnumUnderlyingType() => throw null;
+ public sealed override Guid GUID => throw null!;
+ public sealed override StructLayoutAttribute StructLayoutAttribute => throw null!;
+ protected internal sealed override RoType ComputeEnumUnderlyingType() => throw null!;
- protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => throw null;
- protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => throw null;
+ protected sealed override RoType ComputeBaseTypeWithoutDesktopQuirk() => throw null!;
+ protected sealed override IEnumerable<RoType> ComputeDirectlyImplementedInterfaces() => throw null!;
// Low level support for the BindingFlag-driven enumerator apis.
- internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter) => throw null;
- internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType) => throw null;
- internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType) => throw null;
- internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType) => throw null;
- internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType) => throw null;
- internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter filter) => throw null;
+ internal sealed override IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter) => throw null!;
+ internal sealed override IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType) => throw null!;
+ internal sealed override IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType) => throw null!;
+ internal sealed override IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType) => throw null!;
+ internal sealed override IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType) => throw null!;
+ internal sealed override IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter) => throw null!;
}
}
/// </summary>
internal abstract partial class RoType
{
- public sealed override Type GetInterface(string name, bool ignoreCase)
+ public sealed override Type? GetInterface(string name, bool ignoreCase)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
name.SplitTypeName(out string ns, out string simpleName);
- Type match = null;
+ Type? match = null;
foreach (Type ifc in ImplementedInterfaces)
{
string ifcSimpleName = ifc.Name;
{
BaseTypeClassification classification = BaseTypeClassification.Computed;
- Type baseType = BaseType;
+ Type? baseType = BaseType;
if (baseType != null)
{
CoreTypes coreTypes = Loader.GetAllFoundCoreTypes();
- Type enumType = coreTypes[CoreType.Enum];
- Type valueType = coreTypes[CoreType.ValueType];
+ Type? enumType = coreTypes[CoreType.Enum];
+ Type? valueType = coreTypes[CoreType.ValueType];
if (baseType == enumType)
classification |= BaseTypeClassification.IsEnum | BaseTypeClassification.IsValueType;
internal abstract RoType[] GetGenericTypeParametersNoCopy();
// Applies if HasElementType == true
- public sealed override Type GetElementType() => GetRoElementType();
- internal abstract RoType GetRoElementType();
+ public sealed override Type? GetElementType() => GetRoElementType();
+ internal abstract RoType? GetRoElementType();
// Applies if IsArray == true
public abstract override int GetArrayRank();
// Naming
public sealed override string Name => _lazyName ?? (_lazyName = ComputeName());
protected abstract string ComputeName();
- private volatile string _lazyName;
+ private volatile string? _lazyName;
- public sealed override string Namespace => _lazyNamespace ?? (_lazyNamespace = ComputeNamespace());
- protected abstract string ComputeNamespace();
- private volatile string _lazyNamespace;
+ public sealed override string? Namespace => _lazyNamespace ?? (_lazyNamespace = ComputeNamespace());
+ protected abstract string? ComputeNamespace();
+ private volatile string? _lazyNamespace;
- public sealed override string FullName => _lazyFullName ?? (_lazyFullName = ComputeFullName());
- protected abstract string ComputeFullName();
- private volatile string _lazyFullName;
+ public sealed override string? FullName => _lazyFullName ?? (_lazyFullName = ComputeFullName());
+ protected abstract string? ComputeFullName();
+ private volatile string? _lazyFullName;
- public sealed override string AssemblyQualifiedName => _lazyAssemblyQualifiedFullName ?? (_lazyAssemblyQualifiedFullName = ComputeAssemblyQualifiedName());
- private string ComputeAssemblyQualifiedName()
+ public sealed override string? AssemblyQualifiedName => _lazyAssemblyQualifiedFullName ?? (_lazyAssemblyQualifiedFullName = ComputeAssemblyQualifiedName());
+ private string? ComputeAssemblyQualifiedName()
{
- string fullName = FullName;
+ string? fullName = FullName;
if (fullName == null) // Open types return null for FullName by design.
return null;
- string assemblyName = Assembly.FullName;
+ string? assemblyName = Assembly.FullName;
return fullName + ", " + assemblyName;
}
- private volatile string _lazyAssemblyQualifiedFullName;
+ private volatile string? _lazyAssemblyQualifiedFullName;
// Assembly and module
public sealed override Assembly Assembly => Module.Assembly;
internal abstract RoModule GetRoModule();
// Nesting
- public sealed override Type DeclaringType => GetRoDeclaringType();
- protected abstract RoType ComputeDeclaringType();
- internal RoType GetRoDeclaringType() => _lazyDeclaringType ?? (_lazyDeclaringType = ComputeDeclaringType());
- private volatile RoType _lazyDeclaringType;
+ public sealed override Type? DeclaringType => GetRoDeclaringType();
+ protected abstract RoType? ComputeDeclaringType();
+ internal RoType? GetRoDeclaringType() => _lazyDeclaringType ?? (_lazyDeclaringType = ComputeDeclaringType());
+ private volatile RoType? _lazyDeclaringType;
- public abstract override MethodBase DeclaringMethod { get; }
+ public abstract override MethodBase? DeclaringMethod { get; }
// .NET Framework compat: For types, ReflectedType == DeclaringType. Nested types are always looked up as if BindingFlags.DeclaredOnly was passed.
// For non-nested types, the concept of a ReflectedType doesn't even make sense.
- public sealed override Type ReflectedType => DeclaringType;
+ public sealed override Type? ReflectedType => DeclaringType;
// CustomAttributeData
public sealed override IList<CustomAttributeData> GetCustomAttributesData() => CustomAttributes.ToReadOnlyCollection();
// Optimized routines that find a custom attribute by type name only.
internal abstract bool IsCustomAttributeDefined(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
- internal abstract CustomAttributeData TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
+ internal abstract CustomAttributeData? TryFindCustomAttribute(ReadOnlySpan<byte> ns, ReadOnlySpan<byte> name);
// Inheritance
- public sealed override Type BaseType => GetRoBaseType();
- internal RoType GetRoBaseType() => object.ReferenceEquals(_lazyBaseType, Sentinels.RoType) ? (_lazyBaseType = ComputeBaseType()) : _lazyBaseType;
- private RoType ComputeBaseType()
+ public sealed override Type? BaseType => GetRoBaseType();
+ internal RoType? GetRoBaseType() => object.ReferenceEquals(_lazyBaseType, Sentinels.RoType) ? (_lazyBaseType = ComputeBaseType()) : _lazyBaseType;
+ private RoType? ComputeBaseType()
{
- RoType baseType = ComputeBaseTypeWithoutDesktopQuirk();
+ RoType? baseType = ComputeBaseTypeWithoutDesktopQuirk();
if (baseType != null && baseType.IsGenericParameter)
{
// .NET Framework quirk: a generic parameter whose constraint is another generic parameter reports its BaseType as System.Object
}
return baseType;
}
- private volatile RoType _lazyBaseType = Sentinels.RoType;
+ private volatile RoType? _lazyBaseType = Sentinels.RoType;
//
// This internal method implements BaseType without the following .NET Framework quirk:
// To implement this with the least amount of code smell, we'll implement the idealized version of BaseType here
// and make the special-case adjustment in the public version of BaseType.
//
- protected abstract RoType ComputeBaseTypeWithoutDesktopQuirk();
+ protected abstract RoType? ComputeBaseTypeWithoutDesktopQuirk();
public sealed override Type[] GetInterfaces() => GetInterfacesNoCopy().CloneArray<Type>();
{
HashSet<RoType> ifcs = new HashSet<RoType>();
- RoType baseType = ComputeBaseTypeWithoutDesktopQuirk();
+ RoType? baseType = ComputeBaseTypeWithoutDesktopQuirk();
if (baseType != null)
{
foreach (RoType ifc in baseType.GetInterfacesNoCopy())
return list.ToArray();
}
- private volatile RoType[] _lazyInterfaces;
+ private volatile RoType[]? _lazyInterfaces;
public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) => throw new NotSupportedException(SR.NotSupported_InterfaceMapping);
// Assignability
- public sealed override bool IsAssignableFrom(TypeInfo typeInfo) => IsAssignableFrom((Type)typeInfo);
- public sealed override bool IsAssignableFrom(Type c)
+ public sealed override bool IsAssignableFrom(TypeInfo? typeInfo) => IsAssignableFrom((Type?)typeInfo);
+ public sealed override bool IsAssignableFrom(Type? c)
{
if (c == null)
return false;
// Random interop stuff
public abstract override Guid GUID { get; }
- public abstract override StructLayoutAttribute StructLayoutAttribute { get; }
+ public abstract override StructLayoutAttribute? StructLayoutAttribute { get; }
public sealed override MemberInfo[] GetDefaultMembers()
{
- string defaultMemberName = GetDefaultMemberName();
+ string? defaultMemberName = GetDefaultMemberName();
return defaultMemberName != null ? GetMember(defaultMemberName) : Array.Empty<MemberInfo>();
}
- private string GetDefaultMemberName()
+ private string? GetDefaultMemberName()
{
- for (RoType type = this; type != null; type = type.GetRoBaseType())
+ for (RoType? type = this; type != null; type = type.GetRoBaseType())
{
- CustomAttributeData attribute = type.TryFindCustomAttribute(Utf8Constants.SystemReflection, Utf8Constants.DefaultMemberAttribute);
+ CustomAttributeData? attribute = type.TryFindCustomAttribute(Utf8Constants.SystemReflection, Utf8Constants.DefaultMemberAttribute);
if (attribute != null)
{
IList<CustomAttributeTypedArgument> fixedArguments = attribute.ConstructorArguments;
// Enum methods
public sealed override Type GetEnumUnderlyingType() => _lazyUnderlyingEnumType ?? (_lazyUnderlyingEnumType = ComputeEnumUnderlyingType());
protected internal abstract RoType ComputeEnumUnderlyingType();
- private volatile RoType _lazyUnderlyingEnumType;
+ private volatile RoType? _lazyUnderlyingEnumType;
public sealed override Array GetEnumValues() => throw new InvalidOperationException(SR.Arg_InvalidOperation_Reflection);
// No trust environment to apply these to.
public sealed override object[] GetCustomAttributes(bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
- public sealed override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
+ public sealed override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) => throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
// Low level support for the BindingFlag-driven enumerator apis. These return members declared (not inherited) on the current
// type, possibly doing case-sensitive/case-insensitive filtering on a supplied name.
- internal abstract IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter filter);
- internal abstract IEnumerable<MethodInfo> GetMethodsCore(NameFilter filter, Type reflectedType);
- internal abstract IEnumerable<EventInfo> GetEventsCore(NameFilter filter, Type reflectedType);
- internal abstract IEnumerable<FieldInfo> GetFieldsCore(NameFilter filter, Type reflectedType);
- internal abstract IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter filter, Type reflectedType);
- internal abstract IEnumerable<RoType> GetNestedTypesCore(NameFilter filter);
+ internal abstract IEnumerable<ConstructorInfo> GetConstructorsCore(NameFilter? filter);
+ internal abstract IEnumerable<MethodInfo> GetMethodsCore(NameFilter? filter, Type reflectedType);
+ internal abstract IEnumerable<EventInfo> GetEventsCore(NameFilter? filter, Type reflectedType);
+ internal abstract IEnumerable<FieldInfo> GetFieldsCore(NameFilter? filter, Type reflectedType);
+ internal abstract IEnumerable<PropertyInfo> GetPropertiesCore(NameFilter? filter, Type reflectedType);
+ internal abstract IEnumerable<RoType> GetNestedTypesCore(NameFilter? filter);
// Backdoor for RoModule to invoke GetMethodImpl();
- internal MethodInfo InternalGetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ internal MethodInfo? InternalGetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers)
{
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
public class ClassWithConstructor1<T>
{
- public ClassWithConstructor1(int x, T t) => throw null;
+ public ClassWithConstructor1(int x, T t) => throw null!;
}
public class ClassWithMethods1<T>
{
- public bool Method1(int x, T t) => throw null;
+ public bool Method1(int x, T t) => throw null!;
- public void TestPrimitives1(bool bo, byte b, char c, short s, int i, long l, IntPtr ip, sbyte sb, ushort us, uint ui, ulong ul, UIntPtr uip, float fl, double db, object o, string str, TypedReference tr) => throw null;
+ public void TestPrimitives1(bool bo, byte b, char c, short s, int i, long l, IntPtr ip, sbyte sb, ushort us, uint ui, ulong ul, UIntPtr uip, float fl, double db, object o, string str, TypedReference tr) => throw null!;
}
public class ClassWithGenericMethods1
{
- public void GenericMethod1<M, N>() => throw null;
+ public void GenericMethod1<M, N>() => throw null!;
}
public class GenericClassWithGenericMethods1<T, U>
{
- public void GenericMethod1<M, N>(GenericClass5<N, M[], IEnumerable<U>, T[,], int> g) => throw null;
+ public void GenericMethod1<M, N>(GenericClass5<N, M[], IEnumerable<U>, T[,], int> g) => throw null!;
}
public class ClassWithLiteralFields
public class ParametersWithPseudoCustomtAttributes
{
- public void Foo([In] int i, [Out] out object o, [Optional] object opt, [MarshalAs(UnmanagedType.I4)] int fa) => throw null;
+ public void Foo([In] int i, [Out] out object o, [Optional] object opt, [MarshalAs(UnmanagedType.I4)] int fa) => throw null!;
}
public class SampleCustomAttribute : Attribute
public int PublicProtectedProp { get; protected set; }
public int PublicInternalProp { get; internal set; }
- public string this[int i, T t] => throw null;
+ public string this[int i, T t] => throw null!;
}
public class DerivedFromPropertyHolder1<T> : PropertyHolder1<T> { }
public class EventHolder1<T>
{
- public event Action<T> MyEvent { add { throw null; } remove { throw null; } }
+ public event Action<T> MyEvent { add { throw null!; } remove { throw null!; } }
}
public class DerivedFromEventHolder1<T> : EventHolder1<T>
public void MyMethod2<M>() { }
public void MyParameterizedMethod1(int x, int y) { }
public void MyParameterizedMethod2(int x, int y) { }
- public int MyProperty1 { get { throw null; } set { throw null; } }
- public int MyProperty2 { get { throw null; } set { throw null; } }
+ public int MyProperty1 { get { throw null!; } set { throw null!; } }
+ public int MyProperty2 { get { throw null!; } set { throw null!; } }
}
private class MemberHolder<T> : MemberHolderBase<T>
private class Base
{
- public int MyMethod() { throw null; }
- public static int MyStaticMethod() { throw null; }
+ public int MyMethod() { throw null!; }
+ public static int MyStaticMethod() { throw null!; }
}
private class Derived : Base
{
- public new int MyMethod() { throw null; }
- public static new int MyStaticMethod() { throw null; }
+ public new int MyMethod() { throw null!; }
+ public static new int MyStaticMethod() { throw null!; }
}
}