Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable CA1859 - Use concrete types when possible for improved performance #80848

Merged
merged 15 commits into from
Jan 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,11 @@
<IsShipping Condition="'$(IsTestProject)' == 'true' or '$(IsTestSupportProject)' == 'true' or '$(IsPublishedAppTestProject)' == 'true'">false</IsShipping>
</PropertyGroup>

<ItemGroup Condition="'$(IsTestProject)' == 'true'">
<EditorConfigFiles Remove="$(RepositoryEngineeringDir)CodeAnalysis.src.globalconfig" />
<EditorConfigFiles Include="$(RepositoryEngineeringDir)CodeAnalysis.test.globalconfig" />
</ItemGroup>

<PropertyGroup>
<!-- Treat as a generator project if either the parent or the parent parent directory is named gen. -->
<IsGeneratorProject Condition="$([System.IO.Path]::GetFileName('$(MSBuildProjectDirectory)')) == 'gen' or
Expand Down
3 changes: 3 additions & 0 deletions eng/CodeAnalysis.src.globalconfig
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,9 @@ dotnet_diagnostic.CA1857.severity = warning
# CA1858: Use 'StartsWith' instead of 'IndexOf'
dotnet_diagnostic.CA1858.severity = warning

# CA1859: Use concrete types when possible for improved performance
marek-safar marked this conversation as resolved.
Show resolved Hide resolved
dotnet_diagnostic.CA1859.severity = warning

# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

Expand Down
3 changes: 3 additions & 0 deletions eng/CodeAnalysis.test.globalconfig
Original file line number Diff line number Diff line change
Expand Up @@ -462,6 +462,9 @@ dotnet_diagnostic.CA1857.severity = none
# CA1858: Use 'StartsWith' instead of 'IndexOf'
dotnet_diagnostic.CA1858.severity = none

# CA1859: Use concrete types when possible for improved performance
dotnet_diagnostic.CA1859.severity = none

# CA2000: Dispose objects before losing scope
dotnet_diagnostic.CA2000.severity = none

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyB
IEnumerable<CustomAttributeBuilder>? assemblyAttributes)
=> DefineDynamicAssembly(name, access, assemblyAttributes, Assembly.GetCallingAssembly());

private static AssemblyBuilder DefineDynamicAssembly(
private static RuntimeAssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
IEnumerable<CustomAttributeBuilder>? assemblyAttributes,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1360,7 +1360,7 @@ protected override ConstructorBuilder DefineDefaultConstructorCore(MethodAttribu
Justification = "MakeGenericType is only called on a TypeBuilderInstantiation which is not subject to trimming")]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern",
Justification = "GetConstructor is only called on a TypeBuilderInstantiation which is not subject to trimming")]
private ConstructorBuilder DefineDefaultConstructorNoLock(MethodAttributes attributes)
private RuntimeConstructorBuilder DefineDefaultConstructorNoLock(MethodAttributes attributes)
{
RuntimeConstructorBuilder constBuilder;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ private static void MonitorExitStatic(IntPtr pEEType, ref bool lockTaken)
lockTaken = false;
}

private static object GetStaticLockObject(IntPtr pEEType)
private static Type GetStaticLockObject(IntPtr pEEType)
{
return Type.GetTypeFromEETypePtr(new EETypePtr(pEEType));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ private static unsafe Array InternalCreate(RuntimeType elementType, int rank, in
}
}

#pragma warning disable CA1859 // https://github.com/dotnet/roslyn-analyzers/issues/6451
private static void ValidateElementType(Type elementType)
{
while (elementType.IsArray)
Expand All @@ -106,6 +107,7 @@ private static void ValidateElementType(Type elementType)
if (elementType.ContainsGenericParameters)
throw new NotSupportedException(SR.NotSupported_OpenType);
}
#pragma warning restore CA1859

public unsafe void Initialize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public partial class Exception
}
}

private static IDictionary CreateDataContainer() => new ListDictionaryInternal();
private static ListDictionaryInternal CreateDataContainer() => new ListDictionaryInternal();

private static string? SerializationWatsonBuckets => null;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ internal static class DispenserFactory
}


private static readonly DispenserPolicy s_dispenserPolicy = new DefaultDispenserPolicy();
private static readonly DefaultDispenserPolicy s_dispenserPolicy = new DefaultDispenserPolicy();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ internal static IEnumerable<CustomAttributeData> GetCustomAttributes(MetadataRea
yield return GetCustomAttributeData(reader, customAttributeHandle);
}

private static CustomAttributeData GetCustomAttributeData(MetadataReader reader, CustomAttributeHandle customAttributeHandle)
private static NativeFormatCustomAttributeData GetCustomAttributeData(MetadataReader reader, CustomAttributeHandle customAttributeHandle)
{
return new NativeFormatCustomAttributeData(reader, customAttributeHandle);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public sealed override PropertyInfo GetImplicitlyOverriddenBaseClassProperty(Pro
return p.GetImplicitlyOverriddenBaseClassMember(PropertyPolicies.Instance);
}

private static FieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle)
private static RuntimeFieldInfo GetFieldInfo(RuntimeTypeHandle declaringTypeHandle, FieldHandle fieldHandle)
{
RuntimeTypeInfo contextTypeInfo = declaringTypeHandle.GetTypeForRuntimeTypeHandle();
NativeFormatRuntimeNamedTypeInfo definingTypeInfo = contextTypeInfo.AnchoringTypeDefinitionForDeclaredMembers.CastToNativeFormatRuntimeNamedTypeInfo();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ internal Delegate CreateDelegateNoThrowOnBindFailure(RuntimeTypeInfo runtimeDele
Debug.Assert(runtimeDelegateType.IsDelegate);

ExecutionEnvironment executionEnvironment = ReflectionCoreExecution.ExecutionEnvironment;
MethodInfo invokeMethod = runtimeDelegateType.GetInvokeMethod();
RuntimeMethodInfo invokeMethod = runtimeDelegateType.GetInvokeMethod();

// Make sure the return type is assignment-compatible.
Type expectedReturnType = ReturnParameter.ParameterType;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ public sealed override IEnumerable<Type> ImplementedInterfaces
result.AddRange(baseType.GetInterfaces());
foreach (QTypeDefRefOrSpec directlyImplementedInterface in this.TypeRefDefOrSpecsForDirectlyImplementedInterfaces)
{
Type ifc = directlyImplementedInterface.Resolve(typeContext);
RuntimeTypeInfo ifc = directlyImplementedInterface.Resolve(typeContext);
if (result.Contains(ifc))
continue;
result.Add(ifc);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public sealed override Stream GetManifestResourceStream(Assembly assembly, strin
return null;
}

private static unsafe Stream ReadResourceFromBlob(ResourceInfo resourceInfo)
private static unsafe UnmanagedMemoryStream ReadResourceFromBlob(ResourceInfo resourceInfo)
{
byte* pBlob;
uint cbBlob;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ internal class NativeLayoutInfoLoadContext
public Instantiation _typeArgumentHandles;
public Instantiation _methodArgumentHandles;

private TypeDesc GetInstantiationType(ref NativeParser parser, uint arity)
private DefType GetInstantiationType(ref NativeParser parser, uint arity)
{
DefType typeDefinition = (DefType)GetType(ref parser);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ internal void ParseNativeLayoutInfo(InstantiatedMethod method)

uint nativeLayoutInfoToken;
NativeFormatModuleInfo nativeLayoutModule;
MethodDesc templateMethod = TemplateLocator.TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken);
InstantiatedMethod templateMethod = TemplateLocator.TryGetGenericMethodTemplate(nonTemplateMethod, out nativeLayoutModule, out nativeLayoutInfoToken);
if (templateMethod == null)
{
throw new MissingTemplateException();
Expand Down Expand Up @@ -730,7 +730,7 @@ private unsafe void FinishClassConstructor(TypeDesc type, TypeBuilderState state
*generatedTypeClassConstructorSlotPointer = generatedTypeClassConstructorFatFunctionPointer;
}

private void CopyDictionaryFromTypeToAppropriateSlotInDerivedType(TypeDesc baseType, TypeBuilderState derivedTypeState)
private void CopyDictionaryFromTypeToAppropriateSlotInDerivedType(DefType baseType, TypeBuilderState derivedTypeState)
{
var baseTypeState = baseType.GetOrCreateTypeBuilderState();

Expand Down Expand Up @@ -1242,7 +1242,7 @@ public static bool TryBuildPointerType(RuntimeTypeHandle pointeeTypeHandle, out
if (!TypeSystemContext.PointerTypesCache.TryGetValue(pointeeTypeHandle, out pointerTypeHandle))
{
TypeSystemContext context = TypeSystemContextFactory.Create();
TypeDesc pointerType = context.GetPointerType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle));
PointerType pointerType = context.GetPointerType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle));
pointerTypeHandle = EETypeCreator.CreatePointerEEType((uint)pointerType.GetHashCode(), pointeeTypeHandle, pointerType);
unsafe
{
Expand All @@ -1262,7 +1262,7 @@ public static bool TryBuildByRefType(RuntimeTypeHandle pointeeTypeHandle, out Ru
if (!TypeSystemContext.ByRefTypesCache.TryGetValue(pointeeTypeHandle, out byRefTypeHandle))
{
TypeSystemContext context = TypeSystemContextFactory.Create();
TypeDesc byRefType = context.GetByRefType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle));
ByRefType byRefType = context.GetByRefType(context.ResolveRuntimeTypeHandle(pointeeTypeHandle));
byRefTypeHandle = EETypeCreator.CreateByRefEEType((uint)byRefType.GetHashCode(), pointeeTypeHandle, byRefType);
unsafe
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ private string SanitizeNameWithHash(string literal)
/// <param name="origName">Name to check for uniqueness.</param>
/// <param name="set">Set of names already used.</param>
/// <returns>A name based on <param name="origName"/> that is not part of <param name="set"/>.</returns>
private static string DisambiguateName(string origName, ISet<string> set)
private static string DisambiguateName(string origName, HashSet<string> set)
{
int iter = 0;
string result = origName;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,22 +195,22 @@ public void PatchByteAt(int offset, byte value)
// This is the price we have to pay for using UTF8. Thing like High Surrogate Start Char - '\ud800'
// can be expressed in UTF-16 (which is the format used to store ECMA metadata), but don't have
// a representation in UTF-8.
private static Encoding _stringEncoding = new UTF8Encoding(false, false);
private static readonly UTF8Encoding s_stringEncoding = new UTF8Encoding(false, false);

public void WriteString(string s)
{
// The actual bytes are only necessary for the final version during the growing phase
if (IsGrowing())
{
byte[] bytes = _stringEncoding.GetBytes(s);
byte[] bytes = s_stringEncoding.GetBytes(s);

_encoder.WriteUnsigned((uint)bytes.Length);
for (int i = 0; i < bytes.Length; i++)
_encoder.WriteByte(bytes[i]);
}
else
{
int byteCount = _stringEncoding.GetByteCount(s);
int byteCount = s_stringEncoding.GetByteCount(s);
_encoder.WriteUnsigned((uint)byteCount);
WritePad(byteCount);
}
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/Common/TypeSystem/Common/FieldDesc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ public virtual FieldDesc InstantiateSignature(Instantiation typeInstantiation, I
{
FieldDesc field = this;

TypeDesc owningType = field.OwningType;
DefType owningType = field.OwningType;
TypeDesc instantiatedOwningType = owningType.InstantiateSignature(typeInstantiation, methodInstantiation);
if (owningType != instantiatedOwningType)
field = instantiatedOwningType.Context.GetFieldForInstantiatedType(field.GetTypicalFieldDefinition(), (InstantiatedType)instantiatedOwningType);
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/Common/TypeSystem/Ecma/EcmaModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ protected override IEntityHandleObject CreateValueFromKey(EntityHandle handle)
}
}

private object ResolveModuleReference(ModuleReferenceHandle handle)
private ModuleDesc ResolveModuleReference(ModuleReferenceHandle handle)
{
ModuleReference moduleReference = _metadataReader.GetModuleReference(handle);
string fileName = _metadataReader.GetString(moduleReference.Name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ private TypeDesc ResolveHandle(EntityHandle handle)
}
}

private TypeDesc GetWellKnownType(WellKnownType wellKnownType)
private DefType GetWellKnownType(WellKnownType wellKnownType)
{
return _tsc.GetWellKnownType(wellKnownType);
}
Expand Down
2 changes: 1 addition & 1 deletion src/coreclr/tools/Common/TypeSystem/Ecma/EcmaType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public override int GetHashCode()

private int InitializeHashCode()
{
TypeDesc containingType = ContainingType;
DefType containingType = ContainingType;
if (containingType == null)
{
string ns = Namespace;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private static MethodIL EmitComparerAndEqualityComparerCreateCommon(MethodDesc m
/// Gets the comparer type that is suitable to compare instances of <paramref name="type"/>
/// or null if such comparer cannot be determined at compile time.
/// </summary>
private static TypeDesc GetComparerForType(TypeDesc type, string flavor, string interfaceName)
private static InstantiatedType GetComparerForType(TypeDesc type, string flavor, string interfaceName)
{
TypeSystemContext context = type.Context;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ private void EmitCalli(PInvokeILCodeStreams ilCodeStreams, CalliMarshallingMetho
callsiteSetupCodeStream.Emit(ILOpcode.calli, emitter.NewToken(nativeSig));
}

private MethodIL EmitIL()
private PInvokeILStubMethodIL EmitIL()
{
if (_targetMethod.HasCustomAttribute("System.Runtime.InteropServices", "LCIDConversionAttribute"))
throw new NotSupportedException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -513,7 +513,7 @@ public MethodDesc GetTargetOfGenericVirtualMethodCall(MethodDesc calledMethod)
}

// Normalize to the slot defining method
MethodDesc slotNormalizedMethod = TypeSystemContext.GetInstantiatedMethod(
InstantiatedMethod slotNormalizedMethod = TypeSystemContext.GetInstantiatedMethod(
slotNormalizedMethodDefinition,
targetMethod.Instantiation);

Expand Down Expand Up @@ -541,7 +541,7 @@ public MethodDesc GetTargetOfGenericVirtualMethodCall(MethodDesc calledMethod)

while (!slotNormalizedMethod.OwningType.HasSameTypeDefinition(runtimeDeterminedOwningType))
{
TypeDesc runtimeDeterminedBaseTypeDefinition = runtimeDeterminedOwningType.GetTypeDefinition().BaseType;
DefType runtimeDeterminedBaseTypeDefinition = runtimeDeterminedOwningType.GetTypeDefinition().BaseType;
if (runtimeDeterminedBaseTypeDefinition.HasInstantiation)
{
runtimeDeterminedOwningType = runtimeDeterminedBaseTypeDefinition.InstantiateSignature(runtimeDeterminedOwningType.Instantiation, default);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ protected override TypeAnnotations CreateValueFromKey(TypeDesc key)
try
{
// Also inherit annotation from bases
TypeDesc baseType = key.BaseType;
DefType baseType = key.BaseType;
while (baseType != null)
{
var ecmaBaseType = (EcmaType)baseType.GetTypeDefinition();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1255,7 +1255,7 @@ protected static void AddDependenciesForUniversalGVMSupport(NodeFactory factory,
for (int i = 0; i < universalCanonArray.Length; i++)
universalCanonArray[i] = factory.TypeSystemContext.UniversalCanonType;

MethodDesc universalCanonMethodNonCanonicalized = method.MakeInstantiatedMethod(new Instantiation(universalCanonArray));
InstantiatedMethod universalCanonMethodNonCanonicalized = method.MakeInstantiatedMethod(new Instantiation(universalCanonArray));
MethodDesc universalCanonGVMMethod = universalCanonMethodNonCanonicalized.GetCanonMethodTarget(CanonicalFormKind.Universal);

dependencies ??= new DependencyList();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static bool MightHaveInterfaceDispatchMap(TypeDesc type, NodeFactory fact
if (type.IsInterface)
return ((MetadataType)type).IsDynamicInterfaceCastableImplementation();

TypeDesc declType = type.GetClosestDefType();
DefType declType = type.GetClosestDefType();

for (int interfaceIndex = 0; interfaceIndex < declType.RuntimeInterfaces.Length; interfaceIndex++)
{
Expand Down Expand Up @@ -143,7 +143,7 @@ private void EmitDispatchMap(ref ObjectDataBuilder builder, NodeFactory factory)
var defaultStaticEntryCountReservation = builder.ReserveShort();
int entryCount = 0;

TypeDesc declType = _type.GetClosestDefType();
DefType declType = _type.GetClosestDefType();
TypeDesc declTypeDefinition = declType.GetTypeDefinition();
DefType[] declTypeRuntimeInterfaces = declType.RuntimeInterfaces;
DefType[] declTypeDefinitionRuntimeInterfaces = declTypeDefinition.RuntimeInterfaces;
Expand Down