Skip to content

Commit 5e67657

Browse files
buyaa-nstephentoubdanmoseley
authored
Fix warnings found with CA1861 Avoid constant arrays as arguments (#86229)
* Fix warnings found with CA1861 * Update src/coreclr/tools/aot/ILCompiler/Program.cs Co-authored-by: Stephen Toub <stoub@microsoft.com> * Remove supression from static field * Revert using string.Split(char) * Update src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs --------- Co-authored-by: Stephen Toub <stoub@microsoft.com> Co-authored-by: Dan Moseley <danmose@microsoft.com>
1 parent ed26344 commit 5e67657

File tree

48 files changed

+197
-107
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+197
-107
lines changed

eng/CodeAnalysis.src.globalconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,9 @@ dotnet_diagnostic.CA1859.severity = warning
471471
# CA1860: Avoid using 'Enumerable.Any()' extension method
472472
dotnet_diagnostic.CA1860.severity = warning
473473

474+
# CA1861: Avoid constant arrays as arguments
475+
dotnet_diagnostic.CA1861.severity = warning
476+
474477
# CA2000: Dispose objects before losing scope
475478
dotnet_diagnostic.CA2000.severity = none
476479

eng/CodeAnalysis.test.globalconfig

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,9 @@ dotnet_diagnostic.CA1859.severity = none
468468
# CA1860: Avoid using 'Enumerable.Any()' extension method
469469
dotnet_diagnostic.CA1860.severity = none
470470

471+
# CA1861: Avoid constant arrays as arguments
472+
dotnet_diagnostic.CA1861.severity = none
473+
471474
# CA2000: Dispose objects before losing scope
472475
dotnet_diagnostic.CA2000.severity = none
473476

src/coreclr/tools/aot/ILCompiler/ILCompilerRootCommand.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,9 +267,11 @@ public ILCompilerRootCommand(string[] args) : base(".NET Native IL Compiler")
267267
// + the original command line arguments
268268
// + a rsp file that should work to directly run out of the zip file
269269

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

275277
context.ExitCode = new Program(this).Run();

src/coreclr/tools/aot/ILCompiler/Program.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ namespace ILCompiler
2929
internal sealed class Program
3030
{
3131
private readonly ILCompilerRootCommand _command;
32+
private static readonly char[] s_separator = new char[] { ',', ';', ' ' };
3233

3334
public Program(ILCompilerRootCommand command)
3435
{
@@ -682,7 +683,7 @@ private static IEnumerable<int> ProcessWarningCodes(IEnumerable<string> warningC
682683
{
683684
foreach (string value in warningCodes)
684685
{
685-
string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
686+
string[] values = value.Split(s_separator, StringSplitOptions.RemoveEmptyEntries);
686687
foreach (string id in values)
687688
{
688689
if (!id.StartsWith("IL", StringComparison.Ordinal) || !ushort.TryParse(id.AsSpan(2), out ushort code))

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/IDispatchMetaObject.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ namespace Microsoft.CSharp.RuntimeBinder.ComInterop
1111
internal sealed class IDispatchMetaObject : ComFallbackMetaObject
1212
{
1313
private readonly IDispatchComObject _self;
14+
private static readonly bool[] s_false = new bool[] { false };
1415

1516
[RequiresUnreferencedCode(Binder.TrimmerWarning)]
1617
internal IDispatchMetaObject(Expression expression, IDispatchComObject self)
@@ -218,7 +219,7 @@ private DynamicMetaObject TryPropertyPut(SetMemberBinder binder, DynamicMetaObje
218219
DynamicMetaObject result = new ComInvokeBinder(
219220
new CallInfo(1),
220221
new[] { value },
221-
new bool[] { false },
222+
s_false,
222223
restrictions,
223224
Expression.Constant(method),
224225
dispatch,

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/ComInterop/VariantArray.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ internal static class VariantArray
4949
// Don't need a dictionary for this, it will have very few elements
5050
// (guaranteed less than 28, in practice 0-2)
5151
private static readonly List<Type> s_generatedTypes = new List<Type>(0);
52+
private static readonly string[] s_genericTName = new string[] { "T" };
5253

5354
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray1))]
5455
[DynamicDependency(DynamicallyAccessedMemberTypes.PublicFields, typeof(VariantArray2))]
@@ -100,7 +101,7 @@ private static Type CreateCustomType(int size)
100101
{
101102
TypeAttributes attrs = TypeAttributes.NotPublic | TypeAttributes.SequentialLayout;
102103
TypeBuilder type = UnsafeMethods.DynamicModule.DefineType("VariantArray" + size, attrs, typeof(ValueType));
103-
GenericTypeParameterBuilder T = type.DefineGenericParameters(new string[] { "T" })[0];
104+
GenericTypeParameterBuilder T = type.DefineGenericParameters(s_genericTName)[0];
104105
for (int i = 0; i < size; i++)
105106
{
106107
type.DefineField("Element" + i, T, FieldAttributes.Public);

src/libraries/Microsoft.CSharp/src/Microsoft/CSharp/RuntimeBinder/Semantics/ExpressionBinder.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,7 @@ private void AdjustCallArgumentsForParams(CType callingObjectType, CType type, M
11511151
CType arrayType = (ArrayType)TypeManager.SubstType(mp.Params[mp.Params.Count - 1], type, pTypeArgs);
11521152

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

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

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

12351235
if (it.AtEnd())
@@ -1618,6 +1618,8 @@ private static void CheckUnsafe(CType type)
16181618

16191619
private AggregateSymbol ContextForMemberLookup => Context.ContextForMemberLookup;
16201620

1621+
private static readonly int[] s_zero = new[] { 0 };
1622+
16211623
private static ExprWrap WrapShortLivedExpression(Expr expr) => ExprFactory.CreateWrap(expr);
16221624

16231625
private static ExprAssignment GenerateOptimizedAssignment(Expr op1, Expr op2) => ExprFactory.CreateAssignment(op1, op2);

src/libraries/Microsoft.Extensions.DependencyModel/src/DependencyContextPaths.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ internal sealed class DependencyContextPaths
2020

2121
public IEnumerable<string> NonApplicationPaths { get; }
2222

23+
private static readonly char[] s_semicolon = new[] { ';' };
24+
2325
public DependencyContextPaths(
2426
string? application,
2527
string? sharedRuntime,
@@ -40,7 +42,7 @@ private static DependencyContextPaths GetCurrent()
4042

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

4648
string[]? nonApplicationPaths = files?

src/libraries/Microsoft.Extensions.Logging.EventSource/src/LoggingEventSource.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ public static class Keywords
117117
private const string UseAppFilters = "UseAppFilters";
118118
private const string WriteEventCoreSuppressionJustification = "WriteEventCore is safe when eventData object is a primitive type which is in this case.";
119119
private const string WriteEventDynamicDependencySuppressionJustification = "DynamicDependency attribute will ensure that the required properties are not trimmed.";
120+
private static readonly char[] s_semicolon = new[] { ';' };
121+
private static readonly char[] s_colon = new[] { ':' };
120122

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

367369
var rules = new List<LoggerFilterRule>();
368370
int ruleStringsStartIndex = 0;
369-
string[] ruleStrings = filterSpec.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
371+
string[] ruleStrings = filterSpec.Split(s_semicolon, StringSplitOptions.RemoveEmptyEntries);
370372
if (ruleStrings.Length > 0 && ruleStrings[0].Equals(UseAppFilters, StringComparison.OrdinalIgnoreCase))
371373
{
372374
// Avoid adding default rule to disable event source loggers
@@ -381,7 +383,7 @@ private static LoggerFilterRule[] ParseFilterSpec(string? filterSpec, LogLevel d
381383
{
382384
string rule = ruleStrings[i];
383385
LogLevel level = defaultLevel;
384-
string[] parts = rule.Split(new[] { ':' }, 2);
386+
string[] parts = rule.Split(s_colon, 2);
385387
string loggerName = parts[0];
386388
if (loggerName.Length == 0)
387389
{

src/libraries/System.Data.OleDb/src/OleDbCommandBuilder.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ public OleDbCommandBuilder(OleDbDataAdapter? adapter) : this()
3333
}
3434
}
3535

36+
private static readonly char[] s_trimChars = new char[] { '@', ' ', ':' };
37+
3638
private void OleDbRowUpdatingHandler(object sender, OleDbRowUpdatingEventArgs ruevent)
3739
{
3840
RowUpdatingHandler(ruevent);
@@ -235,7 +237,7 @@ private static OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnect
235237
if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default))
236238
{
237239
// $CONSIDER - not trimming the @ from the beginning but to left the designer do that
238-
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(new char[] { '@', ' ', ':' });
240+
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture)!.TrimStart(s_trimChars);
239241
}
240242
if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default))
241243
{

0 commit comments

Comments
 (0)