From 6b7c17966de495f6a8d29ce553a01aabc7f24d41 Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Fri, 1 Sep 2023 16:16:59 +0200 Subject: [PATCH 1/7] Enabled nullability for BenchmarkDotNet.Diagnostics.dotTrace.csproj --- .../BenchmarkDotNet.Diagnostics.dotTrace.csproj | 1 + .../DotTraceDiagnoser.cs | 6 +++--- .../DotTraceDiagnoserAttribute.cs | 2 +- .../DotTraceToolBase.cs | 14 +++++++------- .../ExternalDotTraceTool.cs | 6 +++--- .../InProcessDotTraceTool.cs | 2 +- .../Progress.cs | 2 +- 7 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/BenchmarkDotNet.Diagnostics.dotTrace.csproj b/src/BenchmarkDotNet.Diagnostics.dotTrace/BenchmarkDotNet.Diagnostics.dotTrace.csproj index e4037e5bcf..e7852f1575 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/BenchmarkDotNet.Diagnostics.dotTrace.csproj +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/BenchmarkDotNet.Diagnostics.dotTrace.csproj @@ -6,6 +6,7 @@ BenchmarkDotNet.Diagnostics.dotTrace BenchmarkDotNet.Diagnostics.dotTrace BenchmarkDotNet.Diagnostics.dotTrace + enable diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoser.cs index a53c305938..1b3186124b 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoser.cs @@ -19,10 +19,10 @@ namespace BenchmarkDotNet.Diagnostics.dotTrace { public class DotTraceDiagnoser : IProfiler { - private readonly Uri nugetUrl; - private readonly string toolsDownloadFolder; + private readonly Uri? nugetUrl; + private readonly string? toolsDownloadFolder; - public DotTraceDiagnoser(Uri nugetUrl = null, string toolsDownloadFolder = null) + public DotTraceDiagnoser(Uri? nugetUrl = null, string? toolsDownloadFolder = null) { this.nugetUrl = nugetUrl; this.toolsDownloadFolder = toolsDownloadFolder; diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoserAttribute.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoserAttribute.cs index de803e6443..19e88a6de1 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoserAttribute.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceDiagnoserAttribute.cs @@ -13,7 +13,7 @@ public DotTraceDiagnoserAttribute() Config = ManualConfig.CreateEmpty().AddDiagnoser(new DotTraceDiagnoser()); } - public DotTraceDiagnoserAttribute(Uri nugetUrl = null, string toolsDownloadFolder = null) + public DotTraceDiagnoserAttribute(Uri? nugetUrl = null, string? toolsDownloadFolder = null) { Config = ManualConfig.CreateEmpty().AddDiagnoser(new DotTraceDiagnoser(nugetUrl, toolsDownloadFolder)); } diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceToolBase.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceToolBase.cs index c41ffc53e5..f2f07625fa 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceToolBase.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/DotTraceToolBase.cs @@ -11,11 +11,11 @@ namespace BenchmarkDotNet.Diagnostics.dotTrace internal abstract class DotTraceToolBase { private readonly ILogger logger; - private readonly Uri nugetUrl; + private readonly Uri? nugetUrl; private readonly NuGetApi nugetApi; - private readonly string downloadTo; + private readonly string? downloadTo; - protected DotTraceToolBase(ILogger logger, Uri nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string downloadTo = null) + protected DotTraceToolBase(ILogger logger, Uri? nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string? downloadTo = null) { this.logger = logger; this.nugetUrl = nugetUrl; @@ -48,9 +48,9 @@ public void Init(DiagnoserActionParameters parameters) public string Start(DiagnoserActionParameters parameters) { string snapshotFile = ArtifactFileNameHelper.GetFilePath(parameters, "snapshots", DateTime.Now, "dtp", ".0000".Length); - string snapshotDirectory = Path.GetDirectoryName(snapshotFile); + string? snapshotDirectory = Path.GetDirectoryName(snapshotFile); logger.WriteLineInfo($"Target snapshot file: {snapshotFile}"); - if (!Directory.Exists(snapshotDirectory)) + if (!Directory.Exists(snapshotDirectory) && snapshotDirectory != null) { try { @@ -126,7 +126,7 @@ protected string GetRunnerPath() if (consoleRunnerPackageField == null) throw new InvalidOperationException("Field 'ConsoleRunnerPackage' not found."); - object consoleRunnerPackage = consoleRunnerPackageField.GetValue(null); + object? consoleRunnerPackage = consoleRunnerPackageField.GetValue(null); if (consoleRunnerPackage == null) throw new InvalidOperationException("Unable to get value of 'ConsoleRunnerPackage'."); @@ -135,7 +135,7 @@ protected string GetRunnerPath() if (getRunnerPathMethod == null) throw new InvalidOperationException("Method 'GetRunnerPath' not found."); - string runnerPath = getRunnerPathMethod.Invoke(consoleRunnerPackage, null) as string; + string? runnerPath = getRunnerPathMethod.Invoke(consoleRunnerPackage, null) as string; if (runnerPath == null) throw new InvalidOperationException("Unable to invoke 'GetRunnerPath'."); diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/ExternalDotTraceTool.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/ExternalDotTraceTool.cs index 9c5161b309..dfc9903b82 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/ExternalDotTraceTool.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/ExternalDotTraceTool.cs @@ -12,7 +12,7 @@ internal class ExternalDotTraceTool : DotTraceToolBase { private static readonly TimeSpan AttachTimeout = TimeSpan.FromMinutes(5); - public ExternalDotTraceTool(ILogger logger, Uri nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string downloadTo = null) : + public ExternalDotTraceTool(ILogger logger, Uri? nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string? downloadTo = null) : base(logger, nugetUrl, nugetApi, downloadTo) { } protected override bool AttachOnly => true; @@ -44,7 +44,7 @@ protected override void Attach(DiagnoserActionParameters parameters, string snap { process.OutputDataReceived += (_, args) => { - string content = args.Data; + string? content = args.Data; if (content != null) { logger.WriteLineInfo("[dotTrace] " + content); @@ -54,7 +54,7 @@ protected override void Attach(DiagnoserActionParameters parameters, string snap }; process.ErrorDataReceived += (_, args) => { - string content = args.Data; + string? content = args.Data; if (content != null) logger.WriteLineError("[dotTrace] " + args.Data); }; diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/InProcessDotTraceTool.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/InProcessDotTraceTool.cs index a124e3e495..a02c9c1995 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/InProcessDotTraceTool.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/InProcessDotTraceTool.cs @@ -7,7 +7,7 @@ namespace BenchmarkDotNet.Diagnostics.dotTrace { internal class InProcessDotTraceTool : DotTraceToolBase { - public InProcessDotTraceTool(ILogger logger, Uri nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string downloadTo = null) : + public InProcessDotTraceTool(ILogger logger, Uri? nugetUrl = null, NuGetApi nugetApi = NuGetApi.V3, string? downloadTo = null) : base(logger, nugetUrl, nugetApi, downloadTo) { } protected override bool AttachOnly => false; diff --git a/src/BenchmarkDotNet.Diagnostics.dotTrace/Progress.cs b/src/BenchmarkDotNet.Diagnostics.dotTrace/Progress.cs index 1d8249f31e..c353939f1f 100644 --- a/src/BenchmarkDotNet.Diagnostics.dotTrace/Progress.cs +++ b/src/BenchmarkDotNet.Diagnostics.dotTrace/Progress.cs @@ -18,7 +18,7 @@ public Progress(ILogger logger, string title) } private int lastProgress; - private Stopwatch stopwatch; + private Stopwatch? stopwatch; public void Report(double value) { From 749918914f30c442a05c20966d26dd067608fcd3 Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Sun, 3 Sep 2023 12:35:20 +0200 Subject: [PATCH 2/7] Fixed nullability warnings in methods signatures --- .../BenchmarkDotNet.Samples/IntroOrderManual.cs | 4 ++-- .../Configs/InliningDiagnoserAttribute.cs | 2 +- .../EtwDiagnoser.cs | 2 +- .../EtwProfilerConfig.cs | 4 ++-- .../InliningDiagnoser.cs | 2 +- src/BenchmarkDotNet/Code/EnumParam.cs | 2 +- src/BenchmarkDotNet/Columns/StatisticColumn.cs | 2 +- .../ConsoleArguments/ConfigParser.cs | 2 +- .../Diagnosers/EventPipeProfiler.cs | 2 +- .../Disassemblers/DisassemblyDiagnoserConfig.cs | 4 ++-- .../Environments/Runtimes/ClrRuntime.cs | 2 +- .../Environments/Runtimes/WasmRuntime.cs | 2 +- .../Exporters/Csv/CsvMeasurementsExporter.cs | 2 +- src/BenchmarkDotNet/Helpers/ProcessHelper.cs | 4 ++-- src/BenchmarkDotNet/Jobs/JobExtensions.cs | 2 +- src/BenchmarkDotNet/Jobs/NugetReference.cs | 2 +- .../Loggers/AsyncProcessOutputReader.cs | 2 +- src/BenchmarkDotNet/Loggers/ConsoleLogger.cs | 2 +- src/BenchmarkDotNet/Order/DefaultOrderer.cs | 4 ++-- src/BenchmarkDotNet/Order/IOrderer.cs | 4 ++-- src/BenchmarkDotNet/Reports/Summary.cs | 2 +- src/BenchmarkDotNet/Reports/SummaryTable.cs | 2 +- src/BenchmarkDotNet/Running/Descriptor.cs | 14 +++++++------- .../Toolchains/CoreRun/CoreRunPublisher.cs | 2 +- .../Toolchains/CoreRun/CoreRunToolchain.cs | 2 +- .../Toolchains/CsProj/CsProjClassicNetToolchain.cs | 4 ++-- .../Toolchains/DotNetCli/DotNetCliBuilder.cs | 2 +- .../Toolchains/DotNetCli/DotNetCliCommand.cs | 6 +++--- .../DotNetCli/DotNetCliCommandExecutor.cs | 2 +- .../Toolchains/DotNetCli/DotNetCliPublisher.cs | 2 +- .../Toolchains/DotNetCli/MsBuildErrorMapper.cs | 2 +- .../Toolchains/DotNetCli/NetCoreAppSettings.cs | 12 ++++++------ .../Toolchains/Parameters/ExecuteParameters.cs | 2 +- .../Toolchains/Results/GenerateResult.cs | 2 +- .../Toolchains/ToolchainExtensions.cs | 2 +- src/BenchmarkDotNet/Validators/ValidationError.cs | 2 +- .../BenchmarkTestExecutor.cs | 6 +++--- .../ExporterIOTests.cs | 2 +- .../RunnableStructCaseBenchmark.tt | 2 +- .../InProcessTest.cs | 2 +- .../Engine/EngineWarmupStageTests.cs | 2 +- .../Reports/FakeMetricDescriptor.cs | 2 +- tests/BenchmarkDotNet.Tests/TypeFilterTests.cs | 2 +- 43 files changed, 65 insertions(+), 65 deletions(-) diff --git a/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs b/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs index 625e78a816..a624edd205 100644 --- a/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs +++ b/samples/BenchmarkDotNet.Samples/IntroOrderManual.cs @@ -22,7 +22,7 @@ private class Config : ManualConfig private class FastestToSlowestOrderer : IOrderer { public IEnumerable GetExecutionOrder(ImmutableArray benchmarksCase, - IEnumerable order = null) => + IEnumerable? order = null) => from benchmark in benchmarksCase orderby benchmark.Parameters["X"] descending, benchmark.Descriptor.WorkloadMethodDisplayInfo @@ -39,7 +39,7 @@ public string GetLogicalGroupKey(ImmutableArray allBenchmarksCase benchmarkCase.Job.DisplayInfo + "_" + benchmarkCase.Parameters.DisplayInfo; public IEnumerable> GetLogicalGroupOrder(IEnumerable> logicalGroups, - IEnumerable order = null) => + IEnumerable? order = null) => logicalGroups.OrderBy(it => it.Key); public bool SeparateLogicalGroups => true; diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Configs/InliningDiagnoserAttribute.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Configs/InliningDiagnoserAttribute.cs index 0a3f4e0dc5..c9878ed6fc 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Configs/InliningDiagnoserAttribute.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Configs/InliningDiagnoserAttribute.cs @@ -13,7 +13,7 @@ public InliningDiagnoserAttribute(bool logFailuresOnly = true, bool filterByName Config = ManualConfig.CreateEmpty().AddDiagnoser(new InliningDiagnoser(logFailuresOnly, filterByNamespace)); } - public InliningDiagnoserAttribute(bool logFailuresOnly = true, string[] allowedNamespaces = null) + public InliningDiagnoserAttribute(bool logFailuresOnly = true, string[]? allowedNamespaces = null) { Config = ManualConfig.CreateEmpty().AddDiagnoser(new InliningDiagnoser(logFailuresOnly, allowedNamespaces)); } diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs index c52006d7c6..80423d72cf 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/EtwDiagnoser.cs @@ -97,7 +97,7 @@ private void Clear() private void OnProcessExit(object sender, EventArgs e) => Session?.Dispose(); - private static string GetSessionName(string prefix, BenchmarkCase benchmarkCase, ParameterInstances parameters = null) + private static string GetSessionName(string prefix, BenchmarkCase benchmarkCase, ParameterInstances? parameters = null) { if (parameters != null && parameters.Items.Count > 0) return $"{prefix}-{benchmarkCase.FolderInfo}-{parameters.FolderInfo}"; diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfilerConfig.cs b/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfilerConfig.cs index 967dcc2d03..7846edd1dd 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfilerConfig.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/EtwProfilerConfig.cs @@ -41,8 +41,8 @@ public EtwProfilerConfig( float cpuSampleIntervalInMilliseconds = 1.0f, KernelTraceEventParser.Keywords kernelKeywords = KernelTraceEventParser.Keywords.ImageLoad | KernelTraceEventParser.Keywords.Profile, KernelTraceEventParser.Keywords kernelStackKeywords = KernelTraceEventParser.Keywords.Profile, - IReadOnlyDictionary> intervalSelectors = null, - IReadOnlyCollection<(Guid providerGuid, TraceEventLevel providerLevel, ulong keywords, TraceEventProviderOptions options)> providers = null, + IReadOnlyDictionary>? intervalSelectors = null, + IReadOnlyCollection<(Guid providerGuid, TraceEventLevel providerLevel, ulong keywords, TraceEventProviderOptions options)>? providers = null, bool createHeapSession = false) { CreateHeapSession = createHeapSession; diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs index 4c09957eef..bb9fd42ce7 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs @@ -35,7 +35,7 @@ public InliningDiagnoser(bool logFailuresOnly = true, bool filterByNamespace = t /// /// only the methods that failed to get inlined. True by default. /// list of namespaces from which inlining message should be print. - public InliningDiagnoser(bool logFailuresOnly = true, string[] allowedNamespaces = null) + public InliningDiagnoser(bool logFailuresOnly = true, string[]? allowedNamespaces = null) { this.logFailuresOnly = logFailuresOnly; this.allowedNamespaces = allowedNamespaces; diff --git a/src/BenchmarkDotNet/Code/EnumParam.cs b/src/BenchmarkDotNet/Code/EnumParam.cs index 9d0ac58950..5c0ecf6afd 100644 --- a/src/BenchmarkDotNet/Code/EnumParam.cs +++ b/src/BenchmarkDotNet/Code/EnumParam.cs @@ -24,7 +24,7 @@ private EnumParam(object value, Type type) public string ToSourceCode() => $"({type.GetCorrectCSharpTypeName()})({ToInvariantCultureString()})"; - internal static IParam FromObject(object value, Type type = null) + internal static IParam FromObject(object value, Type? type = null) { type = type ?? value.GetType(); if (!type.IsEnum) diff --git a/src/BenchmarkDotNet/Columns/StatisticColumn.cs b/src/BenchmarkDotNet/Columns/StatisticColumn.cs index 31e72f2446..f0b9655acc 100644 --- a/src/BenchmarkDotNet/Columns/StatisticColumn.cs +++ b/src/BenchmarkDotNet/Columns/StatisticColumn.cs @@ -107,7 +107,7 @@ private enum Priority private readonly IStatisticColumn parentColumn; private StatisticColumn(string columnName, string legend, Func calc, Priority priority, UnitType type = UnitType.Time, - IStatisticColumn parentColumn = null) + IStatisticColumn? parentColumn = null) { this.calc = calc; this.priority = priority; diff --git a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs index 76500bed44..108c55b1ce 100644 --- a/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs +++ b/src/BenchmarkDotNet/ConsoleArguments/ConfigParser.cs @@ -72,7 +72,7 @@ public static class ConfigParser { "fullxml", new[] { XmlExporter.Full } } }; - public static (bool isSuccess, IConfig config, CommandLineOptions options) Parse(string[] args, ILogger logger, IConfig globalConfig = null) + public static (bool isSuccess, IConfig config, CommandLineOptions options) Parse(string[] args, ILogger logger, IConfig? globalConfig = null) { (bool isSuccess, IConfig config, CommandLineOptions options) result = default; diff --git a/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs b/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs index 211d4a06e2..c1c76e8c9e 100644 --- a/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs +++ b/src/BenchmarkDotNet/Diagnosers/EventPipeProfiler.cs @@ -40,7 +40,7 @@ public EventPipeProfiler() :this(profile: EventPipeProfile.CpuSampling, performE /// A named pre-defined set of provider configurations that allows common tracing scenarios to be specified succinctly. /// A list of EventPipe providers to be enabled. /// if set to true, benchmarks will be executed one more time with the profiler attached. If set to false, there will be no extra run but the results will contain overhead. True by default. - public EventPipeProfiler(EventPipeProfile profile = EventPipeProfile.CpuSampling, IReadOnlyCollection providers = null, bool performExtraBenchmarksRun = true) + public EventPipeProfiler(EventPipeProfile profile = EventPipeProfile.CpuSampling, IReadOnlyCollection? providers = null, bool performExtraBenchmarksRun = true) { this.performExtraBenchmarksRun = performExtraBenchmarksRun; eventPipeProviders = MapToProviders(profile, providers); diff --git a/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoserConfig.cs b/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoserConfig.cs index 7c917c80b0..feff76ef99 100644 --- a/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoserConfig.cs +++ b/src/BenchmarkDotNet/Disassemblers/DisassemblyDiagnoserConfig.cs @@ -22,8 +22,8 @@ public class DisassemblyDiagnoserConfig public DisassemblyDiagnoserConfig( int maxDepth = 1, DisassemblySyntax syntax = DisassemblySyntax.Masm, - string[] filters = null, - FormatterOptions formatterOptions = null, + string[]? filters = null, + FormatterOptions? formatterOptions = null, bool printSource = false, bool printInstructionAddresses = false, bool exportGithubMarkdown = true, diff --git a/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs index 35460ce853..be5a84cce2 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/ClrRuntime.cs @@ -17,7 +17,7 @@ public class ClrRuntime : Runtime, IEquatable public string Version { get; } - private ClrRuntime(RuntimeMoniker runtimeMoniker, string msBuildMoniker, string displayName, string version = null) + private ClrRuntime(RuntimeMoniker runtimeMoniker, string msBuildMoniker, string displayName, string? version = null) : base(runtimeMoniker, msBuildMoniker, displayName) { Version = version; diff --git a/src/BenchmarkDotNet/Environments/Runtimes/WasmRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/WasmRuntime.cs index bb6c122700..3fcc07f26a 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/WasmRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/WasmRuntime.cs @@ -28,7 +28,7 @@ public class WasmRuntime : Runtime, IEquatable /// Specifies whether AOT or Interpreter (default) project should be generated. /// Specifies a wasm data directory surfaced as $(WasmDataDir) for the project /// Runtime moniker - public WasmRuntime(string msBuildMoniker = "net5.0", string displayName = "Wasm", string javaScriptEngine = "v8", string javaScriptEngineArguments = "--expose_wasm", bool aot = false, string wasmDataDir = null, RuntimeMoniker moniker = RuntimeMoniker.Wasm) : base(moniker, msBuildMoniker, displayName) + public WasmRuntime(string msBuildMoniker = "net5.0", string displayName = "Wasm", string javaScriptEngine = "v8", string javaScriptEngineArguments = "--expose_wasm", bool aot = false, string? wasmDataDir = null, RuntimeMoniker moniker = RuntimeMoniker.Wasm) : base(moniker, msBuildMoniker, displayName) { if (!string.IsNullOrEmpty(javaScriptEngine) && javaScriptEngine != "v8" && !File.Exists(javaScriptEngine)) throw new FileNotFoundException($"Provided {nameof(javaScriptEngine)} file: \"{javaScriptEngine}\" doest NOT exist"); diff --git a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs index 74f6130f1c..0d07c9058c 100644 --- a/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs +++ b/src/BenchmarkDotNet/Exporters/Csv/CsvMeasurementsExporter.cs @@ -20,7 +20,7 @@ public class CsvMeasurementsExporter : ExporterBase private static readonly Lazy Columns = new Lazy(BuildColumns); private readonly CsvSeparator separator; - public CsvMeasurementsExporter(CsvSeparator separator, SummaryStyle style = null) + public CsvMeasurementsExporter(CsvSeparator separator, SummaryStyle? style = null) { this.separator = separator; Style = style ?? SummaryStyle.Default; diff --git a/src/BenchmarkDotNet/Helpers/ProcessHelper.cs b/src/BenchmarkDotNet/Helpers/ProcessHelper.cs index 114ae287fb..1b75c6392f 100644 --- a/src/BenchmarkDotNet/Helpers/ProcessHelper.cs +++ b/src/BenchmarkDotNet/Helpers/ProcessHelper.cs @@ -12,7 +12,7 @@ internal static class ProcessHelper /// Run external process and return the console output. /// In the case of any exception, null will be returned. /// - internal static string? RunAndReadOutput(string fileName, string arguments = "", ILogger logger = null) + internal static string? RunAndReadOutput(string fileName, string arguments = "", ILogger? logger = null) { var processStartInfo = new ProcessStartInfo { @@ -42,7 +42,7 @@ internal static class ProcessHelper } internal static (int exitCode, ImmutableArray output) RunAndReadOutputLineByLine(string fileName, string arguments = "", string workingDirectory = "", - Dictionary environmentVariables = null, bool includeErrors = false, ILogger logger = null) + Dictionary? environmentVariables = null, bool includeErrors = false, ILogger? logger = null) { var processStartInfo = new ProcessStartInfo { diff --git a/src/BenchmarkDotNet/Jobs/JobExtensions.cs b/src/BenchmarkDotNet/Jobs/JobExtensions.cs index 8cbf7445d7..2a236dc44f 100644 --- a/src/BenchmarkDotNet/Jobs/JobExtensions.cs +++ b/src/BenchmarkDotNet/Jobs/JobExtensions.cs @@ -339,7 +339,7 @@ public static Job WithEnvironmentVariable(this Job job, string key, string value /// (optional)Indicate the URI of the NuGet package source to use during the restore operation. /// (optional)Allows prerelease packages to be installed. /// - public static Job WithNuGet(this Job job, string packageName, string packageVersion = null, Uri source = null, bool prerelease = false) => + public static Job WithNuGet(this Job job, string packageName, string? packageVersion = null, Uri? source = null, bool prerelease = false) => job.WithCore(j => j.Infrastructure.NuGetReferences = new NuGetReferenceList(j.Infrastructure.NuGetReferences ?? Array.Empty()) { diff --git a/src/BenchmarkDotNet/Jobs/NugetReference.cs b/src/BenchmarkDotNet/Jobs/NugetReference.cs index 3e5819c4ae..0db3a028de 100644 --- a/src/BenchmarkDotNet/Jobs/NugetReference.cs +++ b/src/BenchmarkDotNet/Jobs/NugetReference.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Jobs { public class NuGetReference : IEquatable { - public NuGetReference(string packageName, string packageVersion, Uri source = null, bool prerelease = false) + public NuGetReference(string packageName, string packageVersion, Uri? source = null, bool prerelease = false) { if (string.IsNullOrWhiteSpace(packageName)) throw new ArgumentException("message", nameof(packageName)); diff --git a/src/BenchmarkDotNet/Loggers/AsyncProcessOutputReader.cs b/src/BenchmarkDotNet/Loggers/AsyncProcessOutputReader.cs index a503da8e76..d4a059153d 100644 --- a/src/BenchmarkDotNet/Loggers/AsyncProcessOutputReader.cs +++ b/src/BenchmarkDotNet/Loggers/AsyncProcessOutputReader.cs @@ -19,7 +19,7 @@ internal class AsyncProcessOutputReader : IDisposable private long status; - internal AsyncProcessOutputReader(Process process, bool logOutput = false, ILogger logger = null, bool readStandardError = true) + internal AsyncProcessOutputReader(Process process, bool logOutput = false, ILogger? logger = null, bool readStandardError = true) { if (!process.StartInfo.RedirectStandardOutput) throw new NotSupportedException("set RedirectStandardOutput to true first"); diff --git a/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs b/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs index a54bf88edc..a1c7795d53 100644 --- a/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs +++ b/src/BenchmarkDotNet/Loggers/ConsoleLogger.cs @@ -21,7 +21,7 @@ private static readonly bool ConsoleSupportsColors private readonly Dictionary colorScheme; [PublicAPI] - public ConsoleLogger(bool unicodeSupport = false, Dictionary colorScheme = null) + public ConsoleLogger(bool unicodeSupport = false, Dictionary? colorScheme = null) { this.unicodeSupport = unicodeSupport; this.colorScheme = colorScheme ?? CreateColorfulScheme(); diff --git a/src/BenchmarkDotNet/Order/DefaultOrderer.cs b/src/BenchmarkDotNet/Order/DefaultOrderer.cs index 0bca3cf3ec..656de7ce98 100644 --- a/src/BenchmarkDotNet/Order/DefaultOrderer.cs +++ b/src/BenchmarkDotNet/Order/DefaultOrderer.cs @@ -37,7 +37,7 @@ public DefaultOrderer( [PublicAPI] public virtual IEnumerable GetExecutionOrder( ImmutableArray benchmarkCases, - IEnumerable order = null) + IEnumerable? order = null) { var benchmarkComparer = new BenchmarkComparer(categoryComparer, paramsComparer, jobComparer, targetComparer, order); var list = benchmarkCases.ToList(); @@ -137,7 +137,7 @@ public string GetLogicalGroupKey(ImmutableArray allBenchmarksCase public virtual IEnumerable> GetLogicalGroupOrder( IEnumerable> logicalGroups, - IEnumerable order = null) + IEnumerable? order = null) { var benchmarkComparer = new BenchmarkComparer(categoryComparer, paramsComparer, jobComparer, targetComparer, order); var logicalGroupComparer = new LogicalGroupComparer(benchmarkComparer); diff --git a/src/BenchmarkDotNet/Order/IOrderer.cs b/src/BenchmarkDotNet/Order/IOrderer.cs index dece54e519..bfc6ba5433 100644 --- a/src/BenchmarkDotNet/Order/IOrderer.cs +++ b/src/BenchmarkDotNet/Order/IOrderer.cs @@ -11,7 +11,7 @@ namespace BenchmarkDotNet.Order public interface IOrderer { [PublicAPI] - IEnumerable GetExecutionOrder(ImmutableArray benchmarksCase, IEnumerable order = null); + IEnumerable GetExecutionOrder(ImmutableArray benchmarksCase, IEnumerable? order = null); [PublicAPI] IEnumerable GetSummaryOrder(ImmutableArray benchmarksCases, Summary summary); @@ -24,7 +24,7 @@ public interface IOrderer [PublicAPI] IEnumerable> GetLogicalGroupOrder(IEnumerable> logicalGroups, - IEnumerable order = null); + IEnumerable? order = null); [PublicAPI] bool SeparateLogicalGroups { get; } diff --git a/src/BenchmarkDotNet/Reports/Summary.cs b/src/BenchmarkDotNet/Reports/Summary.cs index 7a9382f62d..680ded2d5b 100644 --- a/src/BenchmarkDotNet/Reports/Summary.cs +++ b/src/BenchmarkDotNet/Reports/Summary.cs @@ -48,7 +48,7 @@ public Summary( CultureInfo cultureInfo, ImmutableArray validationErrors, ImmutableArray columnHidingRules, - SummaryStyle summaryStyle = null) + SummaryStyle? summaryStyle = null) { Title = title; ResultsDirectoryPath = resultsDirectoryPath; diff --git a/src/BenchmarkDotNet/Reports/SummaryTable.cs b/src/BenchmarkDotNet/Reports/SummaryTable.cs index 9ab5e983fd..64aae074ec 100644 --- a/src/BenchmarkDotNet/Reports/SummaryTable.cs +++ b/src/BenchmarkDotNet/Reports/SummaryTable.cs @@ -24,7 +24,7 @@ public class SummaryTable public SummaryStyle EffectiveSummaryStyle { get; } public bool SeparateLogicalGroups { get; } - internal SummaryTable(Summary summary, SummaryStyle style = null) + internal SummaryTable(Summary summary, SummaryStyle? style = null) { Summary = summary; diff --git a/src/BenchmarkDotNet/Running/Descriptor.cs b/src/BenchmarkDotNet/Running/Descriptor.cs index 2e747bb1cd..a38b1a13d9 100644 --- a/src/BenchmarkDotNet/Running/Descriptor.cs +++ b/src/BenchmarkDotNet/Running/Descriptor.cs @@ -31,14 +31,14 @@ public class Descriptor : IEquatable public Descriptor( Type type, MethodInfo workloadMethod, - MethodInfo globalSetupMethod = null, - MethodInfo globalCleanupMethod = null, - MethodInfo iterationSetupMethod = null, - MethodInfo iterationCleanupMethod = null, - string description = null, - string additionalLogic = null, + MethodInfo? globalSetupMethod = null, + MethodInfo? globalCleanupMethod = null, + MethodInfo? iterationSetupMethod = null, + MethodInfo? iterationCleanupMethod = null, + string? description = null, + string? additionalLogic = null, bool baseline = false, - string[] categories = null, + string[]? categories = null, int operationsPerInvoke = 1, int methodIndex = 0) { diff --git a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs index b9605867fe..c77b56b039 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunPublisher.cs @@ -11,7 +11,7 @@ namespace BenchmarkDotNet.Toolchains.CoreRun { public class CoreRunPublisher : IBuilder { - public CoreRunPublisher(FileInfo coreRun, FileInfo customDotNetCliPath = null) + public CoreRunPublisher(FileInfo coreRun, FileInfo? customDotNetCliPath = null) { CoreRun = coreRun; DotNetCliPublisher = new DotNetCliPublisher(customDotNetCliPath?.FullName); diff --git a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs index 03d677a5aa..7eca3f97f0 100644 --- a/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/CoreRun/CoreRunToolchain.cs @@ -21,7 +21,7 @@ public class CoreRunToolchain : IToolchain /// the directory to restore packages to public CoreRunToolchain(FileInfo coreRun, bool createCopy = true, string targetFrameworkMoniker = "netcoreapp2.1", - FileInfo customDotNetCliPath = null, DirectoryInfo restorePath = null, + FileInfo? customDotNetCliPath = null, DirectoryInfo? restorePath = null, string displayName = "CoreRun") { if (coreRun == null) throw new ArgumentNullException(nameof(coreRun)); diff --git a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjClassicNetToolchain.cs b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjClassicNetToolchain.cs index 4e1fe4a641..e3c3f85125 100644 --- a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjClassicNetToolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjClassicNetToolchain.cs @@ -25,7 +25,7 @@ public class CsProjClassicNetToolchain : Toolchain internal string CustomDotNetCliPath { get; } - private CsProjClassicNetToolchain(string targetFrameworkMoniker, string name, string packagesPath = null, string customDotNetCliPath = null) + private CsProjClassicNetToolchain(string targetFrameworkMoniker, string name, string? packagesPath = null, string? customDotNetCliPath = null) : base(name, new CsProjGenerator(targetFrameworkMoniker, customDotNetCliPath, packagesPath, runtimeFrameworkVersion: null, isNetCore: false), new DotNetCliBuilder(targetFrameworkMoniker, customDotNetCliPath), @@ -34,7 +34,7 @@ private CsProjClassicNetToolchain(string targetFrameworkMoniker, string name, st CustomDotNetCliPath = customDotNetCliPath; } - public static IToolchain From(string targetFrameworkMoniker, string packagesPath = null, string customDotNetCliPath = null) + public static IToolchain From(string targetFrameworkMoniker, string? packagesPath = null, string? customDotNetCliPath = null) => new CsProjClassicNetToolchain(targetFrameworkMoniker, targetFrameworkMoniker, packagesPath, customDotNetCliPath); public override IEnumerable Validate(BenchmarkCase benchmarkCase, IResolver resolver) diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliBuilder.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliBuilder.cs index bad11c91be..e034279f89 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliBuilder.cs @@ -17,7 +17,7 @@ public class DotNetCliBuilder : IBuilder private bool RetryFailedBuildWithNoDeps { get; } [PublicAPI] - public DotNetCliBuilder(string targetFrameworkMoniker, string customDotNetCliPath = null, bool logOutput = false, bool retryFailedBuildWithNoDeps = true) + public DotNetCliBuilder(string targetFrameworkMoniker, string? customDotNetCliPath = null, bool logOutput = false, bool retryFailedBuildWithNoDeps = true) { TargetFrameworkMoniker = targetFrameworkMoniker; CustomDotNetCliPath = customDotNetCliPath; diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommand.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommand.cs index 31546d3112..9967b4ef92 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommand.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommand.cs @@ -166,7 +166,7 @@ public DotNetCliCommandResult PublishNoBuildAndNoRestore() internal static IEnumerable GetAddPackagesCommands(BuildPartition buildPartition) => GetNuGetAddPackageCommands(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver); - internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null, string binLogSuffix = null) + internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string? extraArguments = null, string? binLogSuffix = null) => new StringBuilder() .AppendArgument("restore") .AppendArgument(string.IsNullOrEmpty(artifactsPaths.PackagesDirectoryName) ? string.Empty : $"--packages \"{artifactsPaths.PackagesDirectoryName}\"") @@ -176,7 +176,7 @@ internal static string GetRestoreCommand(ArtifactsPaths artifactsPaths, BuildPar .AppendArgument(GetMsBuildBinLogArgument(buildPartition, binLogSuffix)) .ToString(); - internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null, string binLogSuffix = null) + internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string? extraArguments = null, string? binLogSuffix = null) => new StringBuilder() .AppendArgument($"build -c {buildPartition.BuildConfiguration}") // we don't need to specify TFM, our auto-generated project contains always single one .AppendArgument(GetCustomMsBuildArguments(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver)) @@ -186,7 +186,7 @@ internal static string GetBuildCommand(ArtifactsPaths artifactsPaths, BuildParti .AppendArgument(GetMsBuildBinLogArgument(buildPartition, binLogSuffix)) .ToString(); - internal static string GetPublishCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string extraArguments = null, string binLogSuffix = null) + internal static string GetPublishCommand(ArtifactsPaths artifactsPaths, BuildPartition buildPartition, string? extraArguments = null, string? binLogSuffix = null) => new StringBuilder() .AppendArgument($"publish -c {buildPartition.BuildConfiguration}") // we don't need to specify TFM, our auto-generated project contains always single one .AppendArgument(GetCustomMsBuildArguments(buildPartition.RepresentativeBenchmarkCase, buildPartition.Resolver)) diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs index bfe9a97585..3532fa1e07 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs @@ -99,7 +99,7 @@ internal static void LogEnvVars(DotNetCliCommand command) } internal static ProcessStartInfo BuildStartInfo(string customDotNetCliPath, string workingDirectory, string arguments, - IReadOnlyList environmentVariables = null, bool redirectStandardInput = false, bool redirectStandardError = true, bool redirectStandardOutput = true) + IReadOnlyList? environmentVariables = null, bool redirectStandardInput = false, bool redirectStandardError = true, bool redirectStandardOutput = true) { const string dotnetMultiLevelLookupEnvVarName = "DOTNET_MULTILEVEL_LOOKUP"; diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs index 8292619e49..960558d5c0 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Toolchains.DotNetCli { public class DotNetCliPublisher : IBuilder { - public DotNetCliPublisher(string customDotNetCliPath = null, string extraArguments = null, IReadOnlyList environmentVariables = null) + public DotNetCliPublisher(string? customDotNetCliPath = null, string? extraArguments = null, IReadOnlyList environmentVariables = null) { CustomDotNetCliPath = customDotNetCliPath; ExtraArguments = extraArguments; diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs index 6f0e28834b..bd5fba4123 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/MsBuildErrorMapper.cs @@ -30,7 +30,7 @@ internal static class MsBuildErrorMapper ), }; - internal static bool TryToExplainFailureReason(BuildResult buildResult, out string reason) + internal static bool TryToExplainFailureReason(BuildResult buildResult, out string? reason) { reason = null; diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs index 50b1f7b614..26b76af0a6 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs @@ -44,10 +44,10 @@ public NetCoreAppSettings( string targetFrameworkMoniker, string runtimeFrameworkVersion, string name, - string customDotNetCliPath = null, - string packagesPath = null, - string customRuntimePack = null, - string aotCompilerPath = null, + string? customDotNetCliPath = null, + string? packagesPath = null, + string? customRuntimePack = null, + string? aotCompilerPath = null, MonoAotCompilerMode aotCompilerMode = MonoAotCompilerMode.mini ) { @@ -96,10 +96,10 @@ public NetCoreAppSettings( /// public MonoAotCompilerMode AOTCompilerMode { get; } - public NetCoreAppSettings WithCustomDotNetCliPath(string customDotNetCliPath, string displayName = null) + public NetCoreAppSettings WithCustomDotNetCliPath(string customDotNetCliPath, string? displayName = null) => new NetCoreAppSettings(TargetFrameworkMoniker, RuntimeFrameworkVersion, displayName ?? Name, customDotNetCliPath, PackagesPath); - public NetCoreAppSettings WithCustomPackagesRestorePath(string packagesPath, string displayName = null) + public NetCoreAppSettings WithCustomPackagesRestorePath(string packagesPath, string? displayName = null) => new NetCoreAppSettings(TargetFrameworkMoniker, RuntimeFrameworkVersion, displayName ?? Name, CustomDotNetCliPath, packagesPath); } } diff --git a/src/BenchmarkDotNet/Toolchains/Parameters/ExecuteParameters.cs b/src/BenchmarkDotNet/Toolchains/Parameters/ExecuteParameters.cs index bdfbd78a37..e10c81b49b 100644 --- a/src/BenchmarkDotNet/Toolchains/Parameters/ExecuteParameters.cs +++ b/src/BenchmarkDotNet/Toolchains/Parameters/ExecuteParameters.cs @@ -11,7 +11,7 @@ public class ExecuteParameters { internal static readonly TimeSpan ProcessExitTimeout = TimeSpan.FromSeconds(2); - public ExecuteParameters(BuildResult buildResult, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId, ILogger logger, IResolver resolver, int launchIndex, IDiagnoser diagnoser = null) + public ExecuteParameters(BuildResult buildResult, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId, ILogger logger, IResolver resolver, int launchIndex, IDiagnoser? diagnoser = null) { BuildResult = buildResult; BenchmarkCase = benchmarkCase; diff --git a/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs b/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs index b6de670b8d..8763fcbb7a 100644 --- a/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs +++ b/src/BenchmarkDotNet/Toolchains/Results/GenerateResult.cs @@ -22,7 +22,7 @@ public GenerateResult(ArtifactsPaths artifactsPaths, bool isGenerateSuccess, Exc public static GenerateResult Success(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup) => new GenerateResult(artifactsPaths, true, null, artifactsToCleanup); - public static GenerateResult Failure(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup, Exception exception = null) + public static GenerateResult Failure(ArtifactsPaths artifactsPaths, IReadOnlyCollection artifactsToCleanup, Exception? exception = null) => new GenerateResult(artifactsPaths, false, exception, artifactsToCleanup); public override string ToString() => "GenerateResult: " + (IsGenerateSuccess ? "Success" : "Fail"); diff --git a/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs b/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs index 66f17ce246..bec5bb5081 100644 --- a/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs +++ b/src/BenchmarkDotNet/Toolchains/ToolchainExtensions.cs @@ -30,7 +30,7 @@ private static IToolchain GetToolchain(Job job, Descriptor descriptor) descriptor, job.HasValue(InfrastructureMode.NuGetReferencesCharacteristic) || job.HasValue(InfrastructureMode.BuildConfigurationCharacteristic)); - internal static IToolchain GetToolchain(this Runtime runtime, Descriptor descriptor = null, bool preferMsBuildToolchains = false) + internal static IToolchain GetToolchain(this Runtime runtime, Descriptor? descriptor = null, bool preferMsBuildToolchains = false) { switch (runtime) { diff --git a/src/BenchmarkDotNet/Validators/ValidationError.cs b/src/BenchmarkDotNet/Validators/ValidationError.cs index e8f5e40f6b..23faff5a54 100644 --- a/src/BenchmarkDotNet/Validators/ValidationError.cs +++ b/src/BenchmarkDotNet/Validators/ValidationError.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Validators { public class ValidationError : IEquatable { - public ValidationError(bool isCritical, string message, BenchmarkCase benchmarkCase = null) + public ValidationError(bool isCritical, string message, BenchmarkCase? benchmarkCase = null) { IsCritical = isCritical; Message = message; diff --git a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs index 1171b0f014..e835065b27 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkTestExecutor.cs @@ -36,7 +36,7 @@ protected BenchmarkTestExecutor(ITestOutputHelper output) /// Optional custom config to be used instead of the default /// Optional: disable validation (default = true/enabled) /// The summary from the benchmark run - public Reports.Summary CanExecute(IConfig config = null, bool fullValidation = true) + public Reports.Summary CanExecute(IConfig? config = null, bool fullValidation = true) { return CanExecute(typeof(TBenchmark), config, fullValidation); } @@ -50,7 +50,7 @@ public Reports.Summary CanExecute(IConfig config = null, bool fullVa /// Optional custom config to be used instead of the default /// Optional: disable validation (default = true/enabled) /// The summary from the benchmark run - public Reports.Summary CanExecute(Type type, IConfig config = null, bool fullValidation = true) + public Reports.Summary CanExecute(Type type, IConfig? config = null, bool fullValidation = true) { // Add logging, so the Benchmark execution is in the TestRunner output (makes Debugging easier) if (config == null) @@ -90,7 +90,7 @@ public Reports.Summary CanExecute(Type type, IConfig config = null, bool fullVal return summary; } - protected IConfig CreateSimpleConfig(OutputLogger logger = null, Job job = null) + protected IConfig CreateSimpleConfig(OutputLogger? logger = null, Job? job = null) { var baseConfig = job == null ? (IConfig)new SingleRunFastConfig() : new SingleJobConfig(job); return baseConfig diff --git a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs index 3a532b9a61..ef8bba9095 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs @@ -144,7 +144,7 @@ public override void ExportToLog(Summary summary, ILogger logger) } } - private ImmutableArray CreateReports(Type[] types, IConfig config = null) + private ImmutableArray CreateReports(Type[] types, IConfig? config = null) => CreateBenchmarks(types, config).Select(CreateReport).ToImmutableArray(); private BenchmarkCase[] CreateBenchmarks(Type[] types, IConfig config) diff --git a/tests/BenchmarkDotNet.IntegrationTests/InProcess.EmitTests.T4/RunnableStructCaseBenchmark.tt b/tests/BenchmarkDotNet.IntegrationTests/InProcess.EmitTests.T4/RunnableStructCaseBenchmark.tt index 45dbfdad79..a0fe0c5282 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/InProcess.EmitTests.T4/RunnableStructCaseBenchmark.tt +++ b/tests/BenchmarkDotNet.IntegrationTests/InProcess.EmitTests.T4/RunnableStructCaseBenchmark.tt @@ -54,7 +54,7 @@ namespace BenchmarkDotNet.IntegrationTests.InProcess.EmitTests } }<#+ - private void EmitStructCaseBenchmark(ref int counter, string type, string argValue = null) + private void EmitStructCaseBenchmark(ref int counter, string type, string? argValue = null) { #> // ---- Begin StructCase(<#=type#>) ---- diff --git a/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs b/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs index b0b3b9b07c..4d6325116d 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs @@ -180,7 +180,7 @@ private void TestInvoke(BenchmarkAction benchmarkAction, int unrollFactor, bool } } - private IConfig CreateInProcessConfig(OutputLogger logger = null) + private IConfig CreateInProcessConfig(OutputLogger? logger = null) { return new ManualConfig() .AddJob(Job.Dry.WithToolchain(new InProcessNoEmitToolchain(TimeSpan.Zero, true)).WithInvocationCount(UnrollFactor).WithUnrollFactor(UnrollFactor)) diff --git a/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs b/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs index 52136089cb..1f966fbcaa 100644 --- a/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs +++ b/tests/BenchmarkDotNet.Tests/Engine/EngineWarmupStageTests.cs @@ -81,7 +81,7 @@ public class WithForceAutoWarmup public void Method() { } } - private void AutoTest(Func measure, int min, int max = -1, IterationMode mode = IterationMode.Workload, Job job = null) + private void AutoTest(Func measure, int min, int max = -1, IterationMode mode = IterationMode.Workload, Job? job = null) { if (max == -1) max = min; diff --git a/tests/BenchmarkDotNet.Tests/Reports/FakeMetricDescriptor.cs b/tests/BenchmarkDotNet.Tests/Reports/FakeMetricDescriptor.cs index 8c7316e638..22d06c2b3e 100644 --- a/tests/BenchmarkDotNet.Tests/Reports/FakeMetricDescriptor.cs +++ b/tests/BenchmarkDotNet.Tests/Reports/FakeMetricDescriptor.cs @@ -5,7 +5,7 @@ namespace BenchmarkDotNet.Tests.Reports { internal sealed class FakeMetricDescriptor : IMetricDescriptor { - public FakeMetricDescriptor(string id, string legend, string numberFormat = null) + public FakeMetricDescriptor(string id, string legend, string? numberFormat = null) { Id = id; Legend = legend; diff --git a/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs b/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs index 9ec2c63ffc..b1bcdb1dcd 100644 --- a/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs +++ b/tests/BenchmarkDotNet.Tests/TypeFilterTests.cs @@ -213,7 +213,7 @@ public void GenericTypesCanBeFilteredByDisplayName() Assert.Contains("SomeGeneric.Create", benchmarks); } - private HashSet Filter(Type[] types, string[] args, ILogger logger = null) + private HashSet Filter(Type[] types, string[] args, ILogger? logger = null) { var nonNullLogger = logger ?? new OutputLogger(Output); From 9c2d634f693f37b74fbfad25feaeff342e02a764 Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Sun, 3 Sep 2023 12:36:41 +0200 Subject: [PATCH 3/7] Removed CanBeNull attribute --- tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementChecker.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementChecker.cs b/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementChecker.cs index cbe4ac930e..e0510b92f6 100644 --- a/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementChecker.cs +++ b/tests/BenchmarkDotNet.Tests/XUnit/EnvRequirementChecker.cs @@ -9,11 +9,9 @@ namespace BenchmarkDotNet.Tests.XUnit; public static class EnvRequirementChecker { - [CanBeNull] - public static string GetSkip(params EnvRequirement[] requirements) => requirements.Select(GetSkip).FirstOrDefault(skip => skip != null); + public static string? GetSkip(params EnvRequirement[] requirements) => requirements.Select(GetSkip).FirstOrDefault(skip => skip != null); - [CanBeNull] - internal static string GetSkip(EnvRequirement requirement) => requirement switch + internal static string? GetSkip(EnvRequirement requirement) => requirement switch { EnvRequirement.WindowsOnly => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? null : "Windows-only test", EnvRequirement.NonWindows => !RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? null : "Non-Windows test", From aaf8607887ed7dae010f5921d20cc7eef27b08dd Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Sun, 3 Sep 2023 13:04:37 +0200 Subject: [PATCH 4/7] Fixed warnings on null assignments --- .../InliningDiagnoser.cs | 2 +- .../Tracing/NativeMemoryLogParser.cs | 2 +- .../SourceCodeProvider.cs | 4 ++-- src/BenchmarkDotNet/Characteristics/Characteristic.cs | 2 +- src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs | 2 +- src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs | 2 +- src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs | 2 +- src/BenchmarkDotNet/Engines/Consumer.cs | 4 ++-- .../Environments/ProcessorBrandStringHelper.cs | 2 +- src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs | 8 ++++---- src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs | 2 +- src/BenchmarkDotNet/Loggers/Broker.cs | 3 +-- src/BenchmarkDotNet/Loggers/LinqPadLogger.cs | 2 +- src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs | 6 +++--- .../Emit/Implementation/Emitters/ConsumeEmitter.cs | 6 +++--- .../Emit/Implementation/Emitters/RunnableEmitter.cs | 6 +++--- .../Toolchains/InProcess/Emit/InProcessEmitBuilder.cs | 4 ++-- .../Toolchains/NativeAot/NativeAotToolchainBuilder.cs | 2 +- src/BenchmarkDotNet/Toolchains/Toolchain.cs | 2 +- src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs | 2 +- .../BenchmarkSwitcherTest.cs | 4 ++-- tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs | 4 ++-- tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs | 2 +- .../Builders/HostEnvironmentInfoBuilder.cs | 4 ++-- 24 files changed, 39 insertions(+), 40 deletions(-) diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs index bb9fd42ce7..a21dd1dc81 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/InliningDiagnoser.cs @@ -13,7 +13,7 @@ public class InliningDiagnoser : JitDiagnoser, IProfiler private readonly bool logFailuresOnly = true; private readonly bool filterByNamespace = true; - private readonly string[] allowedNamespaces = null; + private readonly string[]? allowedNamespaces = null; private string defaultNamespace; // ReSharper disable once EmptyConstructor parameterless ctor is mandatory for DiagnosersLoader.CreateDiagnoser diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/NativeMemoryLogParser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/NativeMemoryLogParser.cs index 9e269f28fb..76061eed08 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/NativeMemoryLogParser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/NativeMemoryLogParser.cs @@ -95,7 +95,7 @@ private IEnumerable Parse(TraceLog traceLog) var heapParser = new HeapTraceProviderTraceEventParser(eventSource); // We index by heap address and then within the heap we remember the allocation stack var heaps = new Dictionary>(); - Dictionary lastHeapAllocs = null; + Dictionary? lastHeapAllocs = null; Address lastHeapHandle = 0; diff --git a/src/BenchmarkDotNet.Disassembler.x64/SourceCodeProvider.cs b/src/BenchmarkDotNet.Disassembler.x64/SourceCodeProvider.cs index 7cdb00a6d9..c9ac897570 100644 --- a/src/BenchmarkDotNet.Disassembler.x64/SourceCodeProvider.cs +++ b/src/BenchmarkDotNet.Disassembler.x64/SourceCodeProvider.cs @@ -134,7 +134,7 @@ private static SourceLocation FindNearestLine(PdbFunction function, int ilOffset return null; int distance = int.MaxValue; - SourceLocation nearest = null; + SourceLocation? nearest = null; foreach (PdbSequencePointCollection sequenceCollection in function.SequencePoints) { @@ -183,7 +183,7 @@ private static PdbReader GetReaderForMethod(ClrMethod method) ClrModule module = method?.Type?.Module; PdbInfo info = module?.Pdb; - PdbReader reader = null; + PdbReader? reader = null; if (info != null) { if (!s_pdbReaders.TryGetValue(info, out reader)) diff --git a/src/BenchmarkDotNet/Characteristics/Characteristic.cs b/src/BenchmarkDotNet/Characteristics/Characteristic.cs index 6ca88f5f75..d6e5815b4e 100644 --- a/src/BenchmarkDotNet/Characteristics/Characteristic.cs +++ b/src/BenchmarkDotNet/Characteristics/Characteristic.cs @@ -86,7 +86,7 @@ protected Characteristic( private object FallbackValue { get; } - public object this[CharacteristicObject obj] + public object? this[CharacteristicObject obj] { get { return obj.GetValue(this); } set { obj.SetValue(this, value); } diff --git a/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs b/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs index e8bae27870..de0e35b6dd 100644 --- a/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs +++ b/src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs @@ -128,7 +128,7 @@ private static DisassemblyResult CreateErrorResult(IReadOnlyList input, //line example 2: 0000000000000000 subq $0x28, %rsp private static readonly Regex InstructionRegex = new Regex(@"\s*(?
[0-9a-f]+)(\:\s+([0-9a-f]{2}\s+)+)?\s+(?.*)\s*", RegexOptions.Compiled); - private static bool TryParseInstruction(string line, out MonoCode instruction) + private static bool TryParseInstruction(string line, out MonoCode? instruction) { instruction = null; var match = InstructionRegex.Match(line); diff --git a/src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs b/src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs index 55e31cf8b8..777c24370e 100644 --- a/src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs +++ b/src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs @@ -150,7 +150,7 @@ private static ManagedSymbolModule GetReaderForMethod(ClrMethod method) ClrModule module = method?.Type?.Module; PdbInfo info = module?.Pdb; - ManagedSymbolModule reader = null; + ManagedSymbolModule? reader = null; if (info != null) { if (!s_pdbReaders.TryGetValue(info, out reader)) diff --git a/src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs b/src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs index 6add899105..760ebb4057 100644 --- a/src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs +++ b/src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs @@ -63,7 +63,7 @@ public void SendSignal(HostSignal hostSignal) public void ReportResults(RunResults runResults) => runResults.Print(outWriter); [PublicAPI] // called from generated code - public static bool TryGetFileHandles(string[] args, out string writeHandle, out string readHandle) + public static bool TryGetFileHandles(string[] args, out string? writeHandle, out string? readHandle) { for (int i = 0; i < args.Length; i++) { diff --git a/src/BenchmarkDotNet/Engines/Consumer.cs b/src/BenchmarkDotNet/Engines/Consumer.cs index 1abedec0d6..55f8e3b040 100644 --- a/src/BenchmarkDotNet/Engines/Consumer.cs +++ b/src/BenchmarkDotNet/Engines/Consumer.cs @@ -31,7 +31,7 @@ private static readonly HashSet SupportedTypes private double doubleHolder; private long longHolder; private ulong ulongHolder; - private volatile object objectHolder; + private volatile object? objectHolder; private volatile IntPtr ptrHolder; private volatile UIntPtr uptrHolder; #pragma warning restore IDE0052 // Remove unread private members @@ -157,7 +157,7 @@ public void Consume(in T value) internal static bool IsConsumable(Type type) => SupportedTypes.Contains(type) || type.GetTypeInfo().IsClass || type.GetTypeInfo().IsInterface; - internal static bool HasConsumableField(Type type, out FieldInfo consumableField) + internal static bool HasConsumableField(Type type, out FieldInfo? consumableField) { var typeInfo = type.GetTypeInfo(); diff --git a/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs b/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs index 17f79e3202..882078df74 100644 --- a/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs +++ b/src/BenchmarkDotNet/Environments/ProcessorBrandStringHelper.cs @@ -94,7 +94,7 @@ private static string GetBrandStyledActualFrequency(Frequency? frequency) { var data = ResourceHelper.LoadResource("BenchmarkDotNet.Environments.microarchitectures.txt").Split('\r', '\n'); var dictionary = new Dictionary(); - string currentMicroarchitecture = null; + string? currentMicroarchitecture = null; foreach (string line in data) { if (line.StartsWith("//") || string.IsNullOrWhiteSpace(line)) diff --git a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs index bd6923d95d..1f91648f90 100644 --- a/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs +++ b/src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs @@ -77,7 +77,7 @@ internal static CoreRuntime FromVersion(Version version) } } - internal static bool TryGetVersion(out Version version) + internal static bool TryGetVersion(out Version? version) { // we can't just use System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription // because it can be null and it reports versions like 4.6.* for .NET Core 2.* @@ -124,7 +124,7 @@ internal static bool TryGetVersion(out Version version) // sample input: // for dotnet run: C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.1.12\ // for dotnet publish: C:\Users\adsitnik\source\repos\ConsoleApp25\ConsoleApp25\bin\Release\netcoreapp2.0\win-x64\publish\ - internal static bool TryGetVersionFromRuntimeDirectory(string runtimeDirectory, out Version version) + internal static bool TryGetVersionFromRuntimeDirectory(string runtimeDirectory, out Version? version) { if (!string.IsNullOrEmpty(runtimeDirectory) && Version.TryParse(GetParsableVersionPart(new DirectoryInfo(runtimeDirectory).Name), out version)) { @@ -141,7 +141,7 @@ internal static bool TryGetVersionFromRuntimeDirectory(string runtimeDirectory, // 2.2: 4.6.27817.03 @BuiltBy: dlab14-DDVSOWINAGE101 @Branch: release/2.2 @SrcCode: https://github.com/dotnet/coreclr/tree/ce1d090d33b400a25620c0145046471495067cc7, Microsoft .NET Framework // 3.0: 3.0.0-preview8.19379.2+ac25be694a5385a6a1496db40de932df0689b742, Microsoft .NET Core // 5.0: 5.0.0-alpha1.19413.7+0ecefa44c9d66adb8a997d5778dc6c246ad393a7, Microsoft .NET Core - internal static bool TryGetVersionFromProductInfo(string productVersion, string productName, out Version version) + internal static bool TryGetVersionFromProductInfo(string productVersion, string productName, out Version? version) { if (!string.IsNullOrEmpty(productVersion) && !string.IsNullOrEmpty(productName)) { @@ -175,7 +175,7 @@ internal static bool TryGetVersionFromProductInfo(string productVersion, string // sample input: // .NETCoreApp,Version=v2.0 // .NETCoreApp,Version=v2.1 - internal static bool TryGetVersionFromFrameworkName(string frameworkName, out Version version) + internal static bool TryGetVersionFromFrameworkName(string frameworkName, out Version? version) { const string versionPrefix = ".NETCoreApp,Version=v"; if (!string.IsNullOrEmpty(frameworkName) && frameworkName.StartsWith(versionPrefix)) diff --git a/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs b/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs index 1f4160393c..9ccbdd2323 100644 --- a/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs +++ b/src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs @@ -110,7 +110,7 @@ private void WriteCollectionProperty(object source, PropertyInfo property) writer.WriteStartElement(property.Name); - string itemName = null; + string? itemName = null; foreach (var item in collection) { diff --git a/src/BenchmarkDotNet/Loggers/Broker.cs b/src/BenchmarkDotNet/Loggers/Broker.cs index 9055523340..cec11a3091 100644 --- a/src/BenchmarkDotNet/Loggers/Broker.cs +++ b/src/BenchmarkDotNet/Loggers/Broker.cs @@ -78,9 +78,8 @@ private void ProcessDataBlocking() using StreamWriter writer = new (acknowledgments, AnonymousPipesHost.UTF8NoBOM, bufferSize: 1); // Flush the data to the Stream after each write, otherwise the client will wait for input endlessly! writer.AutoFlush = true; - string line = null; - while ((line = reader.ReadLine()) is not null) + while (reader.ReadLine() is { } line) { // TODO: implement Silent mode here logger.WriteLine(LogKind.Default, line); diff --git a/src/BenchmarkDotNet/Loggers/LinqPadLogger.cs b/src/BenchmarkDotNet/Loggers/LinqPadLogger.cs index 930d19d4ca..01fa682c99 100644 --- a/src/BenchmarkDotNet/Loggers/LinqPadLogger.cs +++ b/src/BenchmarkDotNet/Loggers/LinqPadLogger.cs @@ -16,7 +16,7 @@ public sealed class LinqPadLogger : ILogger public static readonly Lazy lazyInstance = new Lazy(() => { // Detect if being run from LINQPad; see https://github.com/dotnet/BenchmarkDotNet/issues/445#issuecomment-300723741 - MethodInfo withStyle = null; + MethodInfo? withStyle = null; if (AppDomain.CurrentDomain.FriendlyName.StartsWith("LINQPad", StringComparison.OrdinalIgnoreCase)) { try diff --git a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs index d732275d95..af12d018b5 100644 --- a/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs +++ b/src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs @@ -121,7 +121,7 @@ protected virtual string GetRuntimeSettings(GcMode gcMode, IResolver resolver) // custom SDKs are not added for non-netcoreapp apps (like net471), so when the TFM != netcoreapp we dont parse " - string sdkName = null; + string? sdkName = null; if (TargetFrameworkMoniker.StartsWith("netcoreapp", StringComparison.InvariantCultureIgnoreCase)) { foreach (XmlElement importElement in projectElement.GetElementsByTagName("Import")) @@ -161,8 +161,8 @@ protected virtual string GetRuntimeSettings(GcMode gcMode, IResolver resolver) sdkName = DefaultSdkName; } - XmlDocument itemGroupsettings = null; - XmlDocument propertyGroupSettings = null; + XmlDocument? itemGroupsettings = null; + XmlDocument? propertyGroupSettings = null; GetSettingsThatNeedToBeCopied(projectElement, ref itemGroupsettings, ref propertyGroupSettings, projectFile); diff --git a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/ConsumeEmitter.cs b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/ConsumeEmitter.cs index 62fe06c649..9767cb8263 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/ConsumeEmitter.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/ConsumeEmitter.cs @@ -31,9 +31,9 @@ protected ConsumeEmitter(ConsumableTypeInfo consumableTypeInfo) protected ConsumableTypeInfo ConsumableInfo { get; } - protected ILGenerator IlBuilder { get; private set; } - protected MethodBuilder ActionMethodBuilder { get; private set; } - protected MethodInfo ActionInvokeMethod { get; private set; } + protected ILGenerator? IlBuilder { get; private set; } + protected MethodBuilder? ActionMethodBuilder { get; private set; } + protected MethodInfo? ActionInvokeMethod { get; private set; } protected RunnableActionKind? ActionKind { get; private set; } [AssertionMethod] diff --git a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/RunnableEmitter.cs b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/RunnableEmitter.cs index c6c6d8e05c..9048474329 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/RunnableEmitter.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/Implementation/Emitters/RunnableEmitter.cs @@ -434,7 +434,7 @@ private void DefineFields() Type argLocalsType; Type argFieldType; - MethodInfo opConversion = null; + MethodInfo? opConversion = null; if (parameterType.IsByRef) { argLocalsType = parameterType; @@ -833,8 +833,8 @@ .locals init ( var skipFirstArg = workloadMethod.IsStatic; var argLocals = EmitDeclareArgLocals(ilBuilder, skipFirstArg); - LocalBuilder callResultLocal = null; - LocalBuilder awaiterLocal = null; + LocalBuilder? callResultLocal = null; + LocalBuilder? awaiterLocal = null; if (consumableInfo.IsAwaitable) { var callResultType = consumableInfo.OriginMethodReturnType; diff --git a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/InProcessEmitBuilder.cs b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/InProcessEmitBuilder.cs index f46f5c99b6..7a75eb3263 100644 --- a/src/BenchmarkDotNet/Toolchains/InProcess/Emit/InProcessEmitBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/InProcess/Emit/InProcessEmitBuilder.cs @@ -11,8 +11,8 @@ public class InProcessEmitBuilder : IBuilder { public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger) { - Assembly assembly = null; - Exception buildError = null; + Assembly? assembly = null; + Exception? buildError = null; try { assembly = RunnableEmitter.EmitPartitionAssembly(generateResult, buildPartition, logger); diff --git a/src/BenchmarkDotNet/Toolchains/NativeAot/NativeAotToolchainBuilder.cs b/src/BenchmarkDotNet/Toolchains/NativeAot/NativeAotToolchainBuilder.cs index 4d37882007..9cdc679716 100644 --- a/src/BenchmarkDotNet/Toolchains/NativeAot/NativeAotToolchainBuilder.cs +++ b/src/BenchmarkDotNet/Toolchains/NativeAot/NativeAotToolchainBuilder.cs @@ -17,7 +17,7 @@ public class NativeAotToolchainBuilder : CustomDotNetCliToolchainBuilder private bool ilcGenerateCompleteTypeMetadata = true; private bool ilcGenerateStackTraceData = true; private string ilcOptimizationPreference = "Speed"; - private string ilcInstructionSet = null; + private string? ilcInstructionSet = null; private bool isIlCompilerConfigured; diff --git a/src/BenchmarkDotNet/Toolchains/Toolchain.cs b/src/BenchmarkDotNet/Toolchains/Toolchain.cs index bbe5f1d94f..e680424de7 100644 --- a/src/BenchmarkDotNet/Toolchains/Toolchain.cs +++ b/src/BenchmarkDotNet/Toolchains/Toolchain.cs @@ -57,7 +57,7 @@ public virtual IEnumerable Validate(BenchmarkCase benchmarkCase } } - internal static bool IsCliPathInvalid(string customDotNetCliPath, BenchmarkCase benchmarkCase, out ValidationError validationError) + internal static bool IsCliPathInvalid(string customDotNetCliPath, BenchmarkCase benchmarkCase, out ValidationError? validationError) { validationError = null; diff --git a/src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs b/src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs index 92d7422ae2..11af691440 100644 --- a/src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs +++ b/src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs @@ -52,7 +52,7 @@ public IEnumerable Validate(ValidationParameters validationPara return errors; } - private bool TryCreateBenchmarkTypeInstance(Type type, List errors, out object instance) + private bool TryCreateBenchmarkTypeInstance(Type type, List errors, out object? instance) { try { diff --git a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs index 695a3baeb6..e9a95fce81 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/BenchmarkSwitcherTest.cs @@ -135,7 +135,7 @@ public void WhenDisableLogFileWeDontWriteToFile() var logger = new OutputLogger(Output); var config = ManualConfig.CreateEmpty().AddLogger(logger).WithOptions(ConfigOptions.DisableLogFile).AddJob(Job.Dry); - string logFilePath = null; + string? logFilePath = null; try { var summaries = BenchmarkSwitcher @@ -161,7 +161,7 @@ public void EnsureLogFileIsWritten() var logger = new OutputLogger(Output); var config = ManualConfig.CreateEmpty().AddLogger(logger).AddJob(Job.Dry); - string logFilePath = null; + string? logFilePath = null; try { var summaries = BenchmarkSwitcher diff --git a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs index ef8bba9095..18328994cb 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs @@ -81,7 +81,7 @@ public void ExporterUsesFullyQualifiedTypeNameAsFileName() var exporter = new MockExporter(); var mockSummary = GetMockSummary(resultsDirectoryPath, config: null, typeof(Generic)); var expectedFilePath = $"{Path.Combine(mockSummary.ResultsDirectoryPath, "BenchmarkDotNet.IntegrationTests.Generic_Int32_")}-report.txt"; - string actualFilePath = null; + string? actualFilePath = null; try { @@ -104,7 +104,7 @@ public void ExporterUsesSummaryTitleAsFileNameWhenBenchmarksJoinedToSingleSummar var joinConfig = ManualConfig.CreateEmpty().WithOptions(ConfigOptions.JoinSummary); var mockSummary = GetMockSummary(resultsDirectoryPath, joinConfig, typeof(ClassA), typeof(ClassB)); var expectedFilePath = $"{Path.Combine(mockSummary.ResultsDirectoryPath, mockSummary.Title)}-report.txt"; - string actualFilePath = null; + string? actualFilePath = null; try { diff --git a/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs b/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs index 4d6325116d..619eaa5740 100644 --- a/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs +++ b/tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs @@ -123,7 +123,7 @@ private void TestInvoke(Expression> methodCall, in bool isValueTask = typeof(T).IsConstructedGenericType && typeof(T).GetGenericTypeDefinition() == typeof(ValueTask<>); - object idleExpected; + object? idleExpected; if (isValueTask) idleExpected = GetDefault(typeof(T).GetGenericArguments()[0]); else if (typeof(T).GetTypeInfo().IsValueType) diff --git a/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs b/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs index e77ee1abd9..d22256f0a9 100644 --- a/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs +++ b/tests/BenchmarkDotNet.Tests/Builders/HostEnvironmentInfoBuilder.cs @@ -12,7 +12,7 @@ public class HostEnvironmentInfoBuilder private string benchmarkDotNetVersion = "0.10.x-mock"; private Frequency chronometerFrequency = new Frequency(2531248); private string configuration = "CONFIGURATION"; - private string dotNetSdkVersion = "1.0.x.mock"; + private string? dotNetSdkVersion = "1.0.x.mock"; private HardwareTimerKind hardwareTimerKind = HardwareTimerKind.Tsc; private bool hasAttachedDebugger = false; private bool hasRyuJit = true; @@ -31,7 +31,7 @@ public class HostEnvironmentInfoBuilder maxFrequency: Frequency.FromMHz(3100), minFrequency: Frequency.FromMHz(3100)); - private VirtualMachineHypervisor virtualMachineHypervisor = HyperV.Default; + private VirtualMachineHypervisor? virtualMachineHypervisor = HyperV.Default; public HostEnvironmentInfoBuilder WithVMHypervisor(VirtualMachineHypervisor hypervisor) { From 68a9e012294df2d605ce9db3d841585609e9b678 Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Mon, 4 Sep 2023 15:30:58 +0200 Subject: [PATCH 5/7] Fixed warnings in EngineEventLogParser --- .../Tracing/EngineEventLogParser.cs | 40 +++++++++---------- .../Tracing/IterationEvent.cs | 10 ++--- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/EngineEventLogParser.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/EngineEventLogParser.cs index c385c1c440..f7e3d8e6fd 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/EngineEventLogParser.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/EngineEventLogParser.cs @@ -8,7 +8,7 @@ namespace BenchmarkDotNet.Diagnostics.Windows.Tracing { public sealed class EngineEventLogParser : TraceEventParser { - private static volatile TraceEvent[] templates; + private static volatile TraceEvent[]? templates; public EngineEventLogParser(TraceEventSource source, bool dontRegister = false) : base(source, dontRegister) { } @@ -114,69 +114,69 @@ public event Action WorkloadActualStop protected override string GetProviderName() { return ProviderName; } - private static IterationEvent BenchmarkStartTemplate(Action action) + private static IterationEvent BenchmarkStartTemplate(Action? action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new IterationEvent(action, EngineEventSource.BenchmarkStartEventId, (int)EngineEventSource.Tasks.Benchmark, nameof(EngineEventSource.Tasks.Benchmark), Guid.Empty, (int)EventOpcode.Start, nameof(EventOpcode.Start), ProviderGuid, ProviderName); } - private static IterationEvent BenchmarkStopTemplate(Action action) + private static IterationEvent BenchmarkStopTemplate(Action? action) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new IterationEvent(action, EngineEventSource.BenchmarkStopEventId, (int)EngineEventSource.Tasks.Benchmark, nameof(EngineEventSource.Tasks.Benchmark), Guid.Empty, (int)EventOpcode.Stop, nameof(EventOpcode.Stop), ProviderGuid, ProviderName); } - private static IterationEvent OverheadJittingStartTemplate(Action action) + private static IterationEvent OverheadJittingStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.OverheadJittingStartEventId, EngineEventSource.Tasks.OverheadJitting); - private static IterationEvent OverheadJittingStopTemplate(Action action) + private static IterationEvent OverheadJittingStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.OverheadJittingStopEventId, EngineEventSource.Tasks.OverheadJitting); - private static IterationEvent WorkloadJittingStartTemplate(Action action) + private static IterationEvent WorkloadJittingStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.WorkloadJittingStartEventId, EngineEventSource.Tasks.WorkloadJitting); - private static IterationEvent WorkloadJittingStopTemplate(Action action) + private static IterationEvent WorkloadJittingStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.WorkloadJittingStopEventId, EngineEventSource.Tasks.WorkloadJitting); - private static IterationEvent WorkloadPilotStartTemplate(Action action) + private static IterationEvent WorkloadPilotStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.WorkloadPilotStartEventId, EngineEventSource.Tasks.WorkloadPilot); - private static IterationEvent WorkloadPilotStopTemplate(Action action) + private static IterationEvent WorkloadPilotStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.WorkloadPilotStopEventId, EngineEventSource.Tasks.WorkloadPilot); - private static IterationEvent OverheadWarmupStartTemplate(Action action) + private static IterationEvent OverheadWarmupStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.OverheadWarmupStartEventId, EngineEventSource.Tasks.OverheadWarmup); - private static IterationEvent OverheadWarmupStopTemplate(Action action) + private static IterationEvent OverheadWarmupStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.OverheadWarmupStopEventId, EngineEventSource.Tasks.OverheadWarmup); - private static IterationEvent WorkloadWarmupStartTemplate(Action action) + private static IterationEvent WorkloadWarmupStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.WorkloadWarmupStartEventId, EngineEventSource.Tasks.WorkloadWarmup); - private static IterationEvent WorkloadWarmupStopTemplate(Action action) + private static IterationEvent WorkloadWarmupStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.WorkloadWarmupStopEventId, EngineEventSource.Tasks.WorkloadWarmup); - private static IterationEvent OverheadActualStartTemplate(Action action) + private static IterationEvent OverheadActualStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.OverheadActualStartEventId, EngineEventSource.Tasks.OverheadActual); - private static IterationEvent OverheadActualStopTemplate(Action action) + private static IterationEvent OverheadActualStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.OverheadActualStopEventId, EngineEventSource.Tasks.OverheadActual); - private static IterationEvent WorkloadActualStartTemplate(Action action) + private static IterationEvent WorkloadActualStartTemplate(Action? action) => CreateIterationStartTemplate(action, EngineEventSource.WorkloadActualStartEventId, EngineEventSource.Tasks.WorkloadActual); - private static IterationEvent WorkloadActualStopTemplate(Action action) + private static IterationEvent WorkloadActualStopTemplate(Action? action) => CreateIterationStopTemplate(action, EngineEventSource.WorkloadActualStopEventId, EngineEventSource.Tasks.WorkloadActual); - private static IterationEvent CreateIterationStartTemplate(Action action, int eventId, EventTask eventTask) + private static IterationEvent CreateIterationStartTemplate(Action? action, int eventId, EventTask eventTask) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new IterationEvent(action, eventId, (int)eventTask, eventTask.ToString(), Guid.Empty, (int)EventOpcode.Start, nameof(EventOpcode.Start), ProviderGuid, ProviderName); } - private static IterationEvent CreateIterationStopTemplate(Action action, int eventId, EventTask eventTask) + private static IterationEvent CreateIterationStopTemplate(Action? action, int eventId, EventTask eventTask) { // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName return new IterationEvent(action, eventId, (int)eventTask, eventTask.ToString(), Guid.Empty, (int)EventOpcode.Stop, nameof(EventOpcode.Stop), ProviderGuid, ProviderName); } - protected override void EnumerateTemplates(Func eventsToObserve, Action callback) + protected override void EnumerateTemplates(Func? eventsToObserve, Action callback) { if (templates == null) { diff --git a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs index 7908f7cf52..3367aa7c60 100644 --- a/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs +++ b/src/BenchmarkDotNet.Diagnostics.Windows/Tracing/IterationEvent.cs @@ -9,15 +9,15 @@ public sealed class IterationEvent : TraceEvent { public long TotalOperations => GetInt64At(0); - private event Action target; + private event Action? target; - internal IterationEvent(Action target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) - : base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) + internal IterationEvent(Action? target, int eventId, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName) + : base(eventId, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName) { this.target = target; } - protected override Delegate Target + protected override Delegate? Target { get => target; set => target = (Action)value; @@ -34,7 +34,7 @@ public override StringBuilder ToXml(StringBuilder sb) return sb; } - public override object PayloadValue(int index) => index == 0 ? (object)TotalOperations : null; + public override object? PayloadValue(int index) => index == 0 ? TotalOperations : null; protected override void Dispatch() => target?.Invoke(this); From 3a86aadbede4c52e1b10dc019bc015ca8f496335 Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Mon, 4 Sep 2023 15:31:27 +0200 Subject: [PATCH 6/7] Removed an unnecessary check --- src/BenchmarkDotNet.Annotations/Attributes/TargetedAttribute.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/BenchmarkDotNet.Annotations/Attributes/TargetedAttribute.cs b/src/BenchmarkDotNet.Annotations/Attributes/TargetedAttribute.cs index f026675bd7..efeb7ee0c6 100644 --- a/src/BenchmarkDotNet.Annotations/Attributes/TargetedAttribute.cs +++ b/src/BenchmarkDotNet.Annotations/Attributes/TargetedAttribute.cs @@ -20,6 +20,6 @@ public string Target set => Targets = string.IsNullOrEmpty(value) ? new string[0] : value.Split(','); // , is for backward compat } - public bool Match(MethodInfo method) => Targets == null || Targets.Length == 0 || Targets.Contains(method.Name); + public bool Match(MethodInfo method) => Targets.Length == 0 || Targets.Contains(method.Name); } } From ddca6281e703cc6c2285476daa045cba5a13af1c Mon Sep 17 00:00:00 2001 From: Alina Smirnova Date: Mon, 4 Sep 2023 15:32:56 +0200 Subject: [PATCH 7/7] Fixed empty catch warning --- samples/BenchmarkDotNet.Samples/IntroExceptionDiagnoser.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/samples/BenchmarkDotNet.Samples/IntroExceptionDiagnoser.cs b/samples/BenchmarkDotNet.Samples/IntroExceptionDiagnoser.cs index a43844e592..7e0f847c95 100644 --- a/samples/BenchmarkDotNet.Samples/IntroExceptionDiagnoser.cs +++ b/samples/BenchmarkDotNet.Samples/IntroExceptionDiagnoser.cs @@ -16,7 +16,10 @@ public void ThrowExceptionRandomly() throw new Exception(); } } - catch { } + catch + { + // ignored + } } } }