Skip to content

Commit

Permalink
C#: Fix quality issues
Browse files Browse the repository at this point in the history
  • Loading branch information
tamasvajk committed Jun 28, 2024
1 parent 4db586f commit 42db708
Show file tree
Hide file tree
Showing 32 changed files with 50 additions and 58 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<Result>().FirstOrDefault();
Expand Down
6 changes: 2 additions & 4 deletions csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -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)
{
Expand Down
2 changes: 1 addition & 1 deletion csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public VcVarsBatFile(string path, int version)
Path = path;
ToolsVersion = version;
}
};
}

/// <summary>
/// Collection of available Visual Studio build tools.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public virtual void Fire(DiagnosticClassifier classifier, Match match) { }
public class DiagnosticClassifier
{
private readonly List<DiagnosticRule> rules;
public readonly List<IDiagnosticsResult> Results;
public List<IDiagnosticsResult> Results { get; }

public DiagnosticClassifier()
{
Expand Down
4 changes: 2 additions & 2 deletions csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class MsBuildRule : IBuildRule<AutobuildOptionsShared>
/// <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)
{
Expand Down Expand Up @@ -60,7 +60,7 @@ public BuildScript Analyse(IAutobuilder<AutobuildOptionsShared> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ public AssemblyInfo GetAssemblyInfo(string filepath)

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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,6 @@ private void AddPackageDependencies(JObject json, string jsonPath)
info.Compile
.ForEach(r => Dependencies.Add(name, r.Key));
});

return;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ internal class DependencyContainer
/// <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
Expand All @@ -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];

/// <summary>
/// Add a dependency inside a package.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ private void AddNetFrameworkDlls(ISet<AssemblyLookupLocation> dllLocations, ISet

if (runtimeLocation is null)
{
runtimeLocation ??= Runtime.ExecutingRuntime;
runtimeLocation = Runtime.ExecutingRuntime;
dllLocations.Add(new AssemblyLookupLocation(runtimeLocation, name => !name.StartsWith("Semmle.")));
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,13 @@ private bool RunCommandAux(string args, string? workingDirectory, out IList<stri
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);
}
}
Original file line number Diff line number Diff line change
@@ -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`).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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}");
Expand Down Expand Up @@ -264,7 +264,7 @@ private void RunMonoNugetCommand(string command, out IList<string> 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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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];
Expand All @@ -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)
Expand Down Expand Up @@ -644,7 +642,7 @@ private bool CheckFeeds(out HashSet<string> explicitFeeds)
(explicitFeeds, var allFeeds) = GetAllFeeds();

var excludedFeeds = EnvironmentVariables.GetURLs(EnvironmentVariableNames.ExcludedNugetFeedsFromResponsivenessCheck)
.ToHashSet() ?? [];
.ToHashSet();

if (excludedFeeds.Count > 0)
{
Expand Down Expand Up @@ -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);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,12 @@ private void StubTypedConstant(TypedConstant c)
}
}

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)
{
Expand Down Expand Up @@ -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<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",
Expand All @@ -308,7 +308,7 @@ 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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.
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ private bool TryGetStringValueFromUtf8Literal(out string? value)

public bool IsBoolLiteral()
{
return TryGetBoolValueFromLiteral(out var _);
return TryGetBoolValueFromLiteral(out _);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ private record AccessStep(string Identifier, Microsoft.CodeAnalysis.Location Loc

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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ public virtual void Dispose()
/// </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()}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public string? SkipReason
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" },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ internal void CacheLambdaParameterSymbol(IParameterSymbol param, SyntaxNode synt
lambdaParameterCache[syntax] = param;
}

private readonly Dictionary<SyntaxNode, IParameterSymbol> lambdaParameterCache = new Dictionary<SyntaxNode, IParameterSymbol>();
private readonly Dictionary<SyntaxNode, IParameterSymbol> lambdaParameterCache = [];

/// <summary>
/// The current compilation unit.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions csharp/extractor/Semmle.Extraction.Tests/DotNet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void TestDotnetInfo()
var dotnetCliInvoker = new DotNetCliInvokerStub(new List<string>());

// Execute
var _ = MakeDotnet(dotnetCliInvoker);
_ = MakeDotnet(dotnetCliInvoker);

// Verify
var lastArgs = dotnetCliInvoker.GetLastArgs();
Expand All @@ -88,7 +88,7 @@ public void TestDotnetInfoFailure()
// Execute
try
{
var _ = MakeDotnet(dotnetCliInvoker);
_ = MakeDotnet(dotnetCliInvoker);
}

// Verify
Expand Down
2 changes: 1 addition & 1 deletion csharp/extractor/Semmle.Extraction/Context.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<IEntity> labelQueue = new();
private readonly Queue<IEntity> labelQueue = [];

protected void DefineLabel(IEntity entity)
{
Expand Down
2 changes: 1 addition & 1 deletion csharp/extractor/Semmle.Extraction/EscapingTextWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private void WriteEscaped(char c)
default:
wrapped.Write(c);
break;
};
}
}

public void WriteSubId(IEntity entity)
Expand Down
Loading

0 comments on commit 42db708

Please sign in to comment.