Skip to content

Commit

Permalink
Fixed warnings on null assignments
Browse files Browse the repository at this point in the history
  • Loading branch information
alinasmirnova authored and AndreyAkinshin committed Oct 3, 2023
1 parent 7fbbc9f commit 9d7350c
Show file tree
Hide file tree
Showing 24 changed files with 39 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class InliningDiagnoser : JitDiagnoser<object>, 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ private IEnumerable<Metric> 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<Address, Dictionary<Address, long>>();
Dictionary<Address, long> lastHeapAllocs = null;
Dictionary<Address, long>? lastHeapAllocs = null;

Address lastHeapHandle = 0;

Expand Down
4 changes: 2 additions & 2 deletions src/BenchmarkDotNet.Disassembler.x64/SourceCodeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Characteristics/Characteristic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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); }
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Disassemblers/MonoDisassembler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ private static DisassemblyResult CreateErrorResult(IReadOnlyList<string?> input,
//line example 2: 0000000000000000 subq $0x28, %rsp
private static readonly Regex InstructionRegex = new Regex(@"\s*(?<address>[0-9a-f]+)(\:\s+([0-9a-f]{2}\s+)+)?\s+(?<instruction>.*)\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);
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Disassemblers/SourceCodeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Engines/AnonymousPipesHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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++)
{
Expand Down
4 changes: 2 additions & 2 deletions src/BenchmarkDotNet/Engines/Consumer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ private static readonly HashSet<Type> 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
Expand Down Expand Up @@ -157,7 +157,7 @@ public void Consume<T>(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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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, string>();
string currentMicroarchitecture = null;
string? currentMicroarchitecture = null;
foreach (string line in data)
{
if (line.StartsWith("//") || string.IsNullOrWhiteSpace(line))
Expand Down
8 changes: 4 additions & 4 deletions src/BenchmarkDotNet/Environments/Runtimes/CoreRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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.*
Expand Down Expand Up @@ -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))
{
Expand All @@ -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))
{
Expand Down Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Exporters/Xml/XmlSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
3 changes: 1 addition & 2 deletions src/BenchmarkDotNet/Loggers/Broker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Loggers/LinqPadLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public sealed class LinqPadLogger : ILogger
public static readonly Lazy<LinqPadLogger> lazyInstance = new Lazy<LinqPadLogger>(() =>
{
// 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
Expand Down
6 changes: 3 additions & 3 deletions src/BenchmarkDotNet/Toolchains/CsProj/CsProjGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 "<Import Sdk="
// we don't allow for that mostly to prevent from edge cases like the following
// <Import Sdk="Microsoft.NET.Sdk.WindowsDesktop" Project="Sdk.props" Condition="'$(TargetFramework)'=='netcoreapp3.0'"/>
string sdkName = null;
string? sdkName = null;
if (TargetFrameworkMoniker.StartsWith("netcoreapp", StringComparison.InvariantCultureIgnoreCase))
{
foreach (XmlElement importElement in projectElement.GetElementsByTagName("Import"))
Expand Down Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,7 @@ private void DefineFields()

Type argLocalsType;
Type argFieldType;
MethodInfo opConversion = null;
MethodInfo? opConversion = null;
if (parameterType.IsByRef)
{
argLocalsType = parameterType;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Toolchains/Toolchain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public virtual IEnumerable<ValidationError> 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;

Expand Down
2 changes: 1 addition & 1 deletion src/BenchmarkDotNet/Validators/ExecutionValidatorBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public IEnumerable<ValidationError> Validate(ValidationParameters validationPara
return errors;
}

private bool TryCreateBenchmarkTypeInstance(Type type, List<ValidationError> errors, out object instance)
private bool TryCreateBenchmarkTypeInstance(Type type, List<ValidationError> errors, out object? instance)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions tests/BenchmarkDotNet.IntegrationTests/ExporterIOTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void ExporterUsesFullyQualifiedTypeNameAsFileName()
var exporter = new MockExporter();
var mockSummary = GetMockSummary(resultsDirectoryPath, config: null, typeof(Generic<int>));
var expectedFilePath = $"{Path.Combine(mockSummary.ResultsDirectoryPath, "BenchmarkDotNet.IntegrationTests.Generic_Int32_")}-report.txt";
string actualFilePath = null;
string? actualFilePath = null;

try
{
Expand All @@ -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
{
Expand Down
2 changes: 1 addition & 1 deletion tests/BenchmarkDotNet.IntegrationTests/InProcessTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ private void TestInvoke<T>(Expression<Func<BenchmarkAllCases, T>> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
{
Expand Down

0 comments on commit 9d7350c

Please sign in to comment.