C#: Fix quality issues

This commit is contained in:
Tamas Vajk
2024-06-28 11:09:40 +02:00
parent 1cf5e89b96
commit 199a9688af
47 changed files with 79 additions and 85 deletions

View File

@@ -99,7 +99,7 @@ namespace Semmle.Autobuild.CSharp
{
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<Result>().FirstOrDefault();

View File

@@ -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
/// </summary>
internal class DotNetRule : IBuildRule<CSharpAutobuildOptions>
{
public readonly List<IProjectOrSolution> FailedProjectsOrSolutions = new();
public List<IProjectOrSolution> FailedProjectsOrSolutions { get; } = [];
/// <summary>
/// A list of projects which are incompatible with DotNet.
/// </summary>
public IEnumerable<Project<CSharpAutobuildOptions>> NotDotNetProjects { get; private set; }
public DotNetRule() => NotDotNetProjects = new List<Project<CSharpAutobuildOptions>>();
public DotNetRule() => NotDotNetProjects = [];
public BuildScript Analyse(IAutobuilder<CSharpAutobuildOptions> builder, bool auto)
{

View File

@@ -18,7 +18,7 @@ namespace Semmle.Autobuild.Shared
Path = path;
ToolsVersion = version;
}
};
}
/// <summary>
/// Collection of available Visual Studio build tools.

View File

@@ -60,7 +60,7 @@ namespace Semmle.Autobuild.Shared
public class DiagnosticClassifier
{
private readonly List<DiagnosticRule> rules;
public readonly List<IDiagnosticsResult> Results;
public List<IDiagnosticsResult> Results { get; }
public DiagnosticClassifier()
{

View File

@@ -32,7 +32,7 @@ namespace Semmle.Autobuild.Shared
/// <summary>
/// A list of solutions or projects which failed to build.
/// </summary>
public readonly List<IProjectOrSolution> FailedProjectsOrSolutions = new();
public List<IProjectOrSolution> FailedProjectsOrSolutions { get; } = [];
public BuildScript Analyse(IAutobuilder<AutobuildOptionsShared> builder, bool auto)
{
@@ -60,7 +60,7 @@ namespace Semmle.Autobuild.Shared
// 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 @@ namespace Semmle.Autobuild.Shared
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)

View File

@@ -133,12 +133,12 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
private readonly List<string> dllsToIndex = new List<string>();
private readonly Dictionary<string, AssemblyInfo> assemblyInfoByFileName = new Dictionary<string, AssemblyInfo>();
private readonly Dictionary<string, AssemblyInfo> assemblyInfoByFileName = [];
// Map from assembly id (in various formats) to the full info.
private readonly Dictionary<string, AssemblyInfo> assemblyInfoById = new Dictionary<string, AssemblyInfo>();
private readonly Dictionary<string, AssemblyInfo> assemblyInfoById = [];
private readonly HashSet<string> failedAssemblyInfoIds = new HashSet<string>();
private readonly HashSet<string> failedAssemblyInfoIds = [];
private readonly ILogger logger;
}

View File

@@ -94,7 +94,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
{
var sections = id.Split(new string[] { ", " }, StringSplitOptions.None);
Name = sections.First();
Name = sections[0];
foreach (var section in sections.Skip(1))
{

View File

@@ -80,7 +80,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
}
else
{
logger.LogDebug("AssemblyLookupLocation: Path not found: " + path);
logger.LogDebug($"AssemblyLookupLocation: Path not found: {path}");
}
return dllsToIndex;
}

View File

@@ -120,8 +120,6 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
info.Compile
.ForEach(r => Dependencies.Add(name, r.Key));
});
return;
}
/// <summary>

View File

@@ -12,12 +12,12 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
/// <summary>
/// Paths to dependencies required for compilation.
/// </summary>
public HashSet<string> Paths { get; } = new();
public HashSet<string> Paths { get; } = [];
/// <summary>
/// Packages that are used as a part of the required dependencies.
/// </summary>
public HashSet<string> Packages { get; } = new();
public HashSet<string> Packages { get; } = [];
/// <summary>
/// If the path specifically adds a .dll we use that, otherwise we as a fallback
@@ -33,9 +33,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
}
private static string GetPackageName(string package) =>
package
.Split(Path.DirectorySeparatorChar)
.First();
package.Split(Path.DirectorySeparatorChar)[0];
/// <summary>
/// Add a dependency inside a package.

View File

@@ -310,7 +310,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
if (runtimeLocation is null)
{
runtimeLocation ??= Runtime.ExecutingRuntime;
runtimeLocation = Runtime.ExecutingRuntime;
dllLocations.Add(new AssemblyLookupLocation(runtimeLocation, name => !name.StartsWith("Semmle.")));
}
else

View File

@@ -230,7 +230,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
Argument("-ExecutionPolicy").
Argument("unrestricted").
Argument("-Command").
Argument("\"" + psCommand + "\"").
Argument($"\"{psCommand}\"").
Script;
return GetInstall("pwsh") | GetInstall("powershell");

View File

@@ -58,13 +58,13 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
return true;
}
public bool RunCommand(string args, bool silent) =>
public bool RunCommand(string args, bool silent = true) =>
RunCommandAux(args, null, out _, silent);
public bool RunCommand(string args, out IList<string> output, bool silent) =>
public bool RunCommand(string args, out IList<string> output, bool silent = true) =>
RunCommandAux(args, null, out output, silent);
public bool RunCommand(string args, string? workingDirectory, out IList<string> output, bool silent) =>
public bool RunCommand(string args, string? workingDirectory, out IList<string> output, bool silent = true) =>
RunCommandAux(args, workingDirectory, out output, silent);
}
}

View File

@@ -1,6 +1,6 @@
namespace Semmle.Extraction.CSharp.DependencyFetching
{
internal class EnvironmentVariableNames
internal static class EnvironmentVariableNames
{
/// <summary>
/// Controls whether to generate source files from resources (`.resx`).

View File

@@ -51,7 +51,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
{
if (File.Exists(nugetConfigPath))
{
var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out var _);
var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out _);
do
{
@@ -188,7 +188,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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()

View File

@@ -538,7 +538,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
(explicitFeeds, var allFeeds) = GetAllFeeds();
var excludedFeeds = EnvironmentVariables.GetURLs(EnvironmentVariableNames.ExcludedNugetFeedsFromResponsivenessCheck)
.ToHashSet() ?? [];
.ToHashSet();
if (excludedFeeds.Count > 0)
{
@@ -779,7 +777,7 @@ namespace Semmle.Extraction.CSharp.DependencyFetching
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);
}
}
}

View File

@@ -201,12 +201,12 @@ internal sealed class StubVisitor : SymbolVisitor
}
}
private static readonly HashSet<string> attributeAllowList = new() {
private static readonly HashSet<string> 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 @@ internal sealed class StubVisitor : SymbolVisitor
(symbol is INamedTypeSymbol named && named.TypeArguments.Any(IsUnsafe)) ||
(symbol is IArrayTypeSymbol at && IsUnsafe(at.ElementType));
private static readonly HashSet<string> keywords = new() {
private static readonly HashSet<string> 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 @@ internal sealed class StubVisitor : SymbolVisitor
"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)
{

View File

@@ -110,8 +110,8 @@ namespace Semmle.Extraction.CSharp.Util
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;

View File

@@ -9,5 +9,5 @@ namespace Semmle.Extraction.CSharp
Best, // The most likely element associated with a comment
Before, // The element before the comment
After // The element after the comment
};
}
}

View File

@@ -9,5 +9,5 @@ namespace Semmle.Extraction.CSharp
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.
};
}
}

View File

@@ -24,7 +24,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
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);
}
}

View File

@@ -9,7 +9,7 @@ namespace Semmle.Extraction.CSharp.Entities
{
internal class Compilation : CachedEntity<object>
{
internal readonly ConcurrentDictionary<string, int> messageCounts = new();
internal readonly ConcurrentDictionary<string, int> messageCounts = [];
private readonly string cwd;
private readonly string[] args;

View File

@@ -193,7 +193,7 @@ namespace Semmle.Extraction.CSharp.Entities
public bool IsBoolLiteral()
{
return TryGetBoolValueFromLiteral(out var _);
return TryGetBoolValueFromLiteral(out _);
}
}
}

View File

@@ -76,7 +76,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
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 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
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;
}
}

View File

@@ -25,7 +25,7 @@ namespace Semmle.Extraction.CSharp.Entities.Expressions
private class AccessStepPack
{
public readonly List<AccessStep> Prefix = new();
public List<AccessStep> Prefix { get; } = [];
public AccessStep Last { get; private set; }
public AccessStepPack Add(string identifier, Microsoft.CodeAnalysis.Location location)

View File

@@ -99,7 +99,7 @@ namespace Semmle.Extraction.CSharp.Entities
// 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;
}
}

View File

@@ -106,7 +106,7 @@ namespace Semmle.Extraction.CSharp
{
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 @@ namespace Semmle.Extraction.CSharp
/// </summary>
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()}");
}

View File

@@ -34,7 +34,7 @@ namespace Semmle.Extraction.CSharp
private set;
}
private static readonly Dictionary<string, string> knownCompilerNames = new Dictionary<string, string>
private static readonly Dictionary<string, string> knownCompilerNames = new()
{
{ "csc.exe", "Microsoft" },
{ "csc2.exe", "Microsoft" },
@@ -132,19 +132,21 @@ namespace Semmle.Extraction.CSharp
{
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<string> args)
{
return args.Any(arg => new[] { "/noconfig", "-noconfig" }.Contains(arg.ToLowerInvariant()));
return args.Any(arg => noConfigFlags.Contains(arg.ToLowerInvariant()));
}
public IEnumerable<string> ArgsWithResponse { get; } = Enumerable.Empty<string>();
private static readonly string[] noConfigFlags = ["/noconfig", "-noconfig"];
}
}

View File

@@ -68,7 +68,7 @@ namespace Semmle.Extraction.CSharp
lambdaParameterCache[syntax] = param;
}
private readonly Dictionary<SyntaxNode, IParameterSymbol> lambdaParameterCache = new Dictionary<SyntaxNode, IParameterSymbol>();
private readonly Dictionary<SyntaxNode, IParameterSymbol> lambdaParameterCache = [];
/// <summary>
/// The current compilation unit.

View File

@@ -8,7 +8,7 @@ namespace Semmle.Extraction.CSharp.Populators
internal class DirectiveVisitor : CSharpSyntaxWalker
{
private readonly Context cx;
private readonly List<IEntity> branchesTaken = new();
private readonly List<IEntity> branchesTaken = [];
/// <summary>
/// Gets a list of `#if`, `#elif`, and `#else` entities where the branch

View File

@@ -72,7 +72,7 @@ namespace Semmle.Extraction.Tests
var dotnetCliInvoker = new DotNetCliInvokerStub(new List<string>());
// Execute
var _ = MakeDotnet(dotnetCliInvoker);
_ = MakeDotnet(dotnetCliInvoker);
// Verify
var lastArgs = dotnetCliInvoker.GetLastArgs();
@@ -88,7 +88,7 @@ namespace Semmle.Extraction.Tests
// Execute
try
{
var _ = MakeDotnet(dotnetCliInvoker);
_ = MakeDotnet(dotnetCliInvoker);
}
// Verify

View File

@@ -168,7 +168,7 @@ namespace Semmle.Extraction.Tests
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

View File

@@ -37,7 +37,7 @@ namespace Semmle.Extraction
// A recursion guard against writing to the trap file whilst writing an id to the trap file.
private bool writingLabel = false;
private readonly Queue<IEntity> labelQueue = new();
private readonly Queue<IEntity> labelQueue = [];
protected void DefineLabel(IEntity entity)
{

View File

@@ -56,7 +56,7 @@ namespace Semmle.Extraction
default:
wrapped.Write(c);
break;
};
}
}
public void WriteSubId(IEntity entity)

View File

@@ -65,7 +65,7 @@ namespace Semmle.Extraction
// Roslyn framework has no apparent mechanism to associate assemblies with their files.
// So this lookup table needs to be populated.
private readonly Dictionary<string, string> referenceFilenames = new Dictionary<string, string>();
private readonly Dictionary<string, string> referenceFilenames = [];
public void SetAssemblyFile(string assembly, string file)
{

View File

@@ -125,7 +125,7 @@ namespace Semmle.Extraction
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;

View File

@@ -92,7 +92,7 @@ namespace Semmle.Extraction
{
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(":", "_");
}
}

View File

@@ -48,7 +48,7 @@ namespace Semmle.Extraction
writerLazy = new Lazy<StreamWriter>(() =>
{
var tempPath = trap ?? FileUtils.GetTemporaryWorkingDirectory(out var _);
var tempPath = trap ?? FileUtils.GetTemporaryWorkingDirectory(out _);
do
{
@@ -139,7 +139,7 @@ namespace Semmle.Extraction
// - 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}");
}
}

View File

@@ -97,7 +97,7 @@ namespace Semmle.Util
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<string, bool> startCallback, Action<int, string, bool> exitCallBack)
{

View File

@@ -107,7 +107,7 @@ namespace Semmle.Util
var result = outPath.ToString(preamble, length - preamble); // Trim off leading \\?\
return result.StartsWith("UNC")
? @"\" + result.Substring(3)
? @$"\{result[3..]}"
: result;
}
}

View File

@@ -45,7 +45,7 @@ namespace Semmle.Util
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;
}

View File

@@ -120,7 +120,7 @@ namespace Semmle.Util
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 @@ namespace Semmle.Util
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;

View File

@@ -22,7 +22,7 @@ namespace Semmle.Util
public void Run()
{
var _ = doInit.Value;
_ = doInit.Value;
}
}
}

View File

@@ -44,7 +44,7 @@ namespace Semmle.Util
public override string ToString()
{
return "Total: " + Total + " Code: " + Code + " Comment: " + Comment;
return $"Total: {Total} Code: {Code} Comment: {Comment}";
}
#endregion

View File

@@ -28,7 +28,7 @@ namespace Semmle.Util.Logging
}
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 @@ namespace Semmle.Util.Logging
private static string GetSeverityPrefix(Severity s)
{
return "[" + s.ToString().ToUpper() + "] ";
return $"[{s.ToString().ToUpper()}] ";
}
public void Log(Severity s, string text, int? threadId = null)

View File

@@ -18,7 +18,7 @@ namespace Semmle.Util.Logging
/// <param name="stream">The stream to write to.</param>
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)
{

View File

@@ -7,7 +7,7 @@ namespace Semmle.Util;
public class MemoizedFunc<T1, T2> where T1 : notnull
{
private readonly Func<T1, T2> f;
private readonly Dictionary<T1, T2> cache = new();
private readonly Dictionary<T1, T2> cache = [];
public MemoizedFunc(Func<T1, T2> f)
{
@@ -28,7 +28,7 @@ public class MemoizedFunc<T1, T2> where T1 : notnull
public class ConcurrentMemoizedFunc<T1, T2> where T1 : notnull
{
private readonly Func<T1, T2> f;
private readonly ConcurrentDictionary<T1, T2> cache = new();
private readonly ConcurrentDictionary<T1, T2> cache = [];
public ConcurrentMemoizedFunc(Func<T1, T2> f)
{