Skip to content

Commit

Permalink
Nullability cleanup (2023-11-26)
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreyAkinshin committed Nov 26, 2023
1 parent a572db1 commit b4ac9df
Show file tree
Hide file tree
Showing 23 changed files with 94 additions and 70 deletions.
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Analysers/BaselineCustomAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ protected override IEnumerable<Conclusion> AnalyseSummary(Summary summary)

foreach (var benchmarkCase in summary.BenchmarksCases)
{
string logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase);
string? logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase);
var baseline = summary.GetBaseline(logicalGroupKey);
if (BaselineCustomColumn.ResultsAreInvalid(summary, benchmarkCase, baseline) == false)
continue;
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ string Format(int n, string verb)
return $"{n} {words} {verb}";
}

var rangeMessages = new List<string> { GetRangeMessage(lowerOutliers, cultureInfo), GetRangeMessage(upperOutliers, cultureInfo) };
var rangeMessages = new List<string?> { GetRangeMessage(lowerOutliers, cultureInfo), GetRangeMessage(upperOutliers, cultureInfo) };
rangeMessages.RemoveAll(string.IsNullOrEmpty);
string rangeMessage = rangeMessages.Any()
? " (" + string.Join(", ", rangeMessages) + ")"
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Columns/BaselineCustomColumn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public string GetValue(Summary summary, BenchmarkCase benchmarkCase)
public override string ToString() => ColumnName;
public bool IsDefault(Summary summary, BenchmarkCase benchmarkCase) => false;

internal static bool ResultsAreInvalid(Summary summary, BenchmarkCase benchmarkCase, BenchmarkCase baseline)
internal static bool ResultsAreInvalid(Summary summary, BenchmarkCase benchmarkCase, BenchmarkCase? baseline)
{
return baseline == null ||
summary[baseline] == null ||
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Columns/TagColumn.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public TagColumn(string columnName, Func<string, string> getTag)
}

public bool IsDefault(Summary summary, BenchmarkCase benchmarkCase) => false;
public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => getTag(benchmarkCase.Descriptor.WorkloadMethod.Name);
public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => getTag(benchmarkCase.Descriptor?.WorkloadMethod?.Name ?? "");

public bool IsAvailable(Summary summary) => true;
public bool AlwaysShow => true;
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Configs/ImmutableConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public sealed class ImmutableConfig : IConfig

public bool HasExtraStatsDiagnoser() => HasMemoryDiagnoser() || HasThreadingDiagnoser() || HasExceptionDiagnoser();

public IDiagnoser GetCompositeDiagnoser(BenchmarkCase benchmarkCase, RunMode runMode)
public IDiagnoser? GetCompositeDiagnoser(BenchmarkCase benchmarkCase, RunMode runMode)
{
var diagnosersForGivenMode = diagnosers.Where(diagnoser => diagnoser.GetRunMode(benchmarkCase) == runMode).ToImmutableHashSet();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Diagnosers
{
public class DiagnoserActionParameters
{
public DiagnoserActionParameters(Process process, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId)
public DiagnoserActionParameters(Process? process, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId)
{
Process = process;
BenchmarkCase = benchmarkCase;
Expand Down
1 change: 1 addition & 0 deletions src/BenchmarkDotNet/Exporters/Json/SimpleJson.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#nullable disable
// ReSharper disable All
//-----------------------------------------------------------------------
// <copyright file="SimpleJson.cs" company="The Outercurve Foundation">
Expand Down
12 changes: 8 additions & 4 deletions src/BenchmarkDotNet/Extensions/CommonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,20 @@ public static string GetColumnTitle(this IColumn column, SummaryStyle style)
}
}

public static bool IsNullOrEmpty<T>(this IReadOnlyCollection<T> value) => value == null || value.Count == 0;
public static bool IsNullOrEmpty<T>(this IReadOnlyCollection<T>? value) => value == null || value.Count == 0;
public static bool IsEmpty<T>(this IReadOnlyCollection<T> value) => value.Count == 0;
public static bool IsEmpty<T>(this IEnumerable<T> value) => !value.Any();

public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> values) => values.Where(value => value != null).Cast<T>();

public static void AddRange<T>(this HashSet<T> hashSet, IEnumerable<T> collection)
{
foreach (var item in collection)
hashSet.Add(item);
}

#if NETSTANDARD2_0
public static TValue GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
public static TValue? GetValueOrDefault<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
=> dictionary.TryGetValue(key, out var value) ? value : default;
#endif

Expand Down Expand Up @@ -97,15 +99,17 @@ internal static string DeleteFileIfExists(this string filePath)

internal static string EnsureFolderExists(this string filePath)
{
string directoryPath = Path.GetDirectoryName(filePath);
string? directoryPath = Path.GetDirectoryName(filePath);
if (directoryPath == null)
throw new ArgumentException($"Can't get directory path from '{filePath}'");

if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);

return filePath;
}

internal static bool IsNotNullButDoesNotExist(this FileSystemInfo fileInfo)
internal static bool IsNotNullButDoesNotExist(this FileSystemInfo? fileInfo)
=> fileInfo != null && !fileInfo.Exists;
}
}
14 changes: 14 additions & 0 deletions src/BenchmarkDotNet/Helpers/Assertion.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using JetBrains.Annotations;

namespace BenchmarkDotNet.Helpers;

internal static class Assertion
{
[AssertionMethod]
public static void NotNull(string name, object? value)
{
if (value == null)
throw new ArgumentNullException(name, $"{name} can't be null");
}
}
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ internal class DirtyAssemblyResolveHelper : IDisposable
/// "the handler is invoked whenever the runtime fails to bind to an assembly by name."
/// </summary>
/// <returns>not null when we find it manually, null when can't help</returns>
private Assembly HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEventArgs args)
private Assembly? HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEventArgs args)
{
var fullName = new AssemblyName(args.Name);
string simpleName = fullName.Name;
Expand Down
12 changes: 8 additions & 4 deletions src/BenchmarkDotNet/Reports/Summary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public class Summary
/// <summary>
/// Returns a report for the given benchmark or null if there is no a corresponded report.
/// </summary>
public BenchmarkReport this[BenchmarkCase benchmarkCase] => ReportMap.GetValueOrDefault(benchmarkCase);
public BenchmarkReport? this[BenchmarkCase benchmarkCase] => ReportMap.GetValueOrDefault(benchmarkCase);

public bool HasCriticalValidationErrors => ValidationErrors.Any(validationError => validationError.IsCritical);

Expand Down Expand Up @@ -108,7 +108,7 @@ internal static string BuildAllRuntimes(HostEnvironmentInfo hostEnvironmentInfo,

foreach (var benchmarkReport in reports)
{
string runtime = benchmarkReport.GetRuntimeInfo();
string? runtime = benchmarkReport.GetRuntimeInfo();
if (runtime != null)
{
string jobId = benchmarkReport.BenchmarkCase.Job.ResolvedId;
Expand All @@ -135,7 +135,7 @@ internal static string BuildAllRuntimes(HostEnvironmentInfo hostEnvironmentInfo,
public bool IsBaseline(BenchmarkCase benchmarkCase)
=> BaseliningStrategy.IsBaseline(benchmarkCase);

public BenchmarkCase? GetBaseline(string logicalGroupKey)
public BenchmarkCase? GetBaseline(string? logicalGroupKey)
=> BenchmarksCases
.Where(b => GetLogicalGroupKey(b) == logicalGroupKey)
.FirstOrDefault(IsBaseline);
Expand All @@ -158,7 +158,11 @@ private static IOrderer GetConfiguredOrdererOrDefaultOne(IEnumerable<ImmutableCo
private static SummaryStyle GetConfiguredSummaryStyleOrDefaultOne(ImmutableArray<BenchmarkCase> benchmarkCases)
=> benchmarkCases
.Where(benchmark => benchmark.Config.SummaryStyle != SummaryStyle.Default
&& benchmark.Config.SummaryStyle != null) // Paranoid
#nullable disable
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract ConditionIsAlwaysTrueOrFalse
// TODO: remove this check once the nullability migration is finished
&& benchmark.Config.SummaryStyle != null) // Paranoid
#nullable enable
.Select(benchmark => benchmark.Config.SummaryStyle)
.Distinct()
.SingleOrDefault()
Expand Down
6 changes: 3 additions & 3 deletions src/BenchmarkDotNet/Reports/SummaryStyle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ public class SummaryStyle : IEquatable<SummaryStyle>
public bool PrintUnitsInContent { get; }
public bool PrintZeroValuesInContent { get; }
public int MaxParameterColumnWidth { get; }
public SizeUnit SizeUnit { get; }
public SizeUnit? SizeUnit { get; }
internal SizeUnit CodeSizeUnit { get; }
public TimeUnit TimeUnit { get; }
public TimeUnit? TimeUnit { get; }
public CultureInfo CultureInfo { get; }

public RatioStyle RatioStyle { get; }

public TextJustification TextColumnJustification { get; }
public TextJustification NumericColumnJustification { get; }

public SummaryStyle(CultureInfo? cultureInfo, bool printUnitsInHeader, SizeUnit sizeUnit, TimeUnit timeUnit, bool printUnitsInContent = true,
public SummaryStyle(CultureInfo? cultureInfo, bool printUnitsInHeader, SizeUnit? sizeUnit, TimeUnit? timeUnit, bool printUnitsInContent = true,
bool printZeroValuesInContent = false, int maxParameterColumnWidth = DefaultMaxParameterColumnWidth, RatioStyle ratioStyle = RatioStyle.Value,
TextJustification textColumnJustification = TextJustification.Left, TextJustification numericColumnJustification = TextJustification.Right)
{
Expand Down
25 changes: 14 additions & 11 deletions src/BenchmarkDotNet/Running/Descriptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@ public class Descriptor : IEquatable<Descriptor>
{
public Type Type { get; }
public MethodInfo WorkloadMethod { get; }
public MethodInfo GlobalSetupMethod { get; }
public MethodInfo GlobalCleanupMethod { get; }
public MethodInfo IterationSetupMethod { get; }
public MethodInfo IterationCleanupMethod { get; }
public MethodInfo? GlobalSetupMethod { get; }
public MethodInfo? GlobalCleanupMethod { get; }
public MethodInfo? IterationSetupMethod { get; }
public MethodInfo? IterationCleanupMethod { get; }
public string AdditionalLogic { get; }
public int OperationsPerInvoke { get; }
public string WorkloadMethodDisplayInfo { get; }
public int MethodIndex { get; }
public bool Baseline { get; }
public string[] Categories { get; }

internal string TypeInfo => Type?.GetDisplayName() ?? "Untitled";
private string MethodFolderInfo => WorkloadMethod?.Name ?? "Untitled";
internal string TypeInfo => Type.GetDisplayName();
private string MethodFolderInfo => WorkloadMethod.Name;

public string FolderInfo => (Type != null ? FolderNameHelper.ToFolderName(Type) : "Untitled") + "_" + MethodFolderInfo;
public string FolderInfo => $"{FolderNameHelper.ToFolderName(Type)}_{MethodFolderInfo}";
public string DisplayInfo => TypeInfo + "." + WorkloadMethodDisplayInfo;

public Descriptor(
Expand All @@ -42,6 +42,9 @@ public class Descriptor : IEquatable<Descriptor>
int operationsPerInvoke = 1,
int methodIndex = 0)
{
Assertion.NotNull(nameof(type), type);
Assertion.NotNull(nameof(workloadMethod), workloadMethod);

Type = type;
WorkloadMethod = workloadMethod;
GlobalSetupMethod = globalSetupMethod;
Expand All @@ -58,9 +61,9 @@ public class Descriptor : IEquatable<Descriptor>

public override string ToString() => DisplayInfo;

private static string FormatDescription(string? description)
private static string? FormatDescription(string? description)
{
var specialSymbols = new[] { ' ', '\'', '[', ']' };
char[] specialSymbols = { ' ', '\'', '[', ']' };
return description != null && specialSymbols.Any(description.Contains)
? "'" + description + "'"
: description;
Expand All @@ -70,9 +73,9 @@ private static string FormatDescription(string? description)

public string GetFilterName() => $"{Type.GetCorrectCSharpTypeName(includeGenericArgumentsNamespace: false)}.{WorkloadMethod.Name}";

public bool Equals(Descriptor other) => GetFilterName().Equals(other.GetFilterName());
public bool Equals(Descriptor? other) => GetFilterName().Equals(other?.GetFilterName());

public override bool Equals(object obj) => obj is Descriptor && Equals((Descriptor)obj);
public override bool Equals(object? obj) => obj is Descriptor descriptor && Equals(descriptor);

public override int GetHashCode() => GetFilterName().GetHashCode();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public static DotNetCliCommandResult Execute(DotNetCliCommand parameters)
}
}

internal static string GetDotNetSdkVersion()
internal static string? GetDotNetSdkVersion()
{
using (var process = new Process { StartInfo = BuildStartInfo(customDotNetCliPath: null, workingDirectory: string.Empty, arguments: "--version") })
using (new ConsoleExitHandler(process, NullLogger.Instance))
Expand Down Expand Up @@ -98,7 +98,7 @@ internal static void LogEnvVars(DotNetCliCommand command)
}
}

internal static ProcessStartInfo BuildStartInfo(string customDotNetCliPath, string workingDirectory, string arguments,
internal static ProcessStartInfo BuildStartInfo(string? customDotNetCliPath, string workingDirectory, string arguments,
IReadOnlyList<EnvironmentVariable>? environmentVariables = null, bool redirectStandardInput = false, bool redirectStandardError = true, bool redirectStandardOutput = true)
{
const string dotnetMultiLevelLookupEnvVarName = "DOTNET_MULTILEVEL_LOOKUP";
Expand Down
11 changes: 7 additions & 4 deletions src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,21 @@ namespace BenchmarkDotNet.Toolchains.DotNetCli
{
public class DotNetCliPublisher : IBuilder
{
public DotNetCliPublisher(string? customDotNetCliPath = null, string? extraArguments = null, IReadOnlyList<EnvironmentVariable> environmentVariables = null)
public DotNetCliPublisher(
string? customDotNetCliPath = null,
string? extraArguments = null,
IReadOnlyList<EnvironmentVariable>? environmentVariables = null)
{
CustomDotNetCliPath = customDotNetCliPath;
ExtraArguments = extraArguments;
EnvironmentVariables = environmentVariables;
}

private string CustomDotNetCliPath { get; }
private string? CustomDotNetCliPath { get; }

private string ExtraArguments { get; }
private string? ExtraArguments { get; }

private IReadOnlyList<EnvironmentVariable> EnvironmentVariables { get; }
private IReadOnlyList<EnvironmentVariable>? EnvironmentVariables { get; }

public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger)
=> new DotNetCliCommand(
Expand Down
12 changes: 6 additions & 6 deletions src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public class NetCoreAppSettings
[PublicAPI]
public NetCoreAppSettings(
string targetFrameworkMoniker,
string runtimeFrameworkVersion,
string? runtimeFrameworkVersion,
string name,
string? customDotNetCliPath = null,
string? packagesPath = null,
Expand All @@ -68,29 +68,29 @@ public class NetCoreAppSettings
/// </summary>
public string TargetFrameworkMoniker { get; }

public string RuntimeFrameworkVersion { get; }
public string? RuntimeFrameworkVersion { get; }

/// <summary>
/// display name used for showing the results
/// </summary>
public string Name { get; }

public string CustomDotNetCliPath { get; }
public string? CustomDotNetCliPath { get; }

/// <summary>
/// The directory to restore packages to.
/// </summary>
public string PackagesPath { get; }
public string? PackagesPath { get; }

/// <summary>
/// Path to a custom runtime pack.
/// </summary>
public string CustomRuntimePack { get; }
public string? CustomRuntimePack { get; }

/// <summary>
/// Path to the Mono AOT Compiler
/// </summary>
public string AOTCompilerPath { get; }
public string? AOTCompilerPath { get; }

/// <summary>
/// Mono AOT Compiler mode, either 'mini' or 'llvm'
Expand Down
6 changes: 3 additions & 3 deletions src/BenchmarkDotNet/Validators/ParamsValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,19 @@ private IEnumerable<ValidationError> Validate(Type type)
BindingFlags.FlattenHierarchy;
foreach (var memberInfo in type.GetMembers(reflectionFlags))
{
var attributes = new Attribute[]
var attributes = new Attribute?[]
{
memberInfo.ResolveAttribute<ParamsAttribute>(),
memberInfo.ResolveAttribute<ParamsAllValuesAttribute>(),
memberInfo.ResolveAttribute<ParamsSourceAttribute>()
}
.Where(attribute => attribute != null)
.WhereNotNull()
.ToList();
if (attributes.IsEmpty())
continue;

string name = $"{type.Name}.{memberInfo.Name}";
string? attributeString = string.Join(", ", attributes.Select(attribute => $"[{attribute.GetType().Name.Replace(nameof(Attribute), "")}]"));
string attributeString = string.Join(", ", attributes.Select(attribute => $"[{attribute.GetType().Name.Replace(nameof(Attribute), "")}]"));

if (attributes.Count > 1)
yield return new ValidationError(TreatsWarningsAsErrors,
Expand Down
8 changes: 4 additions & 4 deletions src/BenchmarkDotNet/Validators/ValidationError.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ public ValidationError(bool isCritical, string message, BenchmarkCase? benchmark

[PublicAPI] public bool IsCritical { get; }
[PublicAPI] public string Message { get; }
[PublicAPI] public BenchmarkCase BenchmarkCase { get; }
[PublicAPI] public BenchmarkCase? BenchmarkCase { get; }

public override string ToString() => Message;

public bool Equals(ValidationError other)
public bool Equals(ValidationError? other)
{
if (ReferenceEquals(null, other))
return false;
Expand All @@ -28,13 +28,13 @@ public bool Equals(ValidationError other)
return IsCritical == other.IsCritical && string.Equals(Message, other.Message) && Equals(BenchmarkCase, other.BenchmarkCase);
}

public override bool Equals(object obj)
public override bool Equals(object? obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != this.GetType())
if (obj.GetType() != GetType())
return false;
return Equals((ValidationError)obj);
}
Expand Down
Loading

0 comments on commit b4ac9df

Please sign in to comment.