Skip to content

Commit 199a968

Browse files
committed
C#: Fix quality issues
1 parent 1cf5e89 commit 199a968

Some content is hidden

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

47 files changed

+79
-85
lines changed

csharp/autobuilder/Semmle.Autobuild.CSharp/CSharpDiagnosticClassifier.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ public override void Fire(DiagnosticClassifier classifier, Match match)
9999
{
100100
if (!match.Groups.TryGetValue("projectFile", out var projectFile))
101101
throw new ArgumentException("Expected regular expression match to contain projectFile");
102-
if (!match.Groups.TryGetValue("location", out var location))
102+
if (!match.Groups.TryGetValue("location", out _))
103103
throw new ArgumentException("Expected regular expression match to contain location");
104104

105105
var result = classifier.Results.OfType<Result>().FirstOrDefault();

csharp/autobuilder/Semmle.Autobuild.CSharp/DotNetRule.cs

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
11
using System;
22
using System.Collections.Generic;
3-
using System.IO;
43
using System.Linq;
54
using Semmle.Util;
6-
using Semmle.Util.Logging;
75
using Semmle.Autobuild.Shared;
86
using Semmle.Extraction.CSharp.DependencyFetching;
97

@@ -15,14 +13,14 @@ namespace Semmle.Autobuild.CSharp
1513
/// </summary>
1614
internal class DotNetRule : IBuildRule<CSharpAutobuildOptions>
1715
{
18-
public readonly List<IProjectOrSolution> FailedProjectsOrSolutions = new();
16+
public List<IProjectOrSolution> FailedProjectsOrSolutions { get; } = [];
1917

2018
/// <summary>
2119
/// A list of projects which are incompatible with DotNet.
2220
/// </summary>
2321
public IEnumerable<Project<CSharpAutobuildOptions>> NotDotNetProjects { get; private set; }
2422

25-
public DotNetRule() => NotDotNetProjects = new List<Project<CSharpAutobuildOptions>>();
23+
public DotNetRule() => NotDotNetProjects = [];
2624

2725
public BuildScript Analyse(IAutobuilder<CSharpAutobuildOptions> builder, bool auto)
2826
{

csharp/autobuilder/Semmle.Autobuild.Shared/BuildTools.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public VcVarsBatFile(string path, int version)
1818
Path = path;
1919
ToolsVersion = version;
2020
}
21-
};
21+
}
2222

2323
/// <summary>
2424
/// Collection of available Visual Studio build tools.

csharp/autobuilder/Semmle.Autobuild.Shared/DiagnosticClassifier.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ public virtual void Fire(DiagnosticClassifier classifier, Match match) { }
6060
public class DiagnosticClassifier
6161
{
6262
private readonly List<DiagnosticRule> rules;
63-
public readonly List<IDiagnosticsResult> Results;
63+
public List<IDiagnosticsResult> Results { get; }
6464

6565
public DiagnosticClassifier()
6666
{

csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public class MsBuildRule : IBuildRule<AutobuildOptionsShared>
3232
/// <summary>
3333
/// A list of solutions or projects which failed to build.
3434
/// </summary>
35-
public readonly List<IProjectOrSolution> FailedProjectsOrSolutions = new();
35+
public List<IProjectOrSolution> FailedProjectsOrSolutions { get; } = [];
3636

3737
public BuildScript Analyse(IAutobuilder<AutobuildOptionsShared> builder, bool auto)
3838
{
@@ -60,7 +60,7 @@ public BuildScript Analyse(IAutobuilder<AutobuildOptionsShared> builder, bool au
6060
// Use `nuget.exe` from source code repo, if present, otherwise first attempt with global
6161
// `nuget` command, and if that fails, attempt to download `nuget.exe` from nuget.org
6262
var nuget = builder.GetFilename("nuget.exe").Select(t => t.Item1).FirstOrDefault() ?? "nuget";
63-
var nugetDownloadPath = builder.Actions.PathCombine(FileUtils.GetTemporaryWorkingDirectory(builder.Actions.GetEnvironmentVariable, builder.Options.Language.UpperCaseName, out var _), ".nuget", "nuget.exe");
63+
var nugetDownloadPath = builder.Actions.PathCombine(FileUtils.GetTemporaryWorkingDirectory(builder.Actions.GetEnvironmentVariable, builder.Options.Language.UpperCaseName, out _), ".nuget", "nuget.exe");
6464
var nugetDownloaded = false;
6565

6666
var ret = BuildScript.Success;
@@ -126,7 +126,7 @@ BuildScript GetNugetRestoreScript() =>
126126
var platform = projectOrSolution is ISolution s1 ? s1.DefaultPlatformName : null;
127127
var configuration = projectOrSolution is ISolution s2 ? s2.DefaultConfigurationName : null;
128128

129-
command.Argument("/t:" + target);
129+
command.Argument($"/t:{target}");
130130
if (platform is not null)
131131
command.Argument($"/p:Platform=\"{platform}\"");
132132
if (configuration is not null)

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyCache.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -133,12 +133,12 @@ public AssemblyInfo GetAssemblyInfo(string filepath)
133133

134134
private readonly List<string> dllsToIndex = new List<string>();
135135

136-
private readonly Dictionary<string, AssemblyInfo> assemblyInfoByFileName = new Dictionary<string, AssemblyInfo>();
136+
private readonly Dictionary<string, AssemblyInfo> assemblyInfoByFileName = [];
137137

138138
// Map from assembly id (in various formats) to the full info.
139-
private readonly Dictionary<string, AssemblyInfo> assemblyInfoById = new Dictionary<string, AssemblyInfo>();
139+
private readonly Dictionary<string, AssemblyInfo> assemblyInfoById = [];
140140

141-
private readonly HashSet<string> failedAssemblyInfoIds = new HashSet<string>();
141+
private readonly HashSet<string> failedAssemblyInfoIds = [];
142142

143143
private readonly ILogger logger;
144144
}

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyInfo.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ private AssemblyInfo(string id, string filename)
9494
{
9595
var sections = id.Split(new string[] { ", " }, StringSplitOptions.None);
9696

97-
Name = sections.First();
97+
Name = sections[0];
9898

9999
foreach (var section in sections.Skip(1))
100100
{

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/AssemblyLookupLocation.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ public List<string> GetDlls(ILogger logger)
8080
}
8181
else
8282
{
83-
logger.LogDebug("AssemblyLookupLocation: Path not found: " + path);
83+
logger.LogDebug($"AssemblyLookupLocation: Path not found: {path}");
8484
}
8585
return dllsToIndex;
8686
}

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/Assets.cs

-2
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,6 @@ private void AddPackageDependencies(JObject json, string jsonPath)
120120
info.Compile
121121
.ForEach(r => Dependencies.Add(name, r.Key));
122122
});
123-
124-
return;
125123
}
126124

127125
/// <summary>

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyContainer.cs

+3-5
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ internal class DependencyContainer
1212
/// <summary>
1313
/// Paths to dependencies required for compilation.
1414
/// </summary>
15-
public HashSet<string> Paths { get; } = new();
15+
public HashSet<string> Paths { get; } = [];
1616

1717
/// <summary>
1818
/// Packages that are used as a part of the required dependencies.
1919
/// </summary>
20-
public HashSet<string> Packages { get; } = new();
20+
public HashSet<string> Packages { get; } = [];
2121

2222
/// <summary>
2323
/// 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)
3333
}
3434

3535
private static string GetPackageName(string package) =>
36-
package
37-
.Split(Path.DirectorySeparatorChar)
38-
.First();
36+
package.Split(Path.DirectorySeparatorChar)[0];
3937

4038
/// <summary>
4139
/// Add a dependency inside a package.

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DependencyManager.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ private void AddNetFrameworkDlls(ISet<AssemblyLookupLocation> dllLocations, ISet
310310

311311
if (runtimeLocation is null)
312312
{
313-
runtimeLocation ??= Runtime.ExecutingRuntime;
313+
runtimeLocation = Runtime.ExecutingRuntime;
314314
dllLocations.Add(new AssemblyLookupLocation(runtimeLocation, name => !name.StartsWith("Semmle.")));
315315
}
316316
else

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNet.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,7 @@ BuildScript GetInstall(string pwsh) =>
230230
Argument("-ExecutionPolicy").
231231
Argument("unrestricted").
232232
Argument("-Command").
233-
Argument("\"" + psCommand + "\"").
233+
Argument($"\"{psCommand}\"").
234234
Script;
235235

236236
return GetInstall("pwsh") | GetInstall("powershell");

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/DotNetCliInvoker.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -58,13 +58,13 @@ private bool RunCommandAux(string args, string? workingDirectory, out IList<stri
5858
return true;
5959
}
6060

61-
public bool RunCommand(string args, bool silent) =>
61+
public bool RunCommand(string args, bool silent = true) =>
6262
RunCommandAux(args, null, out _, silent);
6363

64-
public bool RunCommand(string args, out IList<string> output, bool silent) =>
64+
public bool RunCommand(string args, out IList<string> output, bool silent = true) =>
6565
RunCommandAux(args, null, out output, silent);
6666

67-
public bool RunCommand(string args, string? workingDirectory, out IList<string> output, bool silent) =>
67+
public bool RunCommand(string args, string? workingDirectory, out IList<string> output, bool silent = true) =>
6868
RunCommandAux(args, workingDirectory, out output, silent);
6969
}
7070
}

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/EnvironmentVariableNames.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
namespace Semmle.Extraction.CSharp.DependencyFetching
22
{
3-
internal class EnvironmentVariableNames
3+
internal static class EnvironmentVariableNames
44
{
55
/// <summary>
66
/// Controls whether to generate source files from resources (`.resx`).

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetExeWrapper.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public NugetExeWrapper(FileProvider fileProvider, TemporaryDirectory packageDire
5151
{
5252
if (File.Exists(nugetConfigPath))
5353
{
54-
var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out var _);
54+
var tempFolderPath = FileUtils.GetTemporaryWorkingDirectory(out _);
5555

5656
do
5757
{
@@ -188,7 +188,7 @@ private bool TryRestoreNugetPackage(string packagesConfig)
188188
var threadId = Environment.CurrentManagedThreadId;
189189
void onOut(string s) => logger.LogDebug(s, threadId);
190190
void onError(string s) => logger.LogError(s, threadId);
191-
var exitCode = pi.ReadOutput(out var _, onOut, onError);
191+
var exitCode = pi.ReadOutput(out _, onOut, onError);
192192
if (exitCode != 0)
193193
{
194194
logger.LogError($"Command {pi.FileName} {pi.Arguments} failed with exit code {exitCode}");
@@ -264,7 +264,7 @@ private void RunMonoNugetCommand(string command, out IList<string> stdout)
264264
private void AddDefaultPackageSource(string nugetConfig)
265265
{
266266
logger.LogInfo("Adding default package source...");
267-
RunMonoNugetCommand($"sources add -Name DefaultNugetOrg -Source {NugetPackageRestorer.PublicNugetOrgFeed} -ConfigFile \"{nugetConfig}\"", out var _);
267+
RunMonoNugetCommand($"sources add -Name DefaultNugetOrg -Source {NugetPackageRestorer.PublicNugetOrgFeed} -ConfigFile \"{nugetConfig}\"", out _);
268268
}
269269

270270
public void Dispose()

csharp/extractor/Semmle.Extraction.CSharp.DependencyFetching/NugetPackageRestorer.cs

+5-7
Original file line numberDiff line numberDiff line change
@@ -538,7 +538,7 @@ private void TryChangePackageVersion(DirectoryInfo tempDir, string newVersion)
538538
TryChangeProjectFile(tempDir, PackageReferenceVersion(), $"Version=\"{newVersion}\"", "package reference version");
539539
}
540540

541-
private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, string replacement, string patternName)
541+
private void TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, string replacement, string patternName)
542542
{
543543
try
544544
{
@@ -548,7 +548,7 @@ private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, strin
548548
if (csprojs.Length != 1)
549549
{
550550
logger.LogError($"Could not find the .csproj file in {projectDir.FullName}, count = {csprojs.Length}");
551-
return false;
551+
return;
552552
}
553553

554554
var csproj = csprojs[0];
@@ -557,18 +557,16 @@ private bool TryChangeProjectFile(DirectoryInfo projectDir, Regex pattern, strin
557557
if (matches.Count == 0)
558558
{
559559
logger.LogError($"Could not find the {patternName} in {csproj.FullName}");
560-
return false;
560+
return;
561561
}
562562

563563
content = pattern.Replace(content, replacement, 1);
564564
File.WriteAllText(csproj.FullName, content);
565-
return true;
566565
}
567566
catch (Exception exc)
568567
{
569568
logger.LogError($"Failed to change the {patternName} in {projectDir.FullName}: {exc}");
570569
}
571-
return false;
572570
}
573571

574572
private static async Task ExecuteGetRequest(string address, HttpClient httpClient, CancellationToken cancellationToken)
@@ -644,7 +642,7 @@ private bool CheckFeeds(out HashSet<string> explicitFeeds)
644642
(explicitFeeds, var allFeeds) = GetAllFeeds();
645643

646644
var excludedFeeds = EnvironmentVariables.GetURLs(EnvironmentVariableNames.ExcludedNugetFeedsFromResponsivenessCheck)
647-
.ToHashSet() ?? [];
645+
.ToHashSet();
648646

649647
if (excludedFeeds.Count > 0)
650648
{
@@ -779,7 +777,7 @@ private static string ComputeTempDirectoryPath(string srcDir, string subfolderNa
779777
foreach (var b in sha.Take(8))
780778
sb.AppendFormat("{0:x2}", b);
781779

782-
return Path.Combine(FileUtils.GetTemporaryWorkingDirectory(out var _), sb.ToString(), subfolderName);
780+
return Path.Combine(FileUtils.GetTemporaryWorkingDirectory(out _), sb.ToString(), subfolderName);
783781
}
784782
}
785783
}

csharp/extractor/Semmle.Extraction.CSharp.StubGenerator/StubVisitor.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -201,12 +201,12 @@ private void StubTypedConstant(TypedConstant c)
201201
}
202202
}
203203

204-
private static readonly HashSet<string> attributeAllowList = new() {
204+
private static readonly HashSet<string> attributeAllowList = [
205205
"System.FlagsAttribute",
206206
"System.AttributeUsageAttribute",
207207
"System.Runtime.CompilerServices.InterpolatedStringHandlerAttribute",
208208
"System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute",
209-
};
209+
];
210210

211211
private void StubAttribute(AttributeData a, string prefix, bool addNewLine)
212212
{
@@ -298,7 +298,7 @@ private static bool IsUnsafe(ITypeSymbol symbol) =>
298298
(symbol is INamedTypeSymbol named && named.TypeArguments.Any(IsUnsafe)) ||
299299
(symbol is IArrayTypeSymbol at && IsUnsafe(at.ElementType));
300300

301-
private static readonly HashSet<string> keywords = new() {
301+
private static readonly HashSet<string> keywords = [
302302
"abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked",
303303
"class", "const", "continue", "decimal", "default", "delegate", "do", "double", "else",
304304
"enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach",
@@ -308,10 +308,10 @@ private static bool IsUnsafe(ITypeSymbol symbol) =>
308308
"stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try",
309309
"typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void",
310310
"volatile", "while"
311-
};
311+
];
312312

313313
private static string EscapeIdentifier(string identifier) =>
314-
keywords.Contains(identifier) ? "@" + identifier : identifier;
314+
keywords.Contains(identifier) ? $"@{identifier}" : identifier;
315315

316316
private static bool TryGetConstantValue(IFieldSymbol symbol, out string value)
317317
{

csharp/extractor/Semmle.Extraction.CSharp.Util/SymbolExtensions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,8 @@ static bool TryGetOperatorSymbolFromName(string methodName, out string operatorN
110110
var match = CheckedRegex().Match(methodName);
111111
if (match.Success)
112112
{
113-
TryGetOperatorSymbolFromName("op_" + match.Groups[1], out var uncheckedName);
114-
operatorName = "checked " + uncheckedName;
113+
TryGetOperatorSymbolFromName($"op_{match.Groups[1]}", out var uncheckedName);
114+
operatorName = $"checked {uncheckedName}";
115115
break;
116116
}
117117
operatorName = methodName;

csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentBinding.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ public enum CommentBinding
99
Best, // The most likely element associated with a comment
1010
Before, // The element before the comment
1111
After // The element after the comment
12-
};
12+
}
1313
}

csharp/extractor/Semmle.Extraction.CSharp/Comments/CommentLineType.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ public enum CommentLineType
99
XmlDoc, // Comment starting /// ...
1010
Multiline, // Comment starting /* ..., even if the comment only spans one line.
1111
MultilineContinuation // The second and subsequent lines of comment in a multiline comment.
12-
};
12+
}
1313
}

csharp/extractor/Semmle.Extraction.CSharp/Entities/Assembly.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ private Assembly(Context cx, Microsoft.CodeAnalysis.Location? init)
2424
{
2525
assembly = init!.MetadataModule!.ContainingAssembly;
2626
var identity = assembly.Identity;
27-
var idString = identity.Name + " " + identity.Version;
27+
var idString = $"{identity.Name} {identity.Version}";
2828
assemblyPath = cx.ExtractionContext.GetAssemblyFile(idString);
2929
}
3030
}

csharp/extractor/Semmle.Extraction.CSharp/Entities/Compilations/Compilation.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace Semmle.Extraction.CSharp.Entities
99
{
1010
internal class Compilation : CachedEntity<object>
1111
{
12-
internal readonly ConcurrentDictionary<string, int> messageCounts = new();
12+
internal readonly ConcurrentDictionary<string, int> messageCounts = [];
1313

1414
private readonly string cwd;
1515
private readonly string[] args;

csharp/extractor/Semmle.Extraction.CSharp/Entities/ExpressionNodeInfo.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ private bool TryGetStringValueFromUtf8Literal(out string? value)
193193

194194
public bool IsBoolLiteral()
195195
{
196-
return TryGetBoolValueFromLiteral(out var _);
196+
return TryGetBoolValueFromLiteral(out _);
197197
}
198198
}
199199
}

csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Assignment.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ private static ExprKind GetAssignmentOperation(Context cx, AssignmentExpressionS
7676
case SyntaxKind.QuestionQuestionEqualsToken:
7777
return ExprKind.ASSIGN_COALESCE;
7878
default:
79-
cx.ModelError(syntax, "Unrecognised assignment type " + GetKind(cx, syntax));
79+
cx.ModelError(syntax, $"Unrecognised assignment type {GetKind(cx, syntax)}");
8080
return ExprKind.UNKNOWN;
8181
}
8282
}
@@ -152,7 +152,7 @@ private ExprKind? OperatorKind
152152
case ExprKind.ASSIGN_COALESCE:
153153
return ExprKind.NULL_COALESCING;
154154
default:
155-
Context.ModelError(Syntax, "Couldn't unfold assignment of type " + kind);
155+
Context.ModelError(Syntax, $"Couldn't unfold assignment of type {kind}");
156156
return ExprKind.UNKNOWN;
157157
}
158158
}

csharp/extractor/Semmle.Extraction.CSharp/Entities/Expressions/Patterns/PropertyPattern.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ private record AccessStep(string Identifier, Microsoft.CodeAnalysis.Location Loc
2525

2626
private class AccessStepPack
2727
{
28-
public readonly List<AccessStep> Prefix = new();
28+
public List<AccessStep> Prefix { get; } = [];
2929
public AccessStep Last { get; private set; }
3030

3131
public AccessStepPack Add(string identifier, Microsoft.CodeAnalysis.Location location)

0 commit comments

Comments
 (0)