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

Fix warnings found with CA1861 Avoid constant arrays as arguments #86229

Merged
merged 16 commits into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions eng/CodeAnalysis.src.globalconfig
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,9 @@ dotnet_diagnostic.CA1859.severity = warning
# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = warning

# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.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 @@ -468,6 +468,9 @@ dotnet_diagnostic.CA1859.severity = none
# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = none

# CA1861: Avoid constant arrays as arguments
dotnet_diagnostic.CA1861.severity = none

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

Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,11 @@ public ILCompilerRootCommand(string[] args) : base(".NET Native IL Compiler")
// + the original command line arguments
// + a rsp file that should work to directly run out of the zip file

#pragma warning disable CA1861 // Avoid constant arrays as arguments. Only executed once during the execution of the program.
Helpers.MakeReproPackage(makeReproPath, context.ParseResult.GetValue(OutputFilePath), args, context.ParseResult,
inputOptions : new[] { "r", "reference", "m", "mibc", "rdxml", "directpinvokelist", "descriptor" },
outputOptions : new[] { "o", "out", "exportsfile" });
#pragma warning restore CA1861 // Avoid constant arrays as arguments
}

context.ExitCode = new Program(this).Run();
Expand Down
2 changes: 2 additions & 0 deletions src/coreclr/tools/aot/ILCompiler/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,9 @@ private static IEnumerable<int> ProcessWarningCodes(IEnumerable<string> warningC
{
foreach (string value in warningCodes)
{
#pragma warning disable CA1861 // Avoid constant arrays as arguments. Only executed once.
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
#pragma warning restore CA1861
foreach (string id in values)
{
if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
internal sealed class IDispatchMetaObject : ComFallbackMetaObject
{
private readonly IDispatchComObject _self;
private static readonly bool[] s_false = new bool[] { false };

[RequiresUnreferencedCode(Binder.TrimmerWarning)]
internal IDispatchMetaObject(Expression expression, IDispatchComObject self)
Expand Down Expand Up @@ -218,7 +219,7 @@ private DynamicMetaObject TryPropertyPut(SetMemberBinder binder, DynamicMetaObje
DynamicMetaObject result = new ComInvokeBinder(
new CallInfo(1),
new[] { value },
new bool[] { false },
s_false,
restrictions,
Expression.Constant(method),
dispatch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ internal static class VariantArray
// Don't need a dictionary for this, it will have very few elements
// (guaranteed less than 28, in practice 0-2)
private static readonly List<Type> s_generatedTypes = new List<Type>(0);
private static readonly string[] s_genericTName = new string[] { "T" };

[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray1))]
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray2))]
Expand Down Expand Up @@ -100,7 +101,7 @@ private static Type CreateCustomType(int size)
{
TypeAttributes attrs = TypeAttributes.NotPublic | TypeAttributes.SequentialLayout;
TypeBuilder type = UnsafeMethods.DynamicModule.DefineType("VariantArray" + size, attrs, typeof(ValueType));
GenericTypeParameterBuilder T = type.DefineGenericParameters(new string[] { "T" })[0];
GenericTypeParameterBuilder T = type.DefineGenericParameters(s_genericTName)[0];
for (int i = 0; i < size; i++)
{
type.DefineField("Element" + i, T, FieldAttributes.Public);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,7 @@ private void AdjustCallArgumentsForParams(CType callingObjectType, CType type, M
CType arrayType = (ArrayType)TypeManager.SubstType(mp.Params[mp.Params.Count - 1], type, pTypeArgs);

// Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work.
ExprArrayInit arrayInit = ExprFactory.CreateArrayInit(arrayType, null, null, new[] { 0 });
ExprArrayInit arrayInit = ExprFactory.CreateArrayInit(arrayType, null, null, s_zero);
arrayInit.GeneratedForParamArray = true;
arrayInit.OptionalArguments = named.Value;

Expand Down Expand Up @@ -1229,7 +1229,7 @@ private void AdjustCallArgumentsForParams(CType callingObjectType, CType type, M
CType elementType = subArr.ElementType;

// Use an EK_ARRINIT even in the empty case so empty param arrays in attributes work.
ExprArrayInit exprArrayInit = ExprFactory.CreateArrayInit(substitutedArrayType, null, null, new[] { 0 });
ExprArrayInit exprArrayInit = ExprFactory.CreateArrayInit(substitutedArrayType, null, null, s_zero);
exprArrayInit.GeneratedForParamArray = true;

if (it.AtEnd())
Expand Down Expand Up @@ -1618,6 +1618,8 @@ private static void CheckUnsafe(CType type)

private AggregateSymbol ContextForMemberLookup => Context.ContextForMemberLookup;

private static readonly int[] s_zero = new[] { 0 };

private static ExprWrap WrapShortLivedExpression(Expr expr) => ExprFactory.CreateWrap(expr);

private static ExprAssignment GenerateOptimizedAssignment(Expr op1, Expr op2) => ExprFactory.CreateAssignment(op1, op2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ internal sealed class DependencyContextPaths

public IEnumerable<string> NonApplicationPaths { get; }

private static readonly char[] s_semicolon = new[] { ';' };

public DependencyContextPaths(
string? application,
string? sharedRuntime,
Expand All @@ -40,7 +42,7 @@ private static DependencyContextPaths GetCurrent()

internal static DependencyContextPaths Create(string? depsFiles, string? sharedRuntime)
{
string[]? files = depsFiles?.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[]? files = depsFiles?.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
string? application = files != null && files.Length > 0 ? files[0] : null;

string[]? nonApplicationPaths = files?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ public static class Keywords
private const string UseAppFilters = "UseAppFilters";
private const string WriteEventCoreSuppressionJustification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.";
private const string WriteEventDynamicDependencySuppressionJustification = "DynamicDependency attribute will ensure that the required properties are not trimmed.";
private static readonly char[] s_semicolon = new[] { ';' };
private static readonly char[] s_colon = new[] { ':' };

private LoggingEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat)
{
Expand Down Expand Up @@ -366,7 +368,7 @@ private static LoggerFilterRule[] ParseFilterSpec(string? filterSpec, LogLevel d

var rules = new List<LoggerFilterRule>();
int ruleStringsStartIndex = 0;
string[] ruleStrings = filterSpec.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
string[] ruleStrings = filterSpec.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
if (ruleStrings.Length > 0 && ruleStrings[0].Equals(UseAppFilters, StringComparison.OrdinalIgnoreCase))
{
// Avoid adding default rule to disable event source loggers
Expand All @@ -381,7 +383,7 @@ private static LoggerFilterRule[] ParseFilterSpec(string? filterSpec, LogLevel d
{
string rule = ruleStrings[i];
LogLevel level = defaultLevel;
string[] parts = rule.Split(new[] { ':' }, 2);
string[] parts = rule.Split(s_colon, 2);
string loggerName = parts[0];
if (loggerName.Length == 0)
{
Expand Down
4 changes: 3 additions & 1 deletion src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ public OleDbCommandBuilder(OleDbDataAdapter? adapter) : this()
}
}

private static readonly char[] s_trimChars = new char[] { '@', ' ', ':' };

private void OleDbRowUpdatingHandler(object sender, OleDbRowUpdatingEventArgs ruevent)
{
RowUpdatingHandler(ruevent);
Expand Down Expand Up @@ -235,7 +237,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect
if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default))
{
// $CONSIDER - not trimming the @ from the beginning but to left the designer do that
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(new char[] { '@', ' ', ':' });
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(s_trimChars);
}
if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,8 @@ public override string ServerVersion
}
}

internal static readonly char[] s_comma = new char[] { ',' };

// grouping the native OLE DB casts togther by required interfaces and optional interfaces, connection then session
// want these to be methods, not properties otherwise they appear in VS7 managed debugger which attempts to evaluate them

Expand Down Expand Up @@ -475,7 +477,7 @@ internal bool AddInfoKeywordsToTable(DataTable table, DataColumn keyword)

if (null != keywords)
{
string[] values = keywords.Split(new char[1] { ',' });
string[] values = keywords.Split(s_comma);
for (int i = 0; i < values.Length; ++i)
{
DataRow row = table.NewRow();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,7 @@ public override bool CanConvertFrom(ITypeDescriptorContext? context, Type source
if (svalue.IndexOf(',') != -1)
{
int convertedValue = 0;
string[] values = svalue.Split(new char[] { ',' });
string[] values = svalue.Split(OleDbConnectionInternal.s_comma);
foreach (string v in values)
{
convertedValue |= (int)Enum.Parse<OleDbServiceValues>(v, true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ private static void SetCannotChangePasswordStatus(Principal ap, bool userCannotC
// even before we call ObjectSecurity to see if it would return null, because once ObjectSecurity returns null the
// first time, it'll keep returning null even if we refresh the cache.
if (!de.Properties.Contains("nTSecurityDescriptor"))
de.RefreshCache(new string[] { "nTSecurityDescriptor" });
de.RefreshCache(s_nTSecurityDescriptor);
ActiveDirectorySecurity adsSecurity = de.ObjectSecurity;

bool denySelfFound;
Expand Down Expand Up @@ -829,7 +829,7 @@ internal override bool IsLockedOut(AuthenticablePrincipal p)
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);

de.RefreshCache(new string[] { "msDS-User-Account-Control-Computed", "lockoutTime" });
de.RefreshCache(s_msDSUACCLockoutTime);

if (de.Properties["msDS-User-Account-Control-Computed"].Count > 0)
{
Expand Down Expand Up @@ -992,31 +992,31 @@ protected void WriteAttribute<T>(Principal p, string attribute, T value)
internal override ResultSet FindByLockoutTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "lockoutTime" }, matchType, dt);
return FindByDate(principalType, s_lockoutTime, matchType, dt);
}

internal override ResultSet FindByLogonTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "lastLogon", "lastLogonTimestamp" }, matchType, dt);
return FindByDate(principalType, s_lastLogonTime, matchType, dt);
}

internal override ResultSet FindByPasswordSetTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "pwdLastSet" }, matchType, dt);
return FindByDate(principalType, s_pwdLastSet, matchType, dt);
}

internal override ResultSet FindByBadPasswordAttempt(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "badPasswordTime" }, matchType, dt);
return FindByDate(principalType, s_badPasswordTime, matchType, dt);
}

internal override ResultSet FindByExpirationTime(
DateTime dt, MatchType matchType, Type principalType)
{
return FindByDate(principalType, new string[] { "accountExpires" }, matchType, dt);
return FindByDate(principalType, s_accountExpires, matchType, dt);
}

private ADEntriesSet FindByDate(Type subtype, string[] ldapAttributes, MatchType matchType, DateTime value)
Expand Down Expand Up @@ -1300,7 +1300,7 @@ internal override ResultSet GetGroupsMemberOf(Principal p)

GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADStoreCtx", "GetGroupsMemberOf: principalDN={0}", principalDN);

principalDE.RefreshCache(new string[] { "memberOf", "primaryGroupID" });
principalDE.RefreshCache(s_memberOfPrimaryGroupId);

if ((principalDE.Properties["primaryGroupID"].Count > 0) &&
(principalDE.Properties["objectSid"].Count > 0))
Expand Down Expand Up @@ -2386,6 +2386,16 @@ private ulong LockoutDuration
protected string contextBasePartitionDN; //contains the DN of the Partition to which the user supplied context base (this.ctxBase) belongs.
protected string dnsHostName;
protected ulong lockoutDuration;
private static readonly string[] s_lockoutTime = new string[] { "lockoutTime" };
private static readonly string[] s_lastLogonTime = new string[] { "lastLogon", "lastLogonTimestamp" };
private static readonly string[] s_pwdLastSet = new string[] { "pwdLastSet" };
private static readonly string[] s_badPasswordTime = new string[] { "badPasswordTime" };
private static readonly string[] s_accountExpires = new string[] { "accountExpires" };
private static readonly string[] s_nTSecurityDescriptor = new string[] { "nTSecurityDescriptor" };
private static readonly string[] s_msDSUACCLockoutTime = new string[] { "msDS-User-Account-Control-Computed", "lockoutTime" };
private static readonly string[] s_memberOfPrimaryGroupId = new string[] { "memberOf", "primaryGroupID" };
private static readonly string[] s_lockoutDuration = new string[] { "lockoutDuration" };
internal static readonly char[] s_comma = new char[] { ',' };

protected enum StoreCapabilityMap
{
Expand Down Expand Up @@ -2415,7 +2425,7 @@ protected virtual void LoadDomainInfo()
this.contextBasePartitionDN = this.defaultNamingContext;

// Split the naming context's DN into its RDNs
string[] ncComponents = defaultNamingContext.Split(new char[] { ',' });
string[] ncComponents = defaultNamingContext.Split(s_comma);

StringBuilder sb = new StringBuilder();

Expand Down Expand Up @@ -2492,7 +2502,7 @@ protected virtual void LoadDomainInfo()
this.authTypes);

// So we don't load every property
domainNC.RefreshCache(new string[] { "lockoutDuration" });
domainNC.RefreshCache(s_lockoutDuration);

if (domainNC.Properties["lockoutDuration"].Count > 0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,7 @@ protected static void CommaStringFromLdapConverter(dSPropertyCollection properti
Debug.Assert(values[0] is string);

string commaSeparatedValues = (string)values[0];
string[] individualValues = commaSeparatedValues.Split(new char[] { ',' });
string[] individualValues = commaSeparatedValues.Split(s_comma);

// ValueCollection<string> is Load'ed from a List<string>
List<string> list = new List<string>(individualValues.Length);
Expand Down Expand Up @@ -1078,7 +1078,7 @@ protected static bool CannotChangePwdFromLdapConverter(DirectoryEntry de)
// first time, it'll keep returning null even if we refresh the cache.

if (!de.Properties.Contains("nTSecurityDescriptor"))
de.RefreshCache(new string[] { "nTSecurityDescriptor" });
de.RefreshCache(s_nTSecurityDescriptor);

ActiveDirectorySecurity adsSecurity = de.ObjectSecurity;

Expand Down Expand Up @@ -1637,6 +1637,8 @@ protected static void UpdateGroupMembership(Principal group, DirectoryEntry de,
}
}

private static readonly string[] s_objectSid = new string[] { "objectSid" };

// Builds a SID dn for the principal <SID=...>
protected static string GetSidPathFromPrincipal(Principal p)
{
Expand All @@ -1661,7 +1663,7 @@ protected static string GetSidPathFromPrincipal(Principal p)

// Force it to load if it hasn't been already loaded
if (!de.Properties.Contains("objectSid"))
de.RefreshCache(new string[] { "objectSid" });
de.RefreshCache(s_objectSid);

byte[] sid = (byte[])de.Properties["objectSid"].Value;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -780,7 +780,7 @@ internal static bool IsObjectFromGC(string path)
internal static string ConstructDnsDomainNameFromDn(string dn)
{
// Split the DN into its RDNs
string[] ncComponents = dn.Split(new char[] { ',' });
string[] ncComponents = dn.Split(ADStoreCtx.s_comma);

StringBuilder sb = new StringBuilder();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,8 @@ internal override void ResetAllChangeStatus()
/// </summary>
internal SearchResult SmallGroupMemberSearchResult { get; private set; }

private static readonly string[] s_member = new string[] { "member" };

/// <summary>
/// Finds if the group is "small", meaning that it has less than MaxValRange values (usually 1500)
/// The property list for the searcher of a group has "member" attribute. if there are more results than MaxValRange, there will also be a "member;range=..." attribute
Expand All @@ -366,7 +368,7 @@ internal bool IsSmallGroup()
Debug.Assert(de != null);
if (de != null)
{
using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", new string[] { "member" }, SearchScope.Base))
using (DirectorySearcher ds = new DirectorySearcher(de, "(objectClass=*)", s_member, SearchScope.Base))
{
SearchResult sr = ds.FindOne();
if (sr != null)
Expand Down
Loading