From 199a9688aff8ffc2c0a5ed66cc3fe5f40b2c96fc Mon Sep 17 00:00:00 2001 From: Tamas Vajk Date: Fri, 28 Jun 2024 11:09:40 +0200 Subject: [PATCH] C#: Fix quality issues --- .../CSharpDiagnosticClassifier.cs | 2 +- .../Semmle.Autobuild.CSharp/DotNetRule.cs | 6 ++---- .../Semmle.Autobuild.Shared/BuildTools.cs | 2 +- .../Semmle.Autobuild.Shared/DiagnosticClassifier.cs | 2 +- .../Semmle.Autobuild.Shared/MsBuildRule.cs | 6 +++--- .../AssemblyCache.cs | 6 +++--- .../AssemblyInfo.cs | 2 +- .../AssemblyLookupLocation.cs | 2 +- .../Assets.cs | 2 -- .../DependencyContainer.cs | 8 +++----- .../DependencyManager.cs | 2 +- .../DotNet.cs | 2 +- .../DotNetCliInvoker.cs | 6 +++--- .../EnvironmentVariableNames.cs | 2 +- .../NugetExeWrapper.cs | 6 +++--- .../NugetPackageRestorer.cs | 12 +++++------- .../StubVisitor.cs | 10 +++++----- .../SymbolExtensions.cs | 4 ++-- .../Comments/CommentBinding.cs | 2 +- .../Comments/CommentLineType.cs | 2 +- .../Semmle.Extraction.CSharp/Entities/Assembly.cs | 2 +- .../Entities/Compilations/Compilation.cs | 2 +- .../Entities/ExpressionNodeInfo.cs | 2 +- .../Entities/Expressions/Assignment.cs | 4 ++-- .../Entities/Expressions/Patterns/PropertyPattern.cs | 2 +- .../Semmle.Extraction.CSharp/Entities/Parameter.cs | 2 +- .../Semmle.Extraction.CSharp/Extractor/Analyser.cs | 4 ++-- .../Extractor/CompilerVersion.cs | 10 ++++++---- .../Semmle.Extraction.CSharp/Extractor/Context.cs | 2 +- .../Populators/DirectiveVisitor.cs | 2 +- csharp/extractor/Semmle.Extraction.Tests/DotNet.cs | 4 ++-- csharp/extractor/Semmle.Extraction.Tests/Options.cs | 2 +- csharp/extractor/Semmle.Extraction/Context.cs | 2 +- .../Semmle.Extraction/EscapingTextWriter.cs | 2 +- .../Semmle.Extraction/Extractor/ExtractionContext.cs | 2 +- csharp/extractor/Semmle.Extraction/Id.cs | 2 +- .../extractor/Semmle.Extraction/PathTransformer.cs | 2 +- csharp/extractor/Semmle.Extraction/TrapWriter.cs | 4 ++-- csharp/extractor/Semmle.Util/BuildScript.cs | 2 +- csharp/extractor/Semmle.Util/CanonicalPathCache.cs | 2 +- csharp/extractor/Semmle.Util/EnvironmentVariables.cs | 2 +- csharp/extractor/Semmle.Util/FileUtils.cs | 6 +++--- csharp/extractor/Semmle.Util/Initializer.cs | 2 +- csharp/extractor/Semmle.Util/LineCounter.cs | 2 +- csharp/extractor/Semmle.Util/Logging/FileLogger.cs | 4 ++-- .../extractor/Semmle.Util/Logging/PidStreamWriter.cs | 2 +- csharp/extractor/Semmle.Util/MemoizedFunc.cs | 4 ++-- 47 files changed, 79 insertions(+), 85 deletions(-) diff --git a/csharp/autobuilder/Semmle.Autobuild.CSharp/CSharpDiagnosticClassifier.cs b/csharp/autobuilder/Semmle.Autobuild.CSharp/CSharpDiagnosticClassifier.cs index 85d6c872c84b..2f947d7c33d4 100644 --- a/csharp/autobuilder/Semmle.Autobuild.CSharp/CSharpDiagnosticClassifier.cs +++ b/csharp/autobuilder/Semmle.Autobuild.CSharp/CSharpDiagnosticClassifier.cs @@ -99,7 +99,7 @@ public override void Fire(DiagnosticClassifier classifier, Match match) { if (!match.Groups.TryGetValue("projectFile", out var projectFile)) throw new ArgumentException("Expected regular expression match to contain projectFile"); - if (!match.Groups.TryGetValue("location", out var location)) + if (!match.Groups.TryGetValue("location", out _)) throw new ArgumentException("Expected regular expression match to contain location"); var result = classifier.Results.OfType().FirstOrDefault(); diff --git a/csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs b/csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs index 20ed6f0e4129..43efcd0352f0 100644 --- a/csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs +++ b/csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs @@ -1,9 +1,7 @@ using System; using System.Collections.Generic; -using System.IO; using System.Linq; using Semmle.Util; -using Semmle.Util.Logging; using Semmle.Autobuild.Shared; using Semmle.Extraction.CSharp.DependencyFetching; @@ -15,14 +13,14 @@ namespace Semmle.Autobuild.CSharp /// internal class DotNetRule : IBuildRule { - public readonly List FailedProjectsOrSolutions = new(); + public List FailedProjectsOrSolutions { get; } = []; /// /// A list of projects which are incompatible with DotNet. /// public IEnumerable> NotDotNetProjects { get; private set; } - public DotNetRule() => NotDotNetProjects = new List>(); + public DotNetRule() => NotDotNetProjects = []; public BuildScript Analyse(IAutobuilder builder, bool auto) { diff --git a/csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs b/csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs index 0e910b68d48a..c445fcb805a0 100644 --- a/csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs +++ b/csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs @@ -18,7 +18,7 @@ public VcVarsBatFile(string path, int version) Path = path; ToolsVersion = version; } - }; + } /// /// Collection of available Visual Studio build tools. diff --git a/csharp/autobuilder/Semmle.Autobuild.Shared/DiagnosticClassifier.cs b/csharp/autobuilder/Semmle.Autobuild.Shared/DiagnosticClassifier.cs index 94af39ca9598..43db196d9f69 100644 --- a/csharp/autobuilder/Semmle.Autobuild.Shared/DiagnosticClassifier.cs +++ b/csharp/autobuilder/Semmle.Autobuild.Shared/DiagnosticClassifier.cs @@ -60,7 +60,7 @@ public virtual void Fire(DiagnosticClassifier classifier, Match match) { } public class DiagnosticClassifier { private readonly List rules; - public readonly List Results; + public List Results { get; } public DiagnosticClassifier() { diff --git a/csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs b/csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs index eaf9449af417..7827fe5c2e1e 100644 --- a/csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs +++ b/csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs @@ -32,7 +32,7 @@ public class MsBuildRule : IBuildRule /// /// A list of solutions or projects which failed to build. /// - public readonly List FailedProjectsOrSolutions = new(); + public List FailedProjectsOrSolutions { get; } = []; public BuildScript Analyse(IAutobuilder builder, bool auto) { @@ -60,7 +60,7 @@ public BuildScript Analyse(IAutobuilder builder, bool au // Use `nuget.exe` from source code repo, if present, otherwise first attempt with global // `nuget` command, and if that fails, attempt to download `nuget.exe` from nuget.org var nuget = builder.GetFilename("nuget.exe").Select(t => t.Item1).FirstOrDefault() ?? "nuget"; - var nugetDownloadPath = builder.Actions.PathCombine(FileUtils.GetTemporaryWorkingDirectory(builder.Actions.GetEnvironmentVariable, builder.Options.Language.UpperCaseName, out var _), ".nuget", "nuget.exe"); + var nugetDownloadPath = builder.Actions.PathCombine(FileUtils.GetTemporaryWorkingDirectory(builder.Actions.GetEnvironmentVariable, builder.Options.Language.UpperCaseName, out _), ".nuget", "nuget.exe"); var nugetDownloaded = false; var ret = BuildScript.Success; @@ -126,7 +126,7 @@ BuildScript GetNugetRestoreScript() => var platform = projectOrSolution is ISolution s1 ? s1.DefaultPlatformName : null; var configuration = projectOrSolution is ISolution s2 ? s2.DefaultConfigurationName : null; - command.Argument("/t:" + target); + command.Argument($"/t:{target}"); if (platform is not null) command.Argument($"/p:Platform=\"{platform}\""); if (configuration is not null) diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyCache.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyCache.cs index 62a053870e91..953c0adc5521 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyCache.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyCache.cs @@ -133,12 +133,12 @@ public AssemblyInfo GetAssemblyInfo(string filepath) private readonly List dllsToIndex = new List(); - private readonly Dictionary assemblyInfoByFileName = new Dictionary(); + private readonly Dictionary assemblyInfoByFileName = []; // Map from assembly id (in various formats) to the full info. - private readonly Dictionary assemblyInfoById = new Dictionary(); + private readonly Dictionary assemblyInfoById = []; - private readonly HashSet failedAssemblyInfoIds = new HashSet(); + private readonly HashSet failedAssemblyInfoIds = []; private readonly ILogger logger; } diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs index d77005bf458b..b02f33842a60 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs @@ -94,7 +94,7 @@ private AssemblyInfo(string id, string filename) { var sections = id.Split(new string[] { ", " }, StringSplitOptions.None); - Name = sections.First(); + Name = sections[0]; foreach (var section in sections.Skip(1)) { diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyLookupLocation.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyLookupLocation.cs index d1d3eda772d0..af24f1bddf5a 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyLookupLocation.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyLookupLocation.cs @@ -80,7 +80,7 @@ public List GetDlls(ILogger logger) } else { - logger.LogDebug("AssemblyLookupLocation: Path not found: " + path); + logger.LogDebug($"AssemblyLookupLocation: Path not found: {path}"); } return dllsToIndex; } diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/Assets.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/Assets.cs index 9308a137e7e3..ef2c47397b05 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/Assets.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/Assets.cs @@ -120,8 +120,6 @@ private void AddPackageDependencies(JObject json, string jsonPath) info.Compile .ForEach(r => Dependencies.Add(name, r.Key)); }); - - return; } /// diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyContainer.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyContainer.cs index 230731104124..b5abefb3a651 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyContainer.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyContainer.cs @@ -12,12 +12,12 @@ internal class DependencyContainer /// /// Paths to dependencies required for compilation. /// - public HashSet Paths { get; } = new(); + public HashSet Paths { get; } = []; /// /// Packages that are used as a part of the required dependencies. /// - public HashSet Packages { get; } = new(); + public HashSet Packages { get; } = []; /// /// If the path specifically adds a .dll we use that, otherwise we as a fallback @@ -33,9 +33,7 @@ private static string ParseFilePath(string path) } private static string GetPackageName(string package) => - package - .Split(Path.DirectorySeparatorChar) - .First(); + package.Split(Path.DirectorySeparatorChar)[0]; /// /// Add a dependency inside a package. diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyManager.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyManager.cs index f18d30f4f192..4866df1260e2 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyManager.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyManager.cs @@ -310,7 +310,7 @@ private void AddNetFrameworkDlls(ISet dllLocations, ISet if (runtimeLocation is null) { - runtimeLocation ??= Runtime.ExecutingRuntime; + runtimeLocation = Runtime.ExecutingRuntime; dllLocations.Add(new AssemblyLookupLocation(runtimeLocation, name => !name.StartsWith("Semmle."))); } else diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs index 642403271ff3..655c89abd771 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs @@ -230,7 +230,7 @@ BuildScript GetInstall(string pwsh) => Argument("-ExecutionPolicy"). Argument("unrestricted"). Argument("-Command"). - Argument("\"" + psCommand + "\""). + Argument($"\"{psCommand}\""). Script; return GetInstall("pwsh") | GetInstall("powershell"); diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNetCliInvoker.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNetCliInvoker.cs index 126780212270..4295cce67167 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNetCliInvoker.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNetCliInvoker.cs @@ -58,13 +58,13 @@ private bool RunCommandAux(string args, string? workingDirectory, out IList + public bool RunCommand(string args, bool silent = true) => RunCommandAux(args, null, out _, silent); - public bool RunCommand(string args, out IList output, bool silent) => + public bool RunCommand(string args, out IList output, bool silent = true) => RunCommandAux(args, null, out output, silent); - public bool RunCommand(string args, string? workingDirectory, out IList output, bool silent) => + public bool RunCommand(string args, string? workingDirectory, out IList output, bool silent = true) => RunCommandAux(args, workingDirectory, out output, silent); } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/EnvironmentVariableNames.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/EnvironmentVariableNames.cs index d9a0eac4845a..345cb43453fc 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/EnvironmentVariableNames.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/EnvironmentVariableNames.cs @@ -1,6 +1,6 @@ namespace Semmle.Extraction.CSharp.DependencyFetching { - internal class EnvironmentVariableNames + internal static class EnvironmentVariableNames { /// /// Controls whether to generate source files from resources (`.resx`). diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetExeWrapper.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetExeWrapper.cs index 262ae4b19edd..0371aed16e2d 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetExeWrapper.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetExeWrapper.cs @@ -51,7 +51,7 @@ public NugetExeWrapper(FileProvider fileProvider, TemporaryDirectory packageDire { if (File.Exists(nugetConfigPath)) { - var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out var _); + var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out _); do { @@ -188,7 +188,7 @@ private bool TryRestoreNugetPackage(string packagesConfig) var threadId = Environment.CurrentManagedThreadId; void onOut(string s) => logger.LogDebug(s, threadId); void onError(string s) => logger.LogError(s, threadId); - var exitCode = pi.ReadOutput(out var _, onOut, onError); + var exitCode = pi.ReadOutput(out _, onOut, onError); if (exitCode != 0) { logger.LogError($"Command {pi.FileName} {pi.Arguments} failed with exit code {exitCode}"); @@ -264,7 +264,7 @@ private void RunMonoNugetCommand(string command, out IList stdout) private void AddDefaultPackageSource(string nugetConfig) { logger.LogInfo("Adding default package source..."); - RunMonoNugetCommand($"sources add -Name DefaultNugetOrg -Source {NugetPackageRestorer.PublicNugetOrgFeed} -ConfigFile \"{nugetConfig}\"", out var _); + RunMonoNugetCommand($"sources add -Name DefaultNugetOrg -Source {NugetPackageRestorer.PublicNugetOrgFeed} -ConfigFile \"{nugetConfig}\"", out _); } public void Dispose() diff --git a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs index 0204e9b7c408..4ad4c8c9e31a 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs @@ -538,7 +538,7 @@ private void TryChangePackageVersion(DirectoryInfo tempDir, string newVersion) TryChangeProjectFile(tempDir, PackageReferenceVersion(), $"Version=\"{newVersion}\"", "package reference version"); } - private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, string replacement, string patternName) + private void TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, string replacement, string patternName) { try { @@ -548,7 +548,7 @@ private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, strin if (csprojs.Length != 1) { logger.LogError($"Could not find the .csproj file in {projectDir.FullName}, count = {csprojs.Length}"); - return false; + return; } var csproj = csprojs[0]; @@ -557,18 +557,16 @@ private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, strin if (matches.Count == 0) { logger.LogError($"Could not find the {patternName} in {csproj.FullName}"); - return false; + return; } content = pattern.Replace(content, replacement, 1); File.WriteAllText(csproj.FullName, content); - return true; } catch (Exception exc) { logger.LogError($"Failed to change the {patternName} in {projectDir.FullName}: {exc}"); } - return false; } private static async Task ExecuteGetRequest(string address, HttpClient httpClient, CancellationToken cancellationToken) @@ -644,7 +642,7 @@ private bool CheckFeeds(out HashSet explicitFeeds) (explicitFeeds, var allFeeds) = GetAllFeeds(); var excludedFeeds = EnvironmentVariables.GetURLs(EnvironmentVariableNames.ExcludedNugetFeedsFromResponsivenessCheck) - .ToHashSet() ?? []; + .ToHashSet(); if (excludedFeeds.Count > 0) { @@ -779,7 +777,7 @@ private static string ComputeTempDirectoryPath(string srcDir, string subfolderNa foreach (var b in sha.Take(8)) sb.AppendFormat("{0:x2}", b); - return Path.Combine(FileUtils.GetTemporaryWorkingDirectory(out var _), sb.ToString(), subfolderName); + return Path.Combine(FileUtils.GetTemporaryWorkingDirectory(out _), sb.ToString(), subfolderName); } } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs b/csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs index 56a20473fa3f..b100e2d07779 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs @@ -201,12 +201,12 @@ private void StubTypedConstant(TypedConstant c) } } - private static readonly HashSet attributeAllowList = new() { + private static readonly HashSet attributeAllowList = [ "System.FlagsAttribute", "System.AttributeUsageAttribute", "System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute", "System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", - }; + ]; private void StubAttribute(AttributeData a, string prefix, bool addNewLine) { @@ -298,7 +298,7 @@ private static bool IsUnsafe(ITypeSymbol symbol) => (symbol is INamedTypeSymbol named && named.TypeArguments.Any(IsUnsafe)) || (symbol is IArrayTypeSymbol at && IsUnsafe(at.ElementType)); - private static readonly HashSet keywords = new() { + private static readonly HashSet keywords = [ "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", @@ -308,10 +308,10 @@ private static bool IsUnsafe(ITypeSymbol symbol) => "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile", "while" - }; + ]; private static string EscapeIdentifier(string identifier) => - keywords.Contains(identifier) ? "@" + identifier : identifier; + keywords.Contains(identifier) ? $"@{identifier}" : identifier; private static bool TryGetConstantValue(IFieldSymbol symbol, out string value) { diff --git a/csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs b/csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs index 141189091b0c..659b26c2fe99 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs @@ -110,8 +110,8 @@ static bool TryGetOperatorSymbolFromName(string methodName, out string operatorN var match = CheckedRegex().Match(methodName); if (match.Success) { - TryGetOperatorSymbolFromName("op_" + match.Groups[1], out var uncheckedName); - operatorName = "checked " + uncheckedName; + TryGetOperatorSymbolFromName($"op_{match.Groups[1]}", out var uncheckedName); + operatorName = $"checked {uncheckedName}"; break; } operatorName = methodName; diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentBinding.cs b/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentBinding.cs index 22518ba49301..2089cf7d8fe6 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentBinding.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentBinding.cs @@ -9,5 +9,5 @@ public enum CommentBinding Best, // The most likely element associated with a comment Before, // The element before the comment After // The element after the comment - }; + } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentLineType.cs b/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentLineType.cs index 8506ca701b3e..94ef2dbfa4b8 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentLineType.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentLineType.cs @@ -9,5 +9,5 @@ public enum CommentLineType XmlDoc, // Comment starting /// ... Multiline, // Comment starting /* ..., even if the comment only spans one line. MultilineContinuation // The second and subsequent lines of comment in a multiline comment. - }; + } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Assembly.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Assembly.cs index 849051632531..0fa9422e08ca 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Assembly.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Assembly.cs @@ -24,7 +24,7 @@ private Assembly(Context cx, Microsoft.CodeAnalysis.Location? init) { assembly = init!.MetadataModule!.ContainingAssembly; var identity = assembly.Identity; - var idString = identity.Name + " " + identity.Version; + var idString = $"{identity.Name} {identity.Version}"; assemblyPath = cx.ExtractionContext.GetAssemblyFile(idString); } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Compilations/Compilation.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Compilations/Compilation.cs index 0ba1965723eb..8685c9d7a7dc 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Compilations/Compilation.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Compilations/Compilation.cs @@ -9,7 +9,7 @@ namespace Semmle.Extraction.CSharp.Entities { internal class Compilation : CachedEntity { - internal readonly ConcurrentDictionary messageCounts = new(); + internal readonly ConcurrentDictionary messageCounts = []; private readonly string cwd; private readonly string[] args; diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/ExpressionNodeInfo.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/ExpressionNodeInfo.cs index 4e99689ebe0c..a78f7e8c80b9 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/ExpressionNodeInfo.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/ExpressionNodeInfo.cs @@ -193,7 +193,7 @@ private bool TryGetStringValueFromUtf8Literal(out string? value) public bool IsBoolLiteral() { - return TryGetBoolValueFromLiteral(out var _); + return TryGetBoolValueFromLiteral(out _); } } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Assignment.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Assignment.cs index 4de5e460e6d9..f3e2e510cd64 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Assignment.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Assignment.cs @@ -76,7 +76,7 @@ private static ExprKind GetAssignmentOperation(Context cx, AssignmentExpressionS case SyntaxKind.QuestionQuestionEqualsToken: return ExprKind.ASSIGN_COALESCE; default: - cx.ModelError(syntax, "Unrecognised assignment type " + GetKind(cx, syntax)); + cx.ModelError(syntax, $"Unrecognised assignment type {GetKind(cx, syntax)}"); return ExprKind.UNKNOWN; } } @@ -152,7 +152,7 @@ private ExprKind? OperatorKind case ExprKind.ASSIGN_COALESCE: return ExprKind.NULL_COALESCING; default: - Context.ModelError(Syntax, "Couldn't unfold assignment of type " + kind); + Context.ModelError(Syntax, $"Couldn't unfold assignment of type {kind}"); return ExprKind.UNKNOWN; } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/PropertyPattern.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/PropertyPattern.cs index a195d9ffb832..aa9d4eaea88d 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/PropertyPattern.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/PropertyPattern.cs @@ -25,7 +25,7 @@ private record AccessStep(string Identifier, Microsoft.CodeAnalysis.Location Loc private class AccessStepPack { - public readonly List Prefix = new(); + public List Prefix { get; } = []; public AccessStep Last { get; private set; } public AccessStepPack Add(string identifier, Microsoft.CodeAnalysis.Location location) diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Parameter.cs b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Parameter.cs index 5843418255ce..8c6a65ad5538 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Entities/Parameter.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Entities/Parameter.cs @@ -99,7 +99,7 @@ private string Name // This breaks our database constraints. // Generate an impossible name to ensure that it doesn't conflict. var conflictingCount = Symbol.ContainingSymbol.GetParameters().Count(p => p.Ordinal < Symbol.Ordinal && p.Name == Symbol.Name); - return conflictingCount > 0 ? Symbol.Name + "`" + conflictingCount : Symbol.Name; + return conflictingCount > 0 ? $"{Symbol.Name}`{conflictingCount}" : Symbol.Name; } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Analyser.cs b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Analyser.cs index 45228e8b81d8..460d667147df 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Analyser.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Analyser.cs @@ -106,7 +106,7 @@ protected void SetReferencePaths() { var reader = new System.Reflection.Metadata.MetadataReader(metadata.Pointer, metadata.Length); var def = reader.GetAssemblyDefinition(); - assemblyIdentity = reader.GetString(def.Name) + " " + def.Version; + assemblyIdentity = $"{reader.GetString(def.Name)} {def.Version}"; } ExtractionContext.SetAssemblyFile(assemblyIdentity, refPath); @@ -346,7 +346,7 @@ public virtual void Dispose() /// public void LogExtractorInfo() { - Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs().First()}"); + Logger.LogInfo($" Extractor: {Environment.GetCommandLineArgs()[0]}"); Logger.LogInfo($" Extractor version: {Version}"); Logger.LogInfo($" Current working directory: {Directory.GetCurrentDirectory()}"); } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/CompilerVersion.cs b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/CompilerVersion.cs index a84a912d85ed..e52c79a17e19 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/CompilerVersion.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/CompilerVersion.cs @@ -34,7 +34,7 @@ public string? SkipReason private set; } - private static readonly Dictionary knownCompilerNames = new Dictionary + private static readonly Dictionary knownCompilerNames = new() { { "csc.exe", "Microsoft" }, { "csc2.exe", "Microsoft" }, @@ -132,19 +132,21 @@ private static IEnumerable AddDefaultResponse(string responseFile, IEnum { var ret = SuppressDefaultResponseFile(args) || !File.Exists(responseFile) ? args : - new[] { "@" + responseFile }.Concat(args); + new[] { $"@{responseFile}" }.Concat(args); // make sure to never treat warnings as errors in the extractor: // our version of Roslyn may report warnings that the actual build // doesn't - return ret.Concat(new[] { "/warnaserror-" }); + return ret.Concat(["/warnaserror-"]); } private static bool SuppressDefaultResponseFile(IEnumerable args) { - return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant())); + return args.Any(arg => noConfigFlags.Contains(arg.ToLowerInvariant())); } public IEnumerable ArgsWithResponse { get; } = Enumerable.Empty(); + + private static readonly string[] noConfigFlags = ["/noconfig", "-noconfig"]; } } diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Context.cs b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Context.cs index 57e9a5ca9f17..654ce0cc0f50 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Context.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Extractor/Context.cs @@ -68,7 +68,7 @@ internal void CacheLambdaParameterSymbol(IParameterSymbol param, SyntaxNode synt lambdaParameterCache[syntax] = param; } - private readonly Dictionary lambdaParameterCache = new Dictionary(); + private readonly Dictionary lambdaParameterCache = []; /// /// The current compilation unit. diff --git a/csharp/extractor/Semmle.Extraction.CSharp/Populators/DirectiveVisitor.cs b/csharp/extractor/Semmle.Extraction.CSharp/Populators/DirectiveVisitor.cs index b80d5175a8d1..f5f3c7d2acdf 100644 --- a/csharp/extractor/Semmle.Extraction.CSharp/Populators/DirectiveVisitor.cs +++ b/csharp/extractor/Semmle.Extraction.CSharp/Populators/DirectiveVisitor.cs @@ -8,7 +8,7 @@ namespace Semmle.Extraction.CSharp.Populators internal class DirectiveVisitor : CSharpSyntaxWalker { private readonly Context cx; - private readonly List branchesTaken = new(); + private readonly List branchesTaken = []; /// /// Gets a list of `#if`, `#elif`, and `#else` entities where the branch diff --git a/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs b/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs index 0f6683d32985..3c1b41f54bf1 100644 --- a/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs +++ b/csharp/extractor/Semmle.Extraction.Tests/DotNet.cs @@ -72,7 +72,7 @@ public void TestDotnetInfo() var dotnetCliInvoker = new DotNetCliInvokerStub(new List()); // Execute - var _ = MakeDotnet(dotnetCliInvoker); + _ = MakeDotnet(dotnetCliInvoker); // Verify var lastArgs = dotnetCliInvoker.GetLastArgs(); @@ -88,7 +88,7 @@ public void TestDotnetInfoFailure() // Execute try { - var _ = MakeDotnet(dotnetCliInvoker); + _ = MakeDotnet(dotnetCliInvoker); } // Verify diff --git a/csharp/extractor/Semmle.Extraction.Tests/Options.cs b/csharp/extractor/Semmle.Extraction.Tests/Options.cs index 8b18f8cb0415..1978732ee07b 100644 --- a/csharp/extractor/Semmle.Extraction.Tests/Options.cs +++ b/csharp/extractor/Semmle.Extraction.Tests/Options.cs @@ -168,7 +168,7 @@ public void ArchiveArguments() try { File.AppendAllText(file, "Test"); - sw.WriteContentFromArgumentFile(new string[] { "/noconfig", "@" + file }); + sw.WriteContentFromArgumentFile(new string[] { "/noconfig", $"@{file}" }); Assert.Equal("Test", Regex.Replace(sw.ToString(), @"\t|\n|\r", "")); } finally diff --git a/csharp/extractor/Semmle.Extraction/Context.cs b/csharp/extractor/Semmle.Extraction/Context.cs index ec1ba53d08fc..8b7b750768c4 100644 --- a/csharp/extractor/Semmle.Extraction/Context.cs +++ b/csharp/extractor/Semmle.Extraction/Context.cs @@ -37,7 +37,7 @@ public class Context // A recursion guard against writing to the trap file whilst writing an id to the trap file. private bool writingLabel = false; - private readonly Queue labelQueue = new(); + private readonly Queue labelQueue = []; protected void DefineLabel(IEntity entity) { diff --git a/csharp/extractor/Semmle.Extraction/EscapingTextWriter.cs b/csharp/extractor/Semmle.Extraction/EscapingTextWriter.cs index 6294ec3ffd31..2374b398843d 100644 --- a/csharp/extractor/Semmle.Extraction/EscapingTextWriter.cs +++ b/csharp/extractor/Semmle.Extraction/EscapingTextWriter.cs @@ -56,7 +56,7 @@ private void WriteEscaped(char c) default: wrapped.Write(c); break; - }; + } } public void WriteSubId(IEntity entity) diff --git a/csharp/extractor/Semmle.Extraction/Extractor/ExtractionContext.cs b/csharp/extractor/Semmle.Extraction/Extractor/ExtractionContext.cs index 539b339f85c3..26b30ad004b2 100644 --- a/csharp/extractor/Semmle.Extraction/Extractor/ExtractionContext.cs +++ b/csharp/extractor/Semmle.Extraction/Extractor/ExtractionContext.cs @@ -65,7 +65,7 @@ public void Message(Message msg) // Roslyn framework has no apparent mechanism to associate assemblies with their files. // So this lookup table needs to be populated. - private readonly Dictionary referenceFilenames = new Dictionary(); + private readonly Dictionary referenceFilenames = []; public void SetAssemblyFile(string assembly, string file) { diff --git a/csharp/extractor/Semmle.Extraction/Id.cs b/csharp/extractor/Semmle.Extraction/Id.cs index 3843bfb4531e..c66688f0760e 100644 --- a/csharp/extractor/Semmle.Extraction/Id.cs +++ b/csharp/extractor/Semmle.Extraction/Id.cs @@ -125,7 +125,7 @@ public override string ToString() if (!Valid) throw new InvalidOperationException("Attempt to use an invalid label"); - return "#" + Value; + return $"#{Value}"; } public static bool operator ==(Label l1, Label l2) => l1.Value == l2.Value; diff --git a/csharp/extractor/Semmle.Extraction/PathTransformer.cs b/csharp/extractor/Semmle.Extraction/PathTransformer.cs index 50cad1a51683..e67d60b11df4 100644 --- a/csharp/extractor/Semmle.Extraction/PathTransformer.cs +++ b/csharp/extractor/Semmle.Extraction/PathTransformer.cs @@ -92,7 +92,7 @@ public string DatabaseId { var ret = value; if (ret.Length >= 2 && ret[1] == ':' && Char.IsLower(ret[0])) - ret = Char.ToUpper(ret[0]) + "_" + ret.Substring(2); + ret = $"{char.ToUpper(ret[0])}_{ret[2..]}"; return ret.Replace('\\', '/').Replace(":", "_"); } } diff --git a/csharp/extractor/Semmle.Extraction/TrapWriter.cs b/csharp/extractor/Semmle.Extraction/TrapWriter.cs index 6baf55f7647a..0f5e0ab0ccdb 100644 --- a/csharp/extractor/Semmle.Extraction/TrapWriter.cs +++ b/csharp/extractor/Semmle.Extraction/TrapWriter.cs @@ -48,7 +48,7 @@ public TrapWriter(ILogger logger, PathTransformer.ITransformedPath outputfile, s writerLazy = new Lazy(() => { - var tempPath = trap ?? FileUtils.GetTemporaryWorkingDirectory(out var _); + var tempPath = trap ?? FileUtils.GetTemporaryWorkingDirectory(out _); do { @@ -139,7 +139,7 @@ private void Archive(Func getContent, PathTransformer.ITransformedPath t // - the same file was compiled multiple times, or // - the file doesn't exist (due to wrong #line directive or because it's an in-memory source generated AST). // In any case, this is not a fatal error. - logger.LogWarning("Problem archiving " + dest + ": " + ex); + logger.LogWarning($"Problem archiving {dest}: {ex}"); } } diff --git a/csharp/extractor/Semmle.Util/BuildScript.cs b/csharp/extractor/Semmle.Util/BuildScript.cs index 9092463afda9..9dd3ef9c8e9c 100644 --- a/csharp/extractor/Semmle.Util/BuildScript.cs +++ b/csharp/extractor/Semmle.Util/BuildScript.cs @@ -97,7 +97,7 @@ public BuildCommand(string exe, string? argumentsOpt, bool silent, string? worki this.environment = environment; } - public override string ToString() => arguments.Length > 0 ? exe + " " + arguments : exe; + public override string ToString() => arguments.Length > 0 ? $"{exe} {arguments}" : exe; public override int Run(IBuildActions actions, Action startCallback, Action exitCallBack) { diff --git a/csharp/extractor/Semmle.Util/CanonicalPathCache.cs b/csharp/extractor/Semmle.Util/CanonicalPathCache.cs index e7e4c07c36eb..a79854333ac7 100644 --- a/csharp/extractor/Semmle.Util/CanonicalPathCache.cs +++ b/csharp/extractor/Semmle.Util/CanonicalPathCache.cs @@ -107,7 +107,7 @@ public override string GetCanonicalPath(string path, IPathCache cache) var result = outPath.ToString(preamble, length - preamble); // Trim off leading \\?\ return result.StartsWith("UNC") - ? @"\" + result.Substring(3) + ? @$"\{result[3..]}" : result; } } diff --git a/csharp/extractor/Semmle.Util/EnvironmentVariables.cs b/csharp/extractor/Semmle.Util/EnvironmentVariables.cs index 076507d07e0a..1b0e40790ff1 100644 --- a/csharp/extractor/Semmle.Util/EnvironmentVariables.cs +++ b/csharp/extractor/Semmle.Util/EnvironmentVariables.cs @@ -45,7 +45,7 @@ public static bool GetBooleanOptOut(string name) public static bool GetBoolean(string name) { var env = Environment.GetEnvironmentVariable(name); - var _ = bool.TryParse(env, out var value); + _ = bool.TryParse(env, out var value); return value; } diff --git a/csharp/extractor/Semmle.Util/FileUtils.cs b/csharp/extractor/Semmle.Util/FileUtils.cs index 92087645fd1c..ff7eb8797315 100644 --- a/csharp/extractor/Semmle.Util/FileUtils.cs +++ b/csharp/extractor/Semmle.Util/FileUtils.cs @@ -120,7 +120,7 @@ public static string ConvertPathToSafeRelativePath(string path) path = path.TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); if (path.Length > 1 && path[1] == ':') - path = path[0] + "_" + path.Substring(2); + path = $"{path[0]}_{path[2..]}"; return path; } @@ -139,14 +139,14 @@ public static string NestPaths(ILogger logger, string? outerpath, string innerpa var directoryName = Path.GetDirectoryName(nested); if (directoryName is null) { - logger.LogWarning("Failed to get directory name from path '" + nested + "'."); + logger.LogWarning($"Failed to get directory name from path '{nested}'."); throw new InvalidOperationException(); } Directory.CreateDirectory(directoryName); } catch (PathTooLongException) { - logger.LogWarning("Failed to create parent directory of '" + nested + "': Path too long."); + logger.LogWarning($"Failed to create parent directory of '{nested}': Path too long."); throw; } return nested; diff --git a/csharp/extractor/Semmle.Util/Initializer.cs b/csharp/extractor/Semmle.Util/Initializer.cs index 179c7efbe12b..76d6b022de6b 100644 --- a/csharp/extractor/Semmle.Util/Initializer.cs +++ b/csharp/extractor/Semmle.Util/Initializer.cs @@ -22,7 +22,7 @@ public Initializer(Action action) public void Run() { - var _ = doInit.Value; + _ = doInit.Value; } } } diff --git a/csharp/extractor/Semmle.Util/LineCounter.cs b/csharp/extractor/Semmle.Util/LineCounter.cs index 0b1d8898e5eb..515ba75ee40a 100644 --- a/csharp/extractor/Semmle.Util/LineCounter.cs +++ b/csharp/extractor/Semmle.Util/LineCounter.cs @@ -44,7 +44,7 @@ public override int GetHashCode() public override string ToString() { - return "Total: " + Total + " Code: " + Code + " Comment: " + Comment; + return $"Total: {Total} Code: {Code} Comment: {Comment}"; } #endregion diff --git a/csharp/extractor/Semmle.Util/Logging/FileLogger.cs b/csharp/extractor/Semmle.Util/Logging/FileLogger.cs index 49632458a8ef..3b4ad31bd6d3 100644 --- a/csharp/extractor/Semmle.Util/Logging/FileLogger.cs +++ b/csharp/extractor/Semmle.Util/Logging/FileLogger.cs @@ -28,7 +28,7 @@ public FileLogger(Verbosity verbosity, string outputFile, bool logThreadId) } catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] { - Console.Error.WriteLine("CodeQL: Couldn't initialise C# extractor output: " + ex.Message + "\n" + ex.StackTrace); + Console.Error.WriteLine($"CodeQL: Couldn't initialise C# extractor output: {ex.Message}\n{ex.StackTrace}"); Console.Error.Flush(); throw; } @@ -41,7 +41,7 @@ public void Dispose() private static string GetSeverityPrefix(Severity s) { - return "[" + s.ToString().ToUpper() + "] "; + return $"[{s.ToString().ToUpper()}] "; } public void Log(Severity s, string text, int? threadId = null) diff --git a/csharp/extractor/Semmle.Util/Logging/PidStreamWriter.cs b/csharp/extractor/Semmle.Util/Logging/PidStreamWriter.cs index 26b0944a429b..7d9599298d65 100644 --- a/csharp/extractor/Semmle.Util/Logging/PidStreamWriter.cs +++ b/csharp/extractor/Semmle.Util/Logging/PidStreamWriter.cs @@ -18,7 +18,7 @@ public sealed class PidStreamWriter : StreamWriter /// The stream to write to. public PidStreamWriter(Stream stream) : base(stream) { } - private readonly string prefix = "[" + Process.GetCurrentProcess().Id + "] "; + private readonly string prefix = $"[{System.Environment.ProcessId}] "; public override void WriteLine(string? value) { diff --git a/csharp/extractor/Semmle.Util/MemoizedFunc.cs b/csharp/extractor/Semmle.Util/MemoizedFunc.cs index f2018df8bb71..d1a0edd3a436 100644 --- a/csharp/extractor/Semmle.Util/MemoizedFunc.cs +++ b/csharp/extractor/Semmle.Util/MemoizedFunc.cs @@ -7,7 +7,7 @@ namespace Semmle.Util; public class MemoizedFunc where T1 : notnull { private readonly Func f; - private readonly Dictionary cache = new(); + private readonly Dictionary cache = []; public MemoizedFunc(Func f) { @@ -28,7 +28,7 @@ public T2 Invoke(T1 s) public class ConcurrentMemoizedFunc where T1 : notnull { private readonly Func f; - private readonly ConcurrentDictionary cache = new(); + private readonly ConcurrentDictionary cache = []; public ConcurrentMemoizedFunc(Func f) {