From 0e106faafe479cdad5df6b95d44159711398c33a Mon Sep 17 00:00:00 2001 From: xtqqczze <45661989+xtqqczze@users.noreply.github.com> Date: Thu, 29 Feb 2024 17:56:22 +0000 Subject: [PATCH] Enable CA1868: Unnecessary call to 'Contains' for sets (#21165) https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1868 --- .globalconfig | 4 ++++ .../CimSessionOperations.cs | 3 +-- .../commands/utility/ConvertFrom-SddlString.cs | 3 +-- .../commands/utility/CsvCommands.cs | 6 +----- .../commands/utility/Update-TypeData.cs | 12 ++++-------- .../common/DisplayDatabase/typeDataQuery.cs | 6 ++---- .../engine/CommandDiscovery.cs | 7 ++----- .../engine/InitialSessionState.cs | 6 +----- .../engine/Modules/ModuleCmdletBase.cs | 6 ++---- .../engine/parser/PSType.cs | 3 +-- .../engine/parser/SemanticChecks.cs | 16 +++------------- .../engine/remoting/client/RemotingProtocol2.cs | 5 +---- .../help/CommandHelpProvider.cs | 5 +---- .../help/HelpFileHelpProvider.cs | 6 +----- .../security/CatalogHelper.cs | 3 +-- 15 files changed, 26 insertions(+), 65 deletions(-) diff --git a/.globalconfig b/.globalconfig index 82db4cdf07..d51e5cfacf 100644 --- a/.globalconfig +++ b/.globalconfig @@ -510,6 +510,10 @@ dotnet_diagnostic.CA1846.severity = warning # https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1847 dotnet_diagnostic.CA1847.severity = warning +# CA1868: Unnecessary call to 'Contains' for sets +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1868 +dotnet_diagnostic.CA1868.severity = warning + # CA2000: Dispose objects before losing scope # https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2000 dotnet_diagnostic.CA2000.severity = none diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index f31e703520..b8ebc9adae 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -535,9 +535,8 @@ namespace Microsoft.Management.Infrastructure.CimCmdlets { if (this.curCimSessionsById.ContainsKey(id)) { - if (!sessionIds.Contains(id)) + if (sessionIds.Add(id)) { - sessionIds.Add(id); sessions.Add(this.curCimSessionsById[id].GetPSObject()); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index f4cddb37be..48bda12cd8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -81,9 +81,8 @@ namespace Microsoft.PowerShell.Commands foreach (string memberName in Enum.GetNames(accessRightType)) { int memberValue = (int)Enum.Parse(accessRightType, memberName); - if (!foundAccessRightValues.Contains(memberValue)) + if (foundAccessRightValues.Add(memberValue)) { - foundAccessRightValues.Add(memberValue); if ((accessMask & memberValue) == memberValue) { foundAccessRightNames.Add(memberName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index d45c4d70cd..d4927a7876 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -1419,11 +1419,7 @@ namespace Microsoft.PowerShell.Commands { if (!string.IsNullOrEmpty(currentHeader)) { - if (!headers.Contains(currentHeader)) - { - headers.Add(currentHeader); - } - else + if (!headers.Add(currentHeader)) { // throw a terminating error as there are duplicate headers in the input. string memberAlreadyPresentMsg = diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index d181112ec8..584bc0c8be 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -792,9 +792,8 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); } } @@ -806,9 +805,8 @@ namespace Microsoft.PowerShell.Commands if (entry.FileName != null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(entry); } } @@ -825,9 +823,8 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); } } @@ -971,9 +968,8 @@ namespace Microsoft.PowerShell.Commands if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(appendPathTotalItem)) + if (fullFileNameHash.Add(appendPathTotalItem)) { - fullFileNameHash.Add(appendPathTotalItem); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index c9ecd0042d..c759cabd2a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -601,8 +601,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // if it is a type reference, just add the type name if (r is TypeReference tr) { - if (!allTypes.Contains(tr.name)) - allTypes.Add(tr.name); + allTypes.Add(tr.name); } else { @@ -619,8 +618,7 @@ namespace Microsoft.PowerShell.Commands.Internal.Format // we found the group, go over it foreach (TypeReference x in tgd.typeReferenceList) { - if (!allTypes.Contains(x.name)) - allTypes.Add(x.name); + allTypes.Add(x.name); } } } diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index c656f23fc3..561a33ccba 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -1151,10 +1151,8 @@ namespace System.Management.Automation case "ActivePostCommand": currentActionSet = _activePostCommand; break; } - if (currentActionSet.Contains(command)) + if (!currentActionSet.Add(command)) throw new InvalidOperationException(); - else - currentActionSet.Add(command); } internal void UnregisterLookupCommandInfoAction(string currentAction, string command) @@ -1168,8 +1166,7 @@ namespace System.Management.Automation case "ActivePostCommand": currentActionSet = _activePostCommand; break; } - if (currentActionSet.Contains(command)) - currentActionSet.Remove(command); + currentActionSet.Remove(command); } private readonly HashSet _activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 0a2d3fa74d..2af3ac56ba 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -1569,14 +1569,10 @@ namespace System.Management.Automation.Runspaces string assembly = ss.Assemblies[i].FileName; if (!string.IsNullOrEmpty(assembly)) { - if (assemblyList.Contains(assembly)) + if (!assemblyList.Add(assembly)) { ss.Assemblies.RemoveItem(i); } - else - { - assemblyList.Add(assembly); - } } } diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 48b68574f5..3bbb9126fa 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -1047,9 +1047,8 @@ namespace Microsoft.PowerShell.Commands PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh); if (module != null) { - if (!modules.Contains(resolvedModulePath)) + if (modules.Add(resolvedModulePath)) { - modules.Add(resolvedModulePath); yield return module; } } @@ -1078,9 +1077,8 @@ namespace Microsoft.PowerShell.Commands foundModule = true; // We need to list all versions of the module. string subModulePath = Path.GetDirectoryName(file); - if (!modules.Contains(subModulePath)) + if (modules.Add(subModulePath)) { - modules.Add(subModulePath); yield return module; } } diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index d01a22c305..c5b0d9df98 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -1321,9 +1321,8 @@ namespace System.Management.Automation.Language foreach (var typeDefinitionAst in typeDefinitions) { var typeName = GetClassNameInAssembly(typeDefinitionAst); - if (!definedTypes.Contains(typeName)) + if (definedTypes.Add(typeName)) { - definedTypes.Add(typeName); if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Class) == TypeAttributes.Class) { defineTypeHelpers.Add(new DefineTypeHelper(parser, module, typeDefinitionAst, typeName)); diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 20d0a552cf..4a2a3bb626 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -90,17 +90,13 @@ namespace System.Management.Automation.Language foreach (var parameter in parameters) { string parameterName = parameter.Name.VariablePath.UserPath; - if (parametersSet.Contains(parameterName)) + if (!parametersSet.Add(parameterName)) { _parser.ReportError(parameter.Name.Extent, nameof(ParserStrings.DuplicateFormalParameter), ParserStrings.DuplicateFormalParameter, parameterName); } - else - { - parametersSet.Add(parameterName); - } var voidConstraint = parameter.Attributes.OfType().FirstOrDefault(static t => typeof(void) == t.TypeName.GetReflectionType()); @@ -242,7 +238,7 @@ namespace System.Management.Automation.Language foreach (var namedArg in attributeAst.NamedArguments) { string name = namedArg.ArgumentName; - if (names.Contains(name)) + if (!names.Add(name)) { _parser.ReportError(namedArg.Extent, nameof(ParserStrings.DuplicateNamedArgument), @@ -251,8 +247,6 @@ namespace System.Management.Automation.Language } else { - names.Add(name); - if (!namedArg.ExpressionOmitted && !IsValidAttributeArgument(namedArg.Argument, constantValueVisitor)) { var error = GetNonConstantAttributeArgErrorExpr(constantValueVisitor); @@ -1124,7 +1118,7 @@ namespace System.Management.Automation.Language if (keyStrAst != null) { var keyStr = keyStrAst.Value.ToString(); - if (keys.Contains(keyStr)) + if (!keys.Add(keyStr)) { string errorId; string errorMsg; @@ -1141,10 +1135,6 @@ namespace System.Management.Automation.Language _parser.ReportError(entry.Item1.Extent, errorId, errorMsg, keyStr); } - else - { - keys.Add(keyStr); - } } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index ed01bc7ad1..8aa0c04671 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -797,10 +797,7 @@ namespace System.Management.Automation.Internal return; } - if (_preparingForDisconnectList.Contains(bcmdTM)) - { - _preparingForDisconnectList.Remove(bcmdTM); - } + _preparingForDisconnectList.Remove(bcmdTM); if (_preparingForDisconnectList.Count == 0) { diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index f55b345e45..15af80745d 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -1081,10 +1081,7 @@ namespace System.Management.Automation { // this command is not visible to the user (from CommandOrigin) so // dont show help topic for it. - if (!hiddenCommands.Contains(helpName)) - { - hiddenCommands.Add(helpName); - } + hiddenCommands.Add(helpName); continue; } diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 71680c1386..a6c21a3bac 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -170,11 +170,7 @@ namespace System.Management.Automation { string fileName = Path.GetFileName(file); - if (!fileNameHash.Contains(fileName)) - { - fileNameHash.Add(fileName); - } - else + if (!fileNameHash.Add(fileName)) { // If the file need to be removed, add it to matchedFilesToRemove, if not already present. if (!matchedFilesToRemove.Contains(file)) diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index e815d73e04..4892f7434e 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -220,9 +220,8 @@ namespace System.Management.Automation relativePath = fileToHash.Name; } - if (!relativePaths.Contains(relativePath)) + if (relativePaths.Add(relativePath)) { - relativePaths.Add(relativePath); if (fileToHash.Length != 0) { cdfFilesContent += "" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine;