From 389ac27c9b62eac3ed6a220e5837dcf562a43f37 Mon Sep 17 00:00:00 2001 From: Rolf Bjarne Kvinge Date: Thu, 26 Mar 2026 13:23:02 +0100 Subject: [PATCH] [tests] Stop disabling nullability. And fix any resulting issues. --- tests/common/AppDelegate.cs | 11 ++- tests/common/Configuration.cs | 71 +++++++++--------- tests/common/ConfigurationNUnit.cs | 2 +- tests/common/ExecutionHelper.cs | 28 +++---- tests/common/GlobalUsings.cs | 1 + tests/common/PlatformInfo.cs | 23 +++--- tests/dotnet/UnitTests/ExtensionsTest.cs | 2 +- tests/generator/BGenTool.cs | 4 +- tests/introspection/ApiBaseTest.cs | 29 ++++---- tests/introspection/ApiCMAttachmentTest.cs | 67 ++++++++--------- tests/introspection/ApiClassPtrTest.cs | 15 ++-- .../introspection/ApiCoreImageFiltersTest.cs | 32 ++++---- tests/introspection/ApiCtorInitTest.cs | 27 ++++--- tests/introspection/ApiFieldTest.cs | 21 +++--- tests/introspection/ApiFrameworkTest.cs | 5 +- tests/introspection/ApiPInvokeTest.cs | 25 +++---- tests/introspection/ApiSelectorTest.cs | 19 +++-- tests/introspection/ApiSignatureTest.cs | 73 +++++++++---------- tests/introspection/ApiTypeTest.cs | 5 +- tests/introspection/ApiTypoTest.cs | 20 +++-- tests/introspection/ApiWeakPropertyTest.cs | 28 ++++--- tests/introspection/CoreSelectorTest.cs | 9 +-- tests/introspection/MacApiPInvokeTest.cs | 2 +- tests/introspection/iOSApiFieldTest.cs | 5 +- tests/introspection/iOSApiSelectorTest.cs | 5 +- tests/introspection/iOSApiSignatureTest.cs | 11 ++- tests/introspection/iOSApiWeakPropertyTest.cs | 5 +- .../BaseGeneratorTestClass.cs | 2 +- .../BaseTransformerTestClass.cs | 2 +- 29 files changed, 260 insertions(+), 289 deletions(-) diff --git a/tests/common/AppDelegate.cs b/tests/common/AppDelegate.cs index cb322e2e2b75..cac8bcae5512 100644 --- a/tests/common/AppDelegate.cs +++ b/tests/common/AppDelegate.cs @@ -7,18 +7,17 @@ using MonoTouch.NUnit.UI; using NUnit.Framework.Internal; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable [Register ("AppDelegate")] public partial class AppDelegate : UIApplicationDelegate { - static internal UIWindow MainWindow; - public static TouchRunner Runner { get; set; } + static internal UIWindow? MainWindow; + public static TouchRunner? Runner { get; set; } partial void PostFinishedLaunching (); - public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) + public override bool FinishedLaunching (UIApplication application, NSDictionary? launchOptions) { #if __MACCATALYST__ || __MACOS__ TestRuntime.NotifyLaunchCompleted (); @@ -61,7 +60,7 @@ public override UISceneConfiguration GetConfiguration (UIApplication application public partial class SceneDelegate : UIResponder, IUIWindowSceneDelegate { [Export ("window")] - public UIWindow Window { get; set; } + public UIWindow? Window { get; set; } [Export ("scene:willConnectToSession:options:")] public void WillConnect (UIScene scene, UISceneSession session, UISceneConnectionOptions connectionOptions) diff --git a/tests/common/Configuration.cs b/tests/common/Configuration.cs index e4313eb46264..a354183c20af 100644 --- a/tests/common/Configuration.cs +++ b/tests/common/Configuration.cs @@ -6,23 +6,23 @@ using System.Threading; using Xamarin.Utils; -#nullable disable // until we get around to fixing this file +#nullable enable namespace Xamarin.Tests { static partial class Configuration { public const string XI_ProductName = "MonoTouch"; public const string XM_ProductName = "Xamarin.Mac"; - public static string DotNetBclDir; - public static string DotNetCscCommand; + public static string? DotNetBclDir; + public static string? DotNetCscCommand; public static string DotNetExecutable; public static string DotNetTfm; - public static string mt_src_root; + public static string? mt_src_root; public static string sdk_version; public static string tvos_sdk_version; public static string macos_sdk_version; public static string xcode_root; - public static string XcodeVersionString; + public static string? XcodeVersionString; public static string xcode83_root; public static string xcode94_root; #if MONOMAC @@ -37,12 +37,12 @@ static partial class Configuration { public static bool XcodeIsStable; public static string DOTNET_DIR; - static Version xcode_version; + static Version? xcode_version; public static Version XcodeVersion { get { if (xcode_version is null) - xcode_version = Version.Parse (XcodeVersionString); + xcode_version = Version.Parse (XcodeVersionString!); return xcode_version; } } @@ -101,11 +101,11 @@ public static string XcodeLocation { } // This is the location of an Xcode which is older than the recommended one. - public static string GetOldXcodeRoot (Version min_version = null) + public static string? GetOldXcodeRoot (Version? min_version = null) { var with_versions = new List> (); - var max_version = Version.Parse (XcodeVersionString); + var max_version = Version.Parse (XcodeVersionString!); foreach (var xcode in GetAllXcodes ()) { var path = xcode.Path; var version = xcode.Version; @@ -153,8 +153,8 @@ static void ParseConfigFiles () if (!test_config.Any () && Environment.OSVersion.Platform != PlatformID.Win32NT) { // Run 'make test.config' in the tests/ directory // First find the tests/ directory - var dir = TestAssemblyDirectory; - string tests_dir = null; + var dir = TestAssemblyDirectory!; + string? tests_dir = null; while (dir.Length > 1) { var file = Path.Combine (dir, "tests"); if (Directory.Exists (file)) { @@ -162,7 +162,7 @@ static void ParseConfigFiles () break; } - dir = Path.GetDirectoryName (dir); + dir = Path.GetDirectoryName (dir)!; } if (tests_dir is null) @@ -202,7 +202,8 @@ static void ParseConfigFile (string file) } } - internal static string GetVariable (string variable, string @default) + [return: NotNullIfNotNull (nameof (@default))] + internal static string? GetVariable (string variable, string? @default) { var result = Environment.GetEnvironmentVariable (variable); if (string.IsNullOrEmpty (result)) @@ -239,7 +240,7 @@ public static string EvaluateVariable (string variable) return result.Substring (variable.Length + 1); } - static string GetXcodeVersion (string xcode_path) + static string? GetXcodeVersion (string xcode_path) { var version_plist = Path.Combine (xcode_path, "..", "version.plist"); if (!File.Exists (version_plist)) @@ -248,7 +249,7 @@ static string GetXcodeVersion (string xcode_path) return GetPListStringValue (version_plist, "CFBundleShortVersionString"); } - public static string GetPListStringValue (string plist, string key) + public static string? GetPListStringValue (string plist, string key) { var settings = new System.Xml.XmlReaderSettings (); settings.DtdProcessing = System.Xml.DtdProcessing.Ignore; @@ -256,15 +257,15 @@ public static string GetPListStringValue (string plist, string key) using (var fs = new StringReader (ReadPListAsXml (plist))) { using (var reader = System.Xml.XmlReader.Create (fs, settings)) { doc.Load (reader); - return doc.DocumentElement - .SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()").Value; + return doc.DocumentElement! + .SelectSingleNode ($"//dict/key[text()='{key}']/following-sibling::string[1]/text()")!.Value; } } } public static string ReadPListAsXml (string path) { - string tmpfile = null; + string? tmpfile = null; try { tmpfile = Path.GetTempFileName (); File.Copy (path, tmpfile, true); @@ -297,8 +298,8 @@ static Configuration () include_maccatalyst = !string.IsNullOrEmpty (GetVariable ("INCLUDE_MACCATALYST", "")); DotNetBclDir = GetVariable ("DOTNET_BCL_DIR", null); DotNetCscCommand = GetVariable ("DOTNET_CSC_COMMAND", null)?.Trim ('\''); - DotNetExecutable = GetVariable ("DOTNET", null); - DotNetTfm = GetVariable ("DOTNET_TFM", null); + DotNetExecutable = GetVariable ("DOTNET", ""); + DotNetTfm = GetVariable ("DOTNET_TFM", ""); XcodeIsStable = string.Equals (GetVariable ("XCODE_IS_STABLE", ""), "true", StringComparison.OrdinalIgnoreCase); DOTNET_DIR = GetVariable ("DOTNET_DIR", ""); @@ -359,7 +360,7 @@ public static string RootPath { } } - public static bool TryGetRootPath (out string rootPath) + public static bool TryGetRootPath ([NotNullWhen (true)] out string? rootPath) { try { rootPath = RootPath; @@ -643,7 +644,7 @@ public static string CloneTestDirectory (string directory) foreach (var file in files) { var src = Path.Combine (directory, file); var tgt = Path.Combine (testsTemporaryDirectory, file); - var tgtDir = Path.GetDirectoryName (tgt); + var tgtDir = Path.GetDirectoryName (tgt)!; Directory.CreateDirectory (tgtDir); File.Copy (src, tgt); if (tgt.EndsWith (".csproj", StringComparison.OrdinalIgnoreCase)) { @@ -681,19 +682,19 @@ public static void FixupTestFiles (string directory, string mode) } } - public static Dictionary GetBuildEnvironment (ApplePlatform platform) + public static Dictionary GetBuildEnvironment (ApplePlatform platform) { - var environment = new Dictionary (); + var environment = new Dictionary (); SetBuildVariables (platform, ref environment); return environment; } - public static void SetBuildVariables (ApplePlatform platform, ref Dictionary environment) + public static void SetBuildVariables (ApplePlatform platform, ref Dictionary environment) { if (environment is null) - environment = new Dictionary (); + environment = new Dictionary (); - environment ["MD_APPLE_SDK_ROOT"] = Path.GetDirectoryName (Path.GetDirectoryName (xcode_root)); + environment ["MD_APPLE_SDK_ROOT"] = Path.GetDirectoryName (Path.GetDirectoryName (xcode_root)!)!; // This is set by `dotnet test` and can cause building legacy projects to fail to build with: // Microsoft.NET.Build.Extensions.ConflictResolution.targets(30,5): @@ -713,13 +714,13 @@ public static string GetTestLibraryDirectory (ApplePlatform platform, bool? simu switch (platform) { case ApplePlatform.iOS: - dir = simulator.Value ? "iphonesimulator" : "iphoneos"; + dir = simulator == true ? "iphonesimulator" : "iphoneos"; break; case ApplePlatform.MacOSX: dir = "macos"; break; case ApplePlatform.TVOS: - dir = simulator.Value ? "tvsimulator" : "tvos"; + dir = simulator == true ? "tvsimulator" : "tvos"; break; case ApplePlatform.MacCatalyst: dir = "maccatalyst"; @@ -751,7 +752,7 @@ static bool IsAPFS { } else { var exit_code = ExecutionHelper.Execute ("/bin/df", new string [] { "-t", "apfs", "/" }, out var output, TimeSpan.FromSeconds (10)); - is_apfs = exit_code == 0 && output.Trim ().Split ('\n').Length >= 2; + is_apfs = exit_code == 0 && output!.Trim ().Split ('\n').Length >= 2; } } @@ -790,7 +791,7 @@ public static bool CanRunArm64 { [DllImport ("libc")] static extern int sysctlbyname (string name, ref int value, ref IntPtr size, IntPtr zero, IntPtr zeroAgain); - public static IEnumerable CallNM (string file, string nmArguments, string arch = null) + public static IEnumerable CallNM (string file, string nmArguments, string? arch = null) { var arguments = new List (new [] { nmArguments, file }); if (!string.IsNullOrEmpty (arch)) { @@ -809,12 +810,12 @@ public static IEnumerable CallNM (string file, string nmArguments, strin }); } - public static IEnumerable GetNativeSymbols (string file, string arch = null) + public static IEnumerable GetNativeSymbols (string file, string? arch = null) { return CallNM (file, "-gUjA", arch); } - public static IEnumerable GetUndefinedNativeSymbols (string file, string arch = null) + public static IEnumerable GetUndefinedNativeSymbols (string file, string? arch = null) { return CallNM (file, "-gujA", arch); } @@ -829,7 +830,7 @@ public static bool IsStableRelease { } public static bool TryGetApiDefinitionRsp (TargetFramework framework, - [NotNullWhen (true)] out string rspPath) + [NotNullWhen (true)] out string? rspPath) { rspPath = null; var platform = framework.Platform switch { @@ -846,7 +847,7 @@ public static bool TryGetApiDefinitionRsp (TargetFramework framework, } public static bool TryGetPlatformPreprocessorSymbolsRsp (TargetFramework framework, - [NotNullWhen (true)] out string rspPath) + [NotNullWhen (true)] out string? rspPath) { rspPath = null; var platform = framework.Platform switch { diff --git a/tests/common/ConfigurationNUnit.cs b/tests/common/ConfigurationNUnit.cs index 43a82b38bb15..b351d3b6cf80 100644 --- a/tests/common/ConfigurationNUnit.cs +++ b/tests/common/ConfigurationNUnit.cs @@ -6,7 +6,7 @@ using Xamarin.Utils; -#nullable disable // until we get around to fixing this file +#nullable enable namespace Xamarin.Tests { static partial class Configuration { diff --git a/tests/common/ExecutionHelper.cs b/tests/common/ExecutionHelper.cs index 16165517404a..29b260904da7 100644 --- a/tests/common/ExecutionHelper.cs +++ b/tests/common/ExecutionHelper.cs @@ -2,7 +2,7 @@ using System.Text; using Xamarin.Utils; -#nullable disable // until we get around to fixing this file +#nullable enable namespace Xamarin.Tests { class XBuild { @@ -12,17 +12,17 @@ public static string ToolPath { } } - public static string BuildXM (string project, string configuration = "Debug", string platform = "x86", string verbosity = null, TimeSpan? timeout = null, string [] arguments = null, string targets = "Clean,Build") + public static string BuildXM (string project, string configuration = "Debug", string platform = "x86", string? verbosity = null, TimeSpan? timeout = null, string []? arguments = null, string targets = "Clean,Build") { return Build (project, ApplePlatform.MacOSX, configuration, platform, verbosity, timeout, arguments, targets); } - public static string BuildXI (string project, string configuration = "Debug", string platform = "iPhoneSimulator", string verbosity = null, TimeSpan? timeout = null, string [] arguments = null, string targets = "Clean,Build") + public static string BuildXI (string project, string configuration = "Debug", string platform = "iPhoneSimulator", string? verbosity = null, TimeSpan? timeout = null, string []? arguments = null, string targets = "Clean,Build") { return Build (project, ApplePlatform.iOS, configuration, platform, verbosity, timeout, arguments, targets); } - static string Build (string project, ApplePlatform applePlatform, string configuration = "Debug", string platform = "iPhoneSimulator", string verbosity = null, TimeSpan? timeout = null, string [] arguments = null, string targets = "Clean,Build") + static string Build (string project, ApplePlatform applePlatform, string configuration = "Debug", string platform = "iPhoneSimulator", string? verbosity = null, TimeSpan? timeout = null, string []? arguments = null, string targets = "Clean,Build") { return ExecutionHelper.Execute (ToolPath, new string [] { @@ -50,7 +50,7 @@ public static int Execute (string fileName, IList arguments, TimeSpan? t return Execute (fileName, arguments, null, null, null, timeout); } - public static int Execute (string fileName, IList arguments, string working_directory = null, Action stdout_callback = null, Action stderr_callback = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, string? working_directory = null, Action? stdout_callback = null, Action? stderr_callback = null, TimeSpan? timeout = null) { return Execute (fileName, arguments, timed_out: out var _, workingDirectory: working_directory, stdout_callback: stdout_callback, stderr_callback: stderr_callback, timeout: timeout); } @@ -60,19 +60,19 @@ public static int Execute (string fileName, IList arguments, out StringB return Execute (fileName, arguments, out output, null, null); } - public static int Execute (string fileName, IList arguments, out StringBuilder output, string working_directory, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out StringBuilder output, string? working_directory, TimeSpan? timeout = null) { output = new StringBuilder (); return Execute (fileName, arguments, out var _, workingDirectory: working_directory, stdout: output, stderr: output, timeout: timeout); } - public static int Execute (string fileName, IList arguments, out StringBuilder output, string working_directory, Dictionary environment_variables, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out StringBuilder output, string? working_directory, Dictionary? environment_variables, TimeSpan? timeout = null) { output = new StringBuilder (); return Execute (fileName, arguments, out var _, workingDirectory: working_directory, stdout: output, stderr: output, timeout: timeout, environment_variables: environment_variables); } - public static int Execute (string fileName, IList arguments, out bool timed_out, string workingDirectory = null, Dictionary environment_variables = null, StringBuilder stdout = null, StringBuilder stderr = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out bool timed_out, string? workingDirectory = null, Dictionary? environment_variables = null, StringBuilder? stdout = null, StringBuilder? stderr = null, TimeSpan? timeout = null) { var rv = Execution.RunAsync (fileName, arguments, workingDirectory: workingDirectory, environment: environment_variables, timeout: timeout).Result; if (stdout is not null) @@ -81,11 +81,11 @@ public static int Execute (string fileName, IList arguments, out bool ti stderr.Append (rv.Output.StandardError); timed_out = rv.TimedOut; if (rv.TimedOut) - Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout.Value.TotalMilliseconds} ms, and was killed.", timeout.Value.TotalMinutes); + Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout!.Value.TotalMilliseconds} ms, and was killed.", timeout!.Value.TotalMinutes); return rv.ExitCode; } - public static int Execute (string fileName, IList arguments, out bool timed_out, string workingDirectory = null, Dictionary environment_variables = null, Action stdout_callback = null, Action stderr_callback = null, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out bool timed_out, string? workingDirectory = null, Dictionary? environment_variables = null, Action? stdout_callback = null, Action? stderr_callback = null, TimeSpan? timeout = null) { if (stdout_callback is null) stdout_callback = Console.WriteLine; @@ -95,11 +95,11 @@ public static int Execute (string fileName, IList arguments, out bool ti var rv = Execution.RunWithCallbacksAsync (fileName, arguments, workingDirectory: workingDirectory, environment: environment_variables, standardOutput: stdout_callback, standardError: stderr_callback, timeout: timeout).Result; timed_out = rv.TimedOut; if (rv.TimedOut) - Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout.Value.TotalMilliseconds} ms, and was killed.", timeout.Value.TotalMinutes); + Console.WriteLine ($"Command '{fileName} {StringUtils.FormatArguments (arguments)}' didn't finish in {timeout!.Value.TotalMilliseconds} ms, and was killed.", timeout!.Value.TotalMinutes); return rv.ExitCode; } - public static int Execute (string fileName, IList arguments, out string output, TimeSpan? timeout = null) + public static int Execute (string fileName, IList arguments, out string? output, TimeSpan? timeout = null) { var sb = new StringBuilder (); var rv = Execute (fileName, arguments, timed_out: out var _, stdout: sb, stderr: sb, timeout: timeout); @@ -107,12 +107,12 @@ public static int Execute (string fileName, IList arguments, out string return rv; } - public static int Execute (string fileName, IList arguments, Dictionary environmentVariables, StringBuilder stdout, StringBuilder stderr, TimeSpan? timeout = null, string workingDirectory = null) + public static int Execute (string fileName, IList arguments, Dictionary? environmentVariables, StringBuilder? stdout, StringBuilder? stderr, TimeSpan? timeout = null, string? workingDirectory = null) { return Execute (fileName, arguments, timed_out: out var _, workingDirectory: workingDirectory, environment_variables: environmentVariables, stdout: stdout, stderr: stderr, timeout: timeout); } - public static string Execute (string fileName, IList arguments, bool throwOnError = true, Dictionary environmentVariables = null, bool hide_output = false, TimeSpan? timeout = null) + public static string Execute (string fileName, IList arguments, bool throwOnError = true, Dictionary? environmentVariables = null, bool hide_output = false, TimeSpan? timeout = null) { var rv = Execution.RunAsync (fileName, arguments, environment: environmentVariables, timeout: timeout).Result; var output = rv.Output.MergedOutput; diff --git a/tests/common/GlobalUsings.cs b/tests/common/GlobalUsings.cs index 9f7637a0e6f9..bb2e71447ba4 100644 --- a/tests/common/GlobalUsings.cs +++ b/tests/common/GlobalUsings.cs @@ -3,6 +3,7 @@ global using System; global using System.Collections.Generic; +global using System.Diagnostics.CodeAnalysis; global using System.Runtime.InteropServices; global using CoreFoundation; diff --git a/tests/common/PlatformInfo.cs b/tests/common/PlatformInfo.cs index f88e7abd8b46..11f7cacc582a 100644 --- a/tests/common/PlatformInfo.cs +++ b/tests/common/PlatformInfo.cs @@ -18,14 +18,13 @@ using Xamarin.Utils; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Xamarin.Tests { public sealed class PlatformInfo { static PlatformInfo GetHostPlatformInfo () { - string name; + string? name; string version; #if __MACCATALYST__ name = "MacCatalyst"; @@ -35,8 +34,8 @@ static PlatformInfo GetHostPlatformInfo () version = UIDevice.CurrentDevice.SystemVersion; #elif MONOMAC || __MACOS__ using (var plist = NSDictionary.FromFile ("/System/Library/CoreServices/SystemVersion.plist")) { - name = (NSString) plist ["ProductName"]; - version = (NSString) plist ["ProductVersion"]; + name = (NSString) plist ["ProductName"]!; + version = (NSString) plist ["ProductVersion"]!; } #else #error Unknown platform @@ -58,21 +57,21 @@ static PlatformInfo GetHostPlatformInfo () else throw new FormatException ($"Unknown product name: {name}"); - platformInfo.Version = Version.Parse (version); + platformInfo.Version = Version.Parse (version)!; return platformInfo; } #if __MACCATALYST__ - static string _iOSSupportVersion; + static string? _iOSSupportVersion; internal static string iOSSupportVersion { get { if (_iOSSupportVersion is null) { // This is how Apple does it: https://github.com/llvm/llvm-project/blob/62ec4ac90738a5f2d209ed28c822223e58aaaeb7/lldb/source/Host/macosx/objcxx/HostInfoMacOSX.mm#L100-L105 using var dict = NSMutableDictionary.FromFile ("/System/Library/CoreServices/SystemVersion.plist"); using var str = (NSString) "iOSSupportVersion"; - using var obj = dict.ObjectForKey (str); - _iOSSupportVersion = obj.ToString (); + using var obj = dict.ObjectForKey (str)!; + _iOSSupportVersion = obj.ToString ()!; } return _iOSSupportVersion; } @@ -82,7 +81,7 @@ internal static string iOSSupportVersion { public static readonly PlatformInfo Host = GetHostPlatformInfo (); public ApplePlatform Name { get; private set; } - public Version Version { get; private set; } + public Version? Version { get; private set; } public bool IsMac => Name == ApplePlatform.MacOSX; public bool IsIos => Name == ApplePlatform.iOS; @@ -117,7 +116,7 @@ public static bool IsAvailableOnHostPlatform (this IEnumerable ParseAttributes (IEnumerable attributes) + static IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version? Version)> ParseAttributes (IEnumerable attributes) { foreach (var attr in attributes) { if (!attr.TryParse (out ApplePlatform? platform, out var version)) @@ -153,7 +152,7 @@ public static bool IsAvailable (this IEnumerable attributes } [UnconditionalSuppressMessage ("Trimming", "IL2045", Justification = "Some of the attributes this method uses may have been linked away, so things might not work. It actually works though, so unless something changes, we're going to assume it's trimmer-compatible.")] - public static bool? IsAvailable (IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version Version)> attributes, PlatformInfo targetPlatform, ApplePlatform attributePlatform) + public static bool? IsAvailable (IEnumerable<(OSPlatformAttribute Attribute, ApplePlatform Platform, Version? Version)> attributes, PlatformInfo targetPlatform, ApplePlatform attributePlatform) { // First we check for any unsupported attributes, and only once we know that there aren't any unsupported // attributes, we check for supported attributes. Otherwise we might determine that an API is available diff --git a/tests/dotnet/UnitTests/ExtensionsTest.cs b/tests/dotnet/UnitTests/ExtensionsTest.cs index cc2e89e0328c..cf50e2098e90 100644 --- a/tests/dotnet/UnitTests/ExtensionsTest.cs +++ b/tests/dotnet/UnitTests/ExtensionsTest.cs @@ -27,7 +27,7 @@ public void AdditionalAppExtensionTest (ApplePlatform platform, string runtimeId "-target", "NativeIntentsExtension", "-project", Path.Combine (xcodeProjectFolder, "NativeContainer.xcodeproj"), }; - var env = new Dictionary { + var env = new Dictionary { { "DEVELOPER_DIR", Configuration.XcodeLocation }, }; foreach (var action in new string [] { "clean", "build" }) diff --git a/tests/generator/BGenTool.cs b/tests/generator/BGenTool.cs index 43a5e9ad474b..df2fb80dee68 100644 --- a/tests/generator/BGenTool.cs +++ b/tests/generator/BGenTool.cs @@ -95,7 +95,7 @@ string [] BuildArgumentArray () targetFramework = GetTargetFramework (Profile); if (CompileCommand is null) { - if (!StringUtils.TryParseArguments (Configuration.DotNetCscCommand, out var args, out var ex)) + if (!StringUtils.TryParseArguments (Configuration.DotNetCscCommand!, out var args, out var ex)) throw new InvalidOperationException ($"Unable to parse the .NET csc command '{Configuration.DotNetCscCommand}': {ex.Message}"); CompileCommand = new List (args); @@ -145,7 +145,7 @@ string [] BuildArgumentArray () if (tf is null) { // do nothing } else { - References.AddRange (Directory.GetFiles (Configuration.DotNetBclDir, "*.dll")); + References.AddRange (Directory.GetFiles (Configuration.DotNetBclDir!, "*.dll")); } } diff --git a/tests/introspection/ApiBaseTest.cs b/tests/introspection/ApiBaseTest.cs index bcecf9aec5a0..ab62b8b2ebc9 100644 --- a/tests/introspection/ApiBaseTest.cs +++ b/tests/introspection/ApiBaseTest.cs @@ -32,8 +32,7 @@ using UIKit; #endif -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -43,7 +42,7 @@ public abstract class ApiBaseTest { [DllImport ("/usr/lib/libobjc.dylib", EntryPoint = "objc_msgSend")] protected static extern IntPtr IntPtr_objc_msgSend (IntPtr receiver, IntPtr selector); - private LatchedEnvironmentVariable continueOnFailure = new LatchedEnvironmentVariable ("API_TEST_CONTINUE_ON_FAILURE"); + LatchedEnvironmentVariable continueOnFailure = new LatchedEnvironmentVariable ("API_TEST_CONTINUE_ON_FAILURE"); StringBuilder error_output = new StringBuilder (); @@ -62,7 +61,7 @@ protected void AddErrorLine (string line) Errors++; } - protected void AddErrorLine (string format, params object [] parameters) + protected void AddErrorLine (string format, params object? [] parameters) { AddErrorLine (string.Format (format, parameters)); } @@ -79,7 +78,7 @@ public bool ContinueOnFailure { } - private LatchedEnvironmentVariable logProgress = new LatchedEnvironmentVariable ("API_TEST_LOG_PROGRESS"); + LatchedEnvironmentVariable logProgress = new LatchedEnvironmentVariable ("API_TEST_LOG_PROGRESS"); /// /// Gets or sets a value indicating whether this test fixture will log it's progress. @@ -92,7 +91,7 @@ public bool LogProgress { set { logProgress.Value = value; } } - StringBuilder error_data; + StringBuilder? error_data; protected StringBuilder ErrorData { get { return error_data ?? (error_data = new StringBuilder ()); @@ -103,12 +102,12 @@ protected TextWriter Writer { #if MONOMAC get { return Console.Out; } #else - get { return AppDelegate.Runner.Writer; } + get { return AppDelegate.Runner!.Writer; } #endif } protected int Errors; - protected void ReportError (string s, params object [] parameters) + protected void ReportError (string s, params object? [] parameters) { if (!ContinueOnFailure) Assert.Fail (s, parameters); @@ -120,7 +119,7 @@ protected void ReportError (string s, params object [] parameters) } } - protected void AssertIfErrors (string s, params object [] parameters) + protected void AssertIfErrors (string s, params object? [] parameters) { if (Errors == 0) return; @@ -145,7 +144,7 @@ protected bool SkipDueToInvisibleAndUnsupported (MemberInfo member) if (member is null) return false; - if (SkipDueToInvisibleAndUnsupported (member.DeclaringType)) + if (SkipDueToInvisibleAndUnsupported (member.DeclaringType!)) return true; if (!MemberHasUnsupported (member)) @@ -160,7 +159,7 @@ protected virtual bool SkipDueToAttribute (MemberInfo member) return false; return !member.IsAvailableOnHostPlatform () || - SkipDueToAttribute (member.DeclaringType) || + SkipDueToAttribute (member.DeclaringType!) || SkipDueToAttributeInProperty (member); } @@ -180,7 +179,7 @@ protected bool SkipDueToAttributeInProperty (MemberInfo member) return false; // FIXME: In the future we could cache this to reduce memory requirements - var property = m.DeclaringType + var property = m.DeclaringType! .GetProperties (BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) .SingleOrDefault (p => p.GetGetMethod (true) == m || p.GetSetMethod (true) == m); return property is not null && SkipDueToAttribute (property); @@ -234,7 +233,7 @@ protected virtual Assembly Assembly { } const string libprefix = "/System/Library/Frameworks"; - static readonly string simprefix = Environment.GetEnvironmentVariable ("IPHONE_SIMULATOR_ROOT"); + static readonly string? simprefix = Environment.GetEnvironmentVariable ("IPHONE_SIMULATOR_ROOT"); protected virtual string FindLibrary (string libname, bool requiresFullPath = false) { @@ -253,7 +252,7 @@ protected virtual string FindLibrary (string libname, bool requiresFullPath = fa break; case "IOSurface": if (!TestRuntime.CheckXcodeVersion (9, 0)) - prefix = Path.Combine (Path.GetDirectoryName (prefix), "PrivateFrameworks"); + prefix = Path.Combine (Path.GetDirectoryName (prefix)!, "PrivateFrameworks"); break; case "PdfKit": libname = "PDFKit"; @@ -271,7 +270,7 @@ protected virtual string FindLibrary (string libname, bool requiresFullPath = fa libname = "PHASE"; break; default: - if (requiresFullPath && (Path.GetDirectoryName (libname).Length == 0)) + if (requiresFullPath && (Path.GetDirectoryName (libname)?.Length == 0)) ReportError ("[FAIL] Library '{0}' is specified without a path", libname); break; } diff --git a/tests/introspection/ApiCMAttachmentTest.cs b/tests/introspection/ApiCMAttachmentTest.cs index 4899c545fba7..f371f8743638 100644 --- a/tests/introspection/ApiCMAttachmentTest.cs +++ b/tests/introspection/ApiCMAttachmentTest.cs @@ -21,8 +21,7 @@ using GColorConversionInfoTriple = CoreGraphics.CGColorConversionInfoTriple; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -144,7 +143,7 @@ protected virtual bool Skip (Type type) return SkipNameSpace (type.Namespace) || Skip (type.Name) || SkipDueToAttribute (type); } - protected virtual bool SkipNameSpace (string nameSpace) + protected virtual bool SkipNameSpace (string? nameSpace) { switch (nameSpace) { case "Network": // none of the classes support it and they require a lot of setup to confirm it @@ -250,7 +249,7 @@ protected virtual bool Skip (string nativeName) } } - protected INativeObject GetINativeInstance (Type t) + protected INativeObject? GetINativeInstance (Type t) { var ctor = t.GetConstructor (Type.EmptyTypes); if ((ctor is not null) && !ctor.IsAbstract) @@ -265,7 +264,7 @@ protected INativeObject GetINativeInstance (Type t) return Runtime.GetINativeObject (new NSArray ().Handle, false); case "CFBundle": var bundles = CFBundle.GetAll (); - if (bundles.Length > 0) + if (bundles?.Length > 0) return bundles [0]; else throw new InvalidOperationException (string.Format ("Could not create the new instance for type {0}.", t.Name)); @@ -273,9 +272,7 @@ protected INativeObject GetINativeInstance (Type t) return CFNotificationCenter.Darwin; case "CFReadStream": case "CFStream": - CFReadStream readStream; - CFWriteStream writeStream; - CFStream.CreatePairWithSocketToHost ("www.google.com", 80, out readStream, out writeStream); + CFStream.CreatePairWithSocketToHost ("www.google.com", 80, out var readStream, out var writeStream); return readStream; case "CFWriteStream": CFStream.CreatePairWithSocketToHost ("www.google.com", 80, out readStream, out writeStream); @@ -288,7 +285,7 @@ protected INativeObject GetINativeInstance (Type t) return DispatchData.FromByteBuffer (new byte [] { 1, 2, 3, 4 }); case "AudioFile": var path = Path.GetFullPath ("1.caf"); - var af = AudioFile.Open (CFUrl.FromFile (path), AudioFilePermission.Read, AudioFileType.CAF); + var af = AudioFile.Open (CFUrl.FromFile (path)!, AudioFilePermission.Read, AudioFileType.CAF); return af; case "CFHTTPMessage": return CFHTTPMessage.CreateEmpty (false); @@ -296,7 +293,7 @@ protected INativeObject GetINativeInstance (Type t) return new CFMutableString ("xamarin"); case "CGBitmapContext": byte [] data = new byte [400]; - using (CGColorSpace space = CGColorSpace.CreateDeviceRGB ()) { + using (var space = CGColorSpace.CreateDeviceRGB ()) { return new CGBitmapContext (data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast); } case "CGContextPDF": @@ -305,13 +302,13 @@ protected INativeObject GetINativeInstance (Type t) return new CGContextPDF (url); case "CGColorConversionInfo": var cci = new GColorConversionInfoTriple () { - Space = CGColorSpace.CreateGenericRgb (), + Space = CGColorSpace.CreateGenericRgb ()!, Intent = CGColorRenderingIntent.Default, Transform = CGColorConversionInfoTransformType.ApplySpace }; - return new CGColorConversionInfo ((NSDictionary) null, cci, cci, cci); + return new CGColorConversionInfo ((NSDictionary?) null, cci, cci, cci); case "CGDataConsumer": - using (NSMutableData destData = new NSMutableData ()) { + using (var destData = new NSMutableData ()) { return new CGDataConsumer (destData); } case "CGDataProvider": @@ -334,7 +331,7 @@ protected INativeObject GetINativeInstance (Type t) case "CMBufferQueue": return CMBufferQueue.CreateUnsorted (2); case "CTFont": - CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes () { + var fda = new CTFontDescriptorAttributes () { FamilyName = "Courier", StyleName = "Bold", Size = 16.0f @@ -361,7 +358,7 @@ protected INativeObject GetINativeInstance (Type t) Font = new CTFont ("ArialMT", 24) })); var bPath = UIBezierPath.FromRect (new RectangleF (0, 0, 3, 3)); - return framesetter.GetFrame (new NSRange (0, 0), bPath.CGPath, null); + return framesetter.GetFrame (new NSRange (0, 0), bPath.CGPath!, null); case "CTFramesetter": return new CTFramesetter (new NSAttributedString ("Hello, world", new CTStringAttributes () { @@ -378,7 +375,7 @@ protected INativeObject GetINativeInstance (Type t) })); #if __MACCATALYST__ || __MACOS__ case "CGEvent": - return new CGEvent ((CGEventSource) null); + return new CGEvent ((CGEventSource?) null); case "CGEventSource": return new CGEventSource (CGEventSourceStateID.CombinedSession); #endif @@ -386,7 +383,7 @@ protected INativeObject GetINativeInstance (Type t) var storage = new NSMutableData (); return CGImageDestination.Create (new CGDataConsumer (storage), "public.png", 1); case "CGImageMetadataTag": - using (NSString name = new NSString ("tagName")) + using (var name = new NSString ("tagName")) using (var value = new NSString ("value")) return new CGImageMetadataTag (CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value); case "CGImageSource": @@ -400,11 +397,10 @@ protected INativeObject GetINativeInstance (Type t) return SecPolicy.CreateSslPolicy (false, null); case "SecIdentity": using (var options = NSDictionary.FromObjectAndKey (new NSString ("farscape"), SecImportExport.Passphrase)) { - NSDictionary [] array; - var result = SecImportExport.ImportPkcs12 (farscape_pfx, options, out array); + var result = SecImportExport.ImportPkcs12 (farscape_pfx, options, out var array); if (result != SecStatusCode.Success) throw new InvalidOperationException (string.Format ("Could not create the new instance for type {0} due to {1}.", t.Name, result)); - return Runtime.GetINativeObject (array [0].LowlevelObjectForKey (SecImportExport.Identity.Handle), false); + return Runtime.GetINativeObject (array! [0].LowlevelObjectForKey (SecImportExport.Identity.Handle), false); } case "SecTrust": X509Certificate x = X509CertificateLoader.LoadCertificate (mail_google_com); @@ -417,13 +413,13 @@ protected INativeObject GetINativeInstance (Type t) case "NetworkReachability": return new NetworkReachability (IPAddress.Loopback, null); case "VTHdrPerFrameMetadataGenerationSession": - var rv = VTHdrPerFrameMetadataGenerationSession.Create (30, (NSDictionary) null, out var error); + var rv = VTHdrPerFrameMetadataGenerationSession.Create (30, (NSDictionary?) null, out var error); if (rv is null) throw new InvalidOperationException ($"Could not create the new instance for type {t.Name}: {error}"); return rv; case "VTCompressionSession": case "VTSession": - return VTCompressionSession.Create (1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes) null); + return VTCompressionSession.Create (1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes?) null); case "VTPixelRotationSession": return VTPixelRotationSession.Create (); case "VTPixelTransferSession": @@ -480,20 +476,17 @@ protected INativeObject GetINativeInstance (Type t) return new SecTrust2 (new SecTrust (x2, policy)); case "SecIdentity2": using (var options = NSDictionary.FromObjectAndKey (new NSString ("farscape"), SecImportExport.Passphrase)) { - NSDictionary [] array; - var result = SecImportExport.ImportPkcs12 (farscape_pfx, options, out array); + var result = SecImportExport.ImportPkcs12 (farscape_pfx, options, out var array); if (result != SecStatusCode.Success) throw new InvalidOperationException (string.Format ("Could not create the new instance for type {0} due to {1}.", t.Name, result)); - return new SecIdentity2 (Runtime.GetINativeObject (array [0].LowlevelObjectForKey (SecImportExport.Identity.Handle), false)); + return new SecIdentity2 (Runtime.GetINativeObject (array! [0].LowlevelObjectForKey (SecImportExport.Identity.Handle), false)!); } case "SecKey": - SecKey private_key; - SecKey public_key; using (var record = new SecRecord (SecKind.Key)) { record.KeyType = SecKeyType.RSA; record.KeySizeInBits = 512; // it's not a performance test :) - SecKey.GenerateKeyPair (record.ToDictionary (), out public_key, out private_key); + SecKey.GenerateKeyPair (record.ToDictionary (), out var public_key, out var private_key); return private_key; } case "SecAccessControl": @@ -516,21 +509,19 @@ protected ICMAttachmentBearer GetInstance (Type t) CMBlockBufferError bbe; var result = CMBlockBuffer.CreateEmpty (0, CMBlockBufferFlags.AssureMemoryNow, out bbe); if (bbe == CMBlockBufferError.None) - return result; + return result!; else throw new InvalidOperationException (string.Format ("Could not create the new instance {0}.", bbe.ToString ())); case "CMSampleBuffer": var pixelBuffer = new CVPixelBuffer (20, 10, CVPixelFormatType.CV24RGB); - CMFormatDescriptionError fde; - var desc = CMVideoFormatDescription.CreateForImageBuffer (pixelBuffer, out fde); + var desc = CMVideoFormatDescription.CreateForImageBuffer (pixelBuffer, out var fde)!; var sampleTiming = new CMSampleTimingInfo (); - CMSampleBufferError sbe; - var sb = CMSampleBuffer.CreateForImageBuffer (pixelBuffer, true, desc, sampleTiming, out sbe); + var sb = CMSampleBuffer.CreateForImageBuffer (pixelBuffer, true, desc, sampleTiming, out var sbe); if (sbe == CMSampleBufferError.None) - return sb; + return sb!; else throw new InvalidOperationException (string.Format ("Could not create the new instance {0}.", sbe.ToString ())); default: @@ -557,12 +548,12 @@ public void CheckAttachments () obj.RemoveAllAttachments (); Assert.AreEqual (mode, otherMode); Assert.IsNotNull (otherAttch, "For type {0}", t.Name); - Assert.AreEqual (attch.ToString (), otherAttch.ToString (), "For type {0}", t.Name); + Assert.AreEqual (attch?.ToString (), otherAttch?.ToString (), "For type {0}", t.Name); } } if (t is IDisposable) { var disposable = obj as IDisposable; - disposable.Dispose (); + disposable?.Dispose (); } } } @@ -584,7 +575,7 @@ public void CheckFailAttachments () var n = GetINativeInstance (t); if (n is null) Assert.Fail ("Could not create instance of '{0}'.", t); - var obj = new AttachableNativeObject (n); + var obj = new AttachableNativeObject (n!); Assert.That (obj.Handle, Is.Not.EqualTo (IntPtr.Zero), t.Name + ".Handle"); using (var attch = new CFString ("myAttch")) { CMAttachmentMode otherMode; @@ -596,7 +587,7 @@ public void CheckFailAttachments () } if (t is IDisposable) { var disposable = obj as IDisposable; - disposable.Dispose (); + disposable?.Dispose (); } } } diff --git a/tests/introspection/ApiClassPtrTest.cs b/tests/introspection/ApiClassPtrTest.cs index c3589ead61c5..2ee16ec6cae6 100644 --- a/tests/introspection/ApiClassPtrTest.cs +++ b/tests/introspection/ApiClassPtrTest.cs @@ -12,8 +12,7 @@ using Xamarin.Utils; using System.Runtime.CompilerServices; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -36,7 +35,7 @@ protected virtual bool Skip (Type type) return SkipDueToAttribute (type); } - Type GetExtendedType (Type extensionType) + Type? GetExtendedType (Type extensionType) { var method = (from m in extensionType.GetMethods (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) @@ -58,7 +57,7 @@ IntPtr GetClassPtrFromRegister (Type t) var attribs = t.GetCustomAttributes (typeof (RegisterAttribute), true); if (attribs.Length > 0) { var register = ((RegisterAttribute) attribs [0]); - return Class.GetHandle (register.Name); + return Class.GetHandle (register.Name!); } return IntPtr.Zero; } @@ -76,10 +75,10 @@ public void VerifyClassPtr () if (Skip (t)) continue; - FieldInfo fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + var fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (fi is null) continue; - IntPtr class_ptr = (IntPtr) (NativeHandle) fi.GetValue (null); + IntPtr class_ptr = (IntPtr) (NativeHandle) fi.GetValue (null)!; IntPtr register_class_ptr = GetClassPtrFromRegister (t); Assert.AreEqual (class_ptr, register_class_ptr, "class_ptr and RegisterAttribute are different: " + t.Name); @@ -93,10 +92,10 @@ public void VerifyClassPtrCategories () if (Skip (t)) continue; - FieldInfo fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + var fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (fi is null) continue; - IntPtr class_ptr = (IntPtr) (NativeHandle) fi.GetValue (null); + var class_ptr = (IntPtr) (NativeHandle) fi.GetValue (null)!; var extendedType = GetExtendedType (t); IntPtr extended_class_ptr; diff --git a/tests/introspection/ApiCoreImageFiltersTest.cs b/tests/introspection/ApiCoreImageFiltersTest.cs index 2e435b27e507..44d5b0b46fa1 100644 --- a/tests/introspection/ApiCoreImageFiltersTest.cs +++ b/tests/introspection/ApiCoreImageFiltersTest.cs @@ -29,8 +29,7 @@ using UIKit; #endif -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -84,9 +83,9 @@ protected virtual bool Skip (string nativeName) public void CheckNativeFilters () { Errors = 0; - List filters = new List (); + var filters = new List (); int n = 0; - string qname = CIFilterType.AssemblyQualifiedName; + var qname = CIFilterType.AssemblyQualifiedName!; // that will give us only the list of filters supported by the executing version of iOS foreach (var filter_name in CIFilter.FilterNamesInCategories ()) { if (Skip (filter_name)) @@ -95,7 +94,7 @@ public void CheckNativeFilters () if (Type.GetType (type_name, false, true) is null) { filters.Add (filter_name); if (BindingOutput is not null) - GenerateBinding (CIFilter.FromName (filter_name), BindingOutput); + GenerateBinding (CIFilter.FromName (filter_name)!, BindingOutput); } n++; } @@ -127,7 +126,7 @@ public void CheckManagedFilters () if ((ctor is null) || ctor.IsAbstract) continue; - NSObject obj = ctor.Invoke (null) as NSObject; + var obj = ctor.Invoke (null) as NSObject; #if false // check base type - we might have our own base type or different names, so it's debug only (not failure) var super = new Class (obj.Class.SuperClass).Name; @@ -155,19 +154,18 @@ public void CheckManagedFilters () static void GenerateBinding (NSObject filter, TextWriter writer) { - NSObject value; var f = (CIFilter) filter; - var attributes = (filter as CIFilter).Attributes; + var attributes = f.Attributes; writer.WriteLine ("[CoreImageFilter]"); writer.WriteLine ($"/* Attributes for this filter REMOVE-ME:\n\n{attributes}\n\n */"); writer.WriteLine ($"/* Input Keys for this filter: {string.Join (", ", f.InputKeys.Select (v => v.ToString ()).OrderBy (v => v))} */"); writer.WriteLine ($"/* Output Keys for this filter: {string.Join (", ", f.OutputKeys.Select (v => v.ToString ()).OrderBy (v => v))} */"); - if (!attributes.TryGetValue ((NSString) "CIAttributeFilterAvailable_iOS", out value)) { + if (!attributes.TryGetValue ((NSString) "CIAttributeFilterAvailable_iOS", out var value)) { writer.WriteLine ("[NoiOS]"); } else { - var v = value.ToString (); + var v = value.ToString ()!; // in the (quite common) case we get "5" for iOS 5.0 if (v.IndexOf ('.') == -1) v += ".0"; @@ -181,7 +179,7 @@ static void GenerateBinding (NSObject filter, TextWriter writer) writer.WriteLine ("[NoMac]"); } else { try { - var mac = Version.Parse (value.ToString ()); + var mac = Version.Parse (value.ToString ()!); // we only document availability for 10.7+ if (mac.Minor > 6) writer.WriteLine ("[Mac ({0},{1})]", mac.Major, mac.Minor); @@ -191,15 +189,15 @@ static void GenerateBinding (NSObject filter, TextWriter writer) } } writer.WriteLine ("[BaseType (typeof (CIFilter))]"); - var fname = attributes [(NSString) "CIAttributeFilterName"].ToString (); + var fname = attributes [(NSString) "CIAttributeFilterName"]?.ToString (); writer.WriteLine ("interface {0} {{", fname); foreach (var k in attributes.Keys) { - var key = k.ToString (); + var key = k.ToString ()!; if (key.StartsWith ("CIAttribute", StringComparison.Ordinal)) continue; writer.WriteLine (); - var dict = attributes [k] as NSDictionary; + var dict = (NSDictionary) attributes [k]!; var type = dict [(NSString) "CIAttributeClass"]; writer.WriteLine ($"\t[CoreImageFilterProperty (\"{key}\")]"); @@ -393,7 +391,7 @@ public void Keys () if ((ctor is null) || ctor.IsAbstract) continue; - CIFilter f = ctor.Invoke (null) as CIFilter; + var f = (CIFilter) ctor.Invoke (null)!; var attributes = f.Attributes; // first check that every property can be mapped to an input key - except if it starts with "Output" @@ -405,12 +403,12 @@ public void Keys () if (SkipDueToAttribute (p)) continue; - var getter = p.GetGetMethod (); + var getter = p.GetGetMethod ()!; var ea = getter.GetCustomAttribute (false); // only properties coming (inlined) from protocols have an [Export] attribute if (ea is null) continue; - var key = ea.Selector; + var key = ea.Selector!; // 'output' is always explicit if (key.StartsWith ("output", StringComparison.Ordinal)) { if (Array.IndexOf (f.OutputKeys, key) < 0) { diff --git a/tests/introspection/ApiCtorInitTest.cs b/tests/introspection/ApiCtorInitTest.cs index 06d6cedb761e..796a80d7b993 100644 --- a/tests/introspection/ApiCtorInitTest.cs +++ b/tests/introspection/ApiCtorInitTest.cs @@ -27,14 +27,13 @@ using ARKit; #endif -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { public abstract class ApiCtorInitTest : ApiBaseTest { - string instance_type_name; + string? instance_type_name; /// /// Gets or sets a value indicating whether this test fixture will log untested types. @@ -354,7 +353,7 @@ public void DefaultCtorAllowed () if (Skip (t)) continue; - var ctor = t.GetConstructor (Type.EmptyTypes); + var ctor = t.GetConstructor (Type.EmptyTypes)!; if (SkipDueToAttribute (ctor)) continue; @@ -372,23 +371,23 @@ public void DefaultCtorAllowed () if (LogProgress) Console.WriteLine ("{0}. {1}", n, instance_type_name); - NSObject obj = null; + NSObject? obj = null; try { - obj = ctor.Invoke (null) as NSObject; + obj = (NSObject) ctor.Invoke (null); CheckHandle (obj); CheckToString (obj); CheckIsDirectBinding (obj); CheckNSObjectProtocol (obj); Dispose (obj, t); - } catch (Exception e) { + } catch (Exception? e) { // Objective-C exception thrown if (!ContinueOnFailure) throw; - TargetInvocationException tie = (e as TargetInvocationException); + var tie = (e as TargetInvocationException); if (tie is not null) e = tie.InnerException; - ReportError ("Default constructor not allowed for {0} : {1}", instance_type_name, e.Message); + ReportError ("Default constructor not allowed for {0} : {1}", instance_type_name, e?.Message); } n++; } @@ -429,7 +428,7 @@ public void DesignatedInitializer () if (designated > 0) continue; - var base_class = t.BaseType; + var base_class = t.BaseType!; // NSObject ctor requirements are handled by the generator if (base_class == NSObjectType) continue; @@ -440,7 +439,7 @@ public void DesignatedInitializer () // check if this ctor (from base type) is exposed in the current (subclass) type if (!Match (ctor, t)) - ReportError ("{0} should re-expose {1}::{2}", t, base_class.Name, ctor.ToString ().Replace ("Void ", String.Empty)); + ReportError ("{0} should re-expose {1}::{2}", t, base_class?.Name, ctor?.ToString ()?.Replace ("Void ", String.Empty)); n++; } } @@ -684,7 +683,7 @@ public void ShouldNotExposeDefaultCtorTest () if (SkipCheckShouldNotExposeDefaultCtor (t)) continue; - var ctor = t.GetConstructor (Type.EmptyTypes); + var ctor = t.GetConstructor (Type.EmptyTypes)!; if (SkipDueToAttribute (ctor)) continue; @@ -697,7 +696,7 @@ public void ShouldNotExposeDefaultCtorTest () if (LogProgress) Console.WriteLine ($"{n}: {t.FullName}"); - var parentType = t.BaseType; + var parentType = t.BaseType!; var parentCtor = parentType.GetConstructor (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); if (parentCtor is null) { @@ -707,7 +706,7 @@ public void ShouldNotExposeDefaultCtorTest () if (genObjCTestCode) { var export = t.GetCustomAttribute (); var typeName = export?.Name ?? t.Name; - objCCode.AppendLine ($"{typeName}* test{n} = [[{typeName} alloc] init];"); + objCCode!.AppendLine ($"{typeName}* test{n} = [[{typeName} alloc] init];"); } } n++; diff --git a/tests/introspection/ApiFieldTest.cs b/tests/introspection/ApiFieldTest.cs index 69d1f897b87e..4c1ba26b8e93 100644 --- a/tests/introspection/ApiFieldTest.cs +++ b/tests/introspection/ApiFieldTest.cs @@ -22,8 +22,7 @@ using System.IO; using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -53,7 +52,7 @@ protected virtual bool Skip (Type type) /// Property to be tested protected virtual bool Skip (PropertyInfo property) { - switch (property.DeclaringType.Name) { + switch (property.DeclaringType!.Name) { case "AVPlayerInterstitialEventObserver": switch (property.Name) { // deprecated case "CurrentEventDidChangeNotification": @@ -113,7 +112,7 @@ protected virtual bool SkipNotification (Type declaredType, string notificationN bool CheckAgainstNull (PropertyInfo p, out string name) { name = String.Empty; - var g = p.GetGetMethod (true); + var g = p.GetGetMethod (true)!; if (!g.IsStatic) return true; @@ -125,16 +124,16 @@ bool CheckAgainstNull (PropertyInfo p, out string name) // or something not available in the executing version of iOS bool result = g.Invoke (null, null) is not null; if (!result) - name = p.DeclaringType.FullName + "." + p.Name; + name = p.DeclaringType!.FullName + "." + p.Name; return result; } catch (Exception e) { Console.WriteLine ("[FAIL] Exception on '{0}' : {1}", p, e); - name = p.DeclaringType.FullName + "." + p.Name; + name = p.DeclaringType!.FullName + "." + p.Name; return false; } } - static List properties; + static List? properties; IEnumerable AllProperties () { @@ -179,10 +178,10 @@ public void Notifications () if (!name.EndsWith ("Notification", StringComparison.Ordinal)) continue; - if (SkipNotification (p.DeclaringType, name)) + if (SkipNotification (p.DeclaringType!, name)) continue; - var nested = p.DeclaringType.GetNestedTypes (); + var nested = p.DeclaringType!.GetNestedTypes (); if (nested.Length == 0) { ReportError (name); failed_fields.Add (name); @@ -250,10 +249,10 @@ public void FieldExists () continue; string name = f.SymbolName; - if (Skip (name, f.LibraryName)) + if (Skip (name, f.LibraryName!)) continue; - string path = FindLibrary (f.LibraryName); + string path = FindLibrary (f.LibraryName!); IntPtr lib = Dlfcn.dlopen (path, 0); if (lib == IntPtr.Zero) { ReportError ("Could not open the library '{0}' to find the field '{1}': {2}", path, name, Dlfcn.dlerror ()); diff --git a/tests/introspection/ApiFrameworkTest.cs b/tests/introspection/ApiFrameworkTest.cs index d34e34c264db..002de1aeae3a 100644 --- a/tests/introspection/ApiFrameworkTest.cs +++ b/tests/introspection/ApiFrameworkTest.cs @@ -1,8 +1,7 @@ using System.IO; using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable public class Application { public bool IsSimulatorBuild { @@ -96,7 +95,7 @@ public void NativeFrameworks () foreach (Type t in Assembly.GetTypes ()) { if (!t.IsPublic) continue; - var ns = t.Namespace; + var ns = t.Namespace!; if (Skip (ns)) continue; n++; diff --git a/tests/introspection/ApiPInvokeTest.cs b/tests/introspection/ApiPInvokeTest.cs index 5dee89e4e240..b00e86deebb2 100644 --- a/tests/introspection/ApiPInvokeTest.cs +++ b/tests/introspection/ApiPInvokeTest.cs @@ -13,8 +13,7 @@ using System.Reflection; using Xamarin.Tests; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { [Preserve (AllMembers = true)] @@ -96,12 +95,12 @@ protected virtual bool CheckParameter (MethodInfo mi, ParameterInfo pi) // `ref` is fine but it can hide the droids we're looking for var pt = pi.ParameterType; if (pt.IsByRef) - pt = pt.GetElementType (); + pt = pt.GetElementType ()!; // we don't want generics in p/invokes except for delegates like Func<> and Action<> which we know how to deal with // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=42699 if (pt.IsGenericType && !pt.IsSubclassOf (typeof (Delegate))) { AddErrorLine ("[FAIL] {0}.{1} has a generic parameter in its signature: {2} {3}", - mi.DeclaringType.FullName, mi.Name, pt, pi.Name); + mi.DeclaringType?.FullName, mi.Name, pt, pi.Name); result = false; } result &= CheckForEnumParameter (mi, pi); @@ -112,7 +111,7 @@ protected virtual bool CheckForEnumParameter (MethodInfo mi, ParameterInfo pi) { if (pi.ParameterType.IsEnum && pi.ParameterType.GetCustomAttribute () is not null) { AddErrorLine ("[FAIL] {0}.{1} has a [Native] enum parameter in its signature: {2} {3}", - mi.DeclaringType.FullName, mi.Name, pi.ParameterType, pi.Name); + mi.DeclaringType?.FullName, mi.Name, pi.ParameterType, pi.Name); return false; } @@ -131,7 +130,7 @@ protected virtual bool Skip (string symbolName) return false; } - protected virtual bool SkipLibrary (string libraryName) + protected virtual bool SkipLibrary (string? libraryName) { return false; } @@ -147,9 +146,9 @@ public void SymbolExists () if (LogProgress) Console.WriteLine ("{0}. {1}", c++, mi); - var dllimport = mi.GetCustomAttribute (); + var dllimport = mi.GetCustomAttribute ()!; - string libname = dllimport.Value; + var libname = dllimport.Value; switch (libname) { case "__Internal": continue; @@ -163,7 +162,7 @@ public void SymbolExists () if (SkipLibrary (libname)) continue; - string path = FindLibrary (libname, requiresFullPath: true); + var path = FindLibrary (libname!, requiresFullPath: true); string name = dllimport.EntryPoint ?? mi.Name; if (Skip (name)) @@ -206,9 +205,9 @@ protected void Check (Assembly a) if ((m.Attributes & MethodAttributes.PinvokeImpl) == 0) continue; - var dllimport = m.GetCustomAttribute (); + var dllimport = m.GetCustomAttribute ()!; - string name = dllimport.EntryPoint ?? m.Name; + var name = dllimport.EntryPoint ?? m.Name; switch (name) { // known not to be present in ARM64 case "objc_msgSend_stret": @@ -217,7 +216,7 @@ protected void Check (Assembly a) continue; } - string path = dllimport.Value; + string? path = dllimport.Value; switch (path) { case "__Internal": // load from executable @@ -268,7 +267,7 @@ protected void Check (Assembly a) if (found != 0) { // Resolve symlinks in both cases var dllImportPath = ResolveLibrarySymlinks (path); - var foundLibrary = ResolveLibrarySymlinks (Marshal.PtrToStringAuto (info.dli_fname)); + var foundLibrary = ResolveLibrarySymlinks (Marshal.PtrToStringAuto (info.dli_fname)!); if (Skip (name, ref dllImportPath, ref foundLibrary)) { // Skipped } else if (foundLibrary != dllImportPath) { diff --git a/tests/introspection/ApiSelectorTest.cs b/tests/introspection/ApiSelectorTest.cs index 46ef84fd3ba2..adc714e82090 100644 --- a/tests/introspection/ApiSelectorTest.cs +++ b/tests/introspection/ApiSelectorTest.cs @@ -21,8 +21,7 @@ using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -1342,7 +1341,7 @@ static bool CheckForInlinedProtocolMember (Type actualType, MethodBase method) return false; } - static bool IsMethodImplemented (Type iface, Type type, MethodBase method, bool isExtensionMethod) + static bool IsMethodImplemented (Type iface, Type? type, MethodBase method, bool isExtensionMethod) { if (type is null) return false; @@ -1417,11 +1416,11 @@ void ProcessProtocolMember (Type t, MethodBase m, ref int n) return; foreach (object ca in m.GetCustomAttributes (true)) { - ExportAttribute export = (ca as ExportAttribute); + var export = ca as ExportAttribute; if (export is null) continue; - string name = export.Selector; + string name = export.Selector!; if (Skip (t, name)) continue; @@ -1443,7 +1442,7 @@ protected virtual bool TryGetClassForType (Type type, out IntPtr cls) return false; } - cls = (NativeHandle) fi.GetValue (null); + cls = (NativeHandle) fi.GetValue (null)!; return true; } @@ -1484,11 +1483,11 @@ void Process (IntPtr class_ptr, Type t, MethodBase m, ref int n) return; foreach (object ca in m.GetCustomAttributes (true)) { - ExportAttribute export = (ca as ExportAttribute); + var export = ca as ExportAttribute; if (export is null) continue; - string name = export.Selector; + string name = export.Selector!; if (Skip (t, name)) continue; @@ -1569,13 +1568,13 @@ public void StaticMethods () foreach (object ca in m.GetCustomAttributes (true)) { if (ca is ExportAttribute) { - string name = (ca as ExportAttribute).Selector; + var name = (ca as ExportAttribute)!.Selector!; if (Skip (t, name)) continue; bool result = bool_objc_msgSend_IntPtr (class_ptr, responds_handle, Selector.GetHandle (name)); - bool response = CheckStaticResponse (result, t, m.DeclaringType, m, ref name); + bool response = CheckStaticResponse (result, t, m.DeclaringType!, m, ref name); if (!response) ReportError (name); n++; diff --git a/tests/introspection/ApiSignatureTest.cs b/tests/introspection/ApiSignatureTest.cs index 95973e43b7ea..d843b25dec62 100644 --- a/tests/introspection/ApiSignatureTest.cs +++ b/tests/introspection/ApiSignatureTest.cs @@ -24,8 +24,7 @@ using System.Text; using System.Linq; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -45,11 +44,11 @@ public abstract class ApiSignatureTest : ApiBaseTest { [DllImport ("/usr/lib/libobjc.dylib")] static extern IntPtr class_getInstanceMethod (IntPtr klass, IntPtr selector); - protected string [] Split (string encoded, out int size) + protected string []? Split (string encoded, out int size) { - List elements = new List (); + var elements = new List (); int pos = 0; - string s = Next (encoded, ref pos); + var s = Next (encoded, ref pos); int end = pos; while (Char.IsDigit (encoded [end])) end++; @@ -72,7 +71,7 @@ protected string [] Split (string encoded, out int size) return elements.ToArray (); } - static string Next (string encoded, ref int pos) + static string? Next (string encoded, ref int pos) { // skip digits while (pos < encoded.Length && Char.IsDigit (encoded [pos])) @@ -80,7 +79,7 @@ static string Next (string encoded, ref int pos) if (pos >= encoded.Length) return null; - StringBuilder sb = new StringBuilder (); + var sb = new StringBuilder (); int acc = 0; char c = encoded [pos]; while (!Char.IsDigit (c) || acc > 0) { @@ -175,11 +174,11 @@ protected virtual bool Skip (Type type, MethodBase method, string selector) public int CurrentParameter { get; private set; } - public MethodBase CurrentMethod { get; private set; } + public MethodBase? CurrentMethod { get; private set; } - public string CurrentSelector { get; private set; } + public string? CurrentSelector { get; private set; } - public Type CurrentType { get; private set; } + public Type? CurrentType { get; private set; } const BindingFlags Flags = BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance; @@ -201,10 +200,10 @@ public void NativeSignatures () CurrentType = t; - FieldInfo fi = null; + FieldInfo? fi = null; if (!static_type) fi = t.GetField ("class_ptr", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); - IntPtr class_ptr = fi is null ? IntPtr.Zero : (IntPtr) (NativeHandle) fi.GetValue (null); + IntPtr class_ptr = fi is null ? IntPtr.Zero : (IntPtr) (NativeHandle) fi.GetValue (null)!; foreach (MethodBase m in t.GetMethods (Flags)) CheckMemberSignature (m, t, class_ptr, ref n); @@ -235,7 +234,7 @@ void CheckMemberSignature (MethodBase m, Type t, IntPtr class_ptr, ref int n) var exportAttribute = ca as ExportAttribute; if (exportAttribute is null) continue; - string name = exportAttribute.Selector; + var name = exportAttribute.Selector!; if (exportAttribute.IsVariadic) { VariadicChecks (m); @@ -251,7 +250,7 @@ void CheckMemberSignature (MethodBase m, Type t, IntPtr class_ptr, ref int n) if (class_ptr == IntPtr.Zero) { BasicChecks (m, t, ref n); } else { - IntrospectionTest (m, methodinfo, t, class_ptr, ref n); + IntrospectionTest (m, methodinfo!, t, class_ptr, ref n); } } } @@ -259,14 +258,14 @@ void CheckMemberSignature (MethodBase m, Type t, IntPtr class_ptr, ref int n) void VariadicChecks (MethodBase m) { if (m.IsPublic || m.IsFamily || m.IsFamilyOrAssembly) { - AddErrorLine ("Function '{0}.{1}' is exposed and variadic. Variadic methods need custom marshaling, and must not be exposed directly.", m.DeclaringType.FullName, m.Name); + AddErrorLine ("Function '{0}.{1}' is exposed and variadic. Variadic methods need custom marshaling, and must not be exposed directly.", m.DeclaringType!.FullName, m.Name); } } void BasicChecks (MethodBase m, Type t, ref int n) { int native = 0; - int pos = CurrentSelector.IndexOf (':'); + int pos = CurrentSelector!.IndexOf (':'); while (pos != -1) { native++; pos = CurrentSelector.IndexOf (':', pos + 1); @@ -289,14 +288,14 @@ void BasicChecks (MethodBase m, Type t, ref int n) void IntrospectionTest (MethodBase m, MethodInfo methodinfo, Type t, IntPtr class_ptr, ref int n) { - IntPtr sel = Selector.GetHandle (CurrentSelector); + IntPtr sel = Selector.GetHandle (CurrentSelector!); IntPtr method; if (methodinfo is not null) method = m.IsStatic ? class_getClassMethod (class_ptr, sel) : class_getInstanceMethod (class_ptr, sel); else method = class_getInstanceMethod (class_ptr, sel); IntPtr tenc = method_getTypeEncoding (method); - string encoded = Marshal.PtrToStringAuto (tenc); + var encoded = Marshal.PtrToStringAuto (tenc); if (LogProgress) Console.WriteLine ("{0} {1} '{2} {3}' selector: {4} == {5}", ++n, t.Name, methodinfo is not null ? methodinfo.IsStatic ? "static" : "instance" : "ctor", m, CurrentSelector, encoded); @@ -306,7 +305,7 @@ void IntrospectionTest (MethodBase m, MethodInfo methodinfo, Type t, IntPtr clas return; int encoded_size = -1; - string [] elements = null; + string []? elements = null; try { elements = Split (encoded, out encoded_size); } catch { @@ -544,7 +543,7 @@ protected virtual bool Check (string encodedType, Type type) case '@': switch (encodedType [1]) { case '?': - return (type.Name == "NSAction") || type.BaseType.FullName == "System.MulticastDelegate"; + return (type.Name == "NSAction") || type.BaseType!.FullName == "System.MulticastDelegate"; default: return false; } @@ -552,7 +551,7 @@ protected virtual bool Check (string encodedType, Type type) switch (encodedType [1]) { case 'v': // NSOpenGLContext 'instance MonoMac.OpenGL.CGLContext get_CGLContext()' selector: CGLContextObj == ^v8@0:4 - if ((CurrentType.Name == "NSOpenGLContext") && (type.Name == "CGLContext")) + if ((CurrentType!.Name == "NSOpenGLContext") && (type.Name == "CGLContext")) return true; // NSOpenGLPixelFormat 'instance MonoMac.OpenGL.CGLPixelFormat get_CGLPixelFormat()' selector: CGLPixelFormatObj == ^v8@0:4 if ((CurrentType.Name == "NSOpenGLPixelFormat") && (type.Name == "CGLPixelFormat")) @@ -573,7 +572,7 @@ protected virtual bool Check (string encodedType, Type type) case 'q': case 'Q': case 'S': - return (type.FullName == "System.IntPtr") || Check (encodedType.Substring (1), type.GetElementType ()); + return (type.FullName == "System.IntPtr") || Check (encodedType.Substring (1), type.GetElementType ()!); // NSInputStream 'instance Boolean GetBuffer(IntPtr ByRef, UInt32 ByRef)' selector: getBuffer:length: == c16@0:4^*8^I12 case '*': case '{': @@ -581,9 +580,9 @@ protected virtual bool Check (string encodedType, Type type) case 'r': if (type.FullName == "System.IntPtr") return true; - return Check (encodedType.Substring (1), type.IsByRef ? type.GetElementType () : type); + return Check (encodedType.Substring (1), type.IsByRef ? type.GetElementType ()! : type); case '@': - return Check ('@', type.IsByRef ? type.GetElementType () : type); + return Check ('@', type.IsByRef ? type.GetElementType ()! : type); case '^': case '?': return (type.FullName == "System.IntPtr"); @@ -629,7 +628,7 @@ protected virtual bool Check (char encodedType, Type type) (type.Name == "NSArray") || // NSArray (type.FullName == "System.String") || // NSString (type.FullName == "System.IntPtr") || // unbinded, e.g. internal - (type.BaseType.FullName == "System.MulticastDelegate") || // completion handler -> delegate + (type.BaseType!.FullName == "System.MulticastDelegate") || // completion handler -> delegate NSObjectType.IsAssignableFrom (type)) || // NSObject derived inativeobject.IsAssignableFrom (type); // e.g. CGImage case 'B': @@ -760,7 +759,7 @@ protected virtual bool Check (char encodedType, Type type) case 'v': return type.FullName == "System.Void"; case '?': - return type.BaseType.FullName == "System.MulticastDelegate"; // completion handler -> delegate + return type.BaseType!.FullName == "System.MulticastDelegate"; // completion handler -> delegate case '#': return type.FullName == "System.IntPtr" || type.Name == "Class"; // CAMediaTimingFunction 'instance Void GetControlPointAtIndex(Int32, IntPtr)' selector: getControlPointAtIndex:values: == v16@0:4L8[2f]12 @@ -802,7 +801,7 @@ public void ManagedSignature () protected virtual bool CheckType (Type t, ref int n) { if (t.IsArray) - return CheckType (t.GetElementType (), ref n); + return CheckType (t.GetElementType ()!, ref n); // e.g. NSDictionary needs 3 check if (t.IsGenericType) { foreach (var ga in t.GetGenericArguments ()) @@ -839,7 +838,7 @@ protected virtual void CheckManagedMemberSignatures (MethodBase m, Type t, ref i ReportError ($"`{t.Name}.{m.Name}` includes a parameter of type `{pt.Name}` which is a concrete type `[Model]` and not an interface `[Protocol]`"); } if (!m.IsConstructor) { - var rt = (m as MethodInfo).ReturnType; + var rt = ((MethodInfo) m).ReturnType; if (!CheckType (rt, ref n)) ReportError ($"`{t.Name}.{m.Name}` return type `{rt.Name}` is a concrete type `[Model]` and not an interface `[Protocol]`"); } @@ -934,7 +933,7 @@ public void AsyncCandidates () if (methods.Where ((mi) => mi.Name == ma).FirstOrDefault () is not null) continue; - var name = m.ToString (); + var name = m.ToString ()!; var i = name.IndexOf (' '); ErrorData.AppendLine (name.Insert (i + 1, m.DeclaringType.Name + "::")); Errors++; @@ -948,27 +947,27 @@ protected virtual bool IgnoreAsync (MethodInfo m) switch (m.Name) { // we bind PerformChangesAndWait which does the same case "PerformChanges": - return m.DeclaringType.Name == "PHPhotoLibrary"; + return m.DeclaringType!.Name == "PHPhotoLibrary"; // it sets the callback, it will never call it case "SetCompletionBlock": - return m.DeclaringType.Name == "SCNTransaction"; + return m.DeclaringType!.Name == "SCNTransaction"; // It does not make sense for this API case "CreateRunningPropertyAnimator": - return m.DeclaringType.Name == "UIViewPropertyAnimator"; + return m.DeclaringType!.Name == "UIViewPropertyAnimator"; // It does not make sense for this API case "RequestData": - return m.DeclaringType.Name == "PHAssetResourceManager"; + return m.DeclaringType!.Name == "PHAssetResourceManager"; // It does not make sense for this API case "Register": case "SignalEnumerator": - return m.DeclaringType.Name == "NSFileProviderManager"; + return m.DeclaringType!.Name == "NSFileProviderManager"; case "Synchronize": // comes from a protocol implementation - return m.DeclaringType.Name == "NSTextContentManager"; + return m.DeclaringType!.Name == "NSTextContentManager"; case "AccommodatePresentedItemEviction": // comes from a protocol implementation - return m.DeclaringType.Name == "NSFilePresenter" || m.DeclaringType.Name == "UIDocument"; + return m.DeclaringType!.Name == "NSFilePresenter" || m.DeclaringType!.Name == "UIDocument"; case "StartCapture": case "StopCapture": // it does not make sense for these APIs - return m.DeclaringType.Name == "SCStream"; + return m.DeclaringType!.Name == "SCStream"; } return false; } diff --git a/tests/introspection/ApiTypeTest.cs b/tests/introspection/ApiTypeTest.cs index a5d8069a0195..7692e7dea16e 100644 --- a/tests/introspection/ApiTypeTest.cs +++ b/tests/introspection/ApiTypeTest.cs @@ -3,8 +3,7 @@ using Xamarin.Utils; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -60,7 +59,7 @@ public void StaticCtor () try { RuntimeHelpers.RunClassConstructor (t.TypeHandle); } catch (TypeInitializationException e) { - issues.Add (t.FullName); + issues.Add (t.FullName!); ReportError ($"{t.FullName} .cctor could not execute properly: {e}"); } } diff --git a/tests/introspection/ApiTypoTest.cs b/tests/introspection/ApiTypoTest.cs index 42e31c73d30d..905466a88909 100644 --- a/tests/introspection/ApiTypoTest.cs +++ b/tests/introspection/ApiTypoTest.cs @@ -33,8 +33,7 @@ using Xamarin.Tests; using Xamarin.Utils; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { public abstract class ApiTypoTest : ApiBaseTest { @@ -50,7 +49,7 @@ public virtual bool Skip (Type baseType, string typo) public virtual bool Skip (MemberInfo methodName, string typo) { - return SkipAllowed (methodName.DeclaringType.Name, methodName.Name, typo); + return SkipAllowed (methodName.DeclaringType!.Name, methodName.Name, typo); } readonly HashSet allowedRule3 = new HashSet { @@ -731,7 +730,7 @@ public virtual bool Skip (MemberInfo methodName, string typo) // ease maintenance of the list HashSet used = new HashSet (); - bool SkipAllowed (string typeName, string methodName, string typo) + bool SkipAllowed (string typeName, string? methodName, string typo) { if (allowed.Contains (typo)) { used.Add (typo); @@ -740,7 +739,7 @@ bool SkipAllowed (string typeName, string methodName, string typo) return false; } - bool IsObsolete (MemberInfo mi) + bool IsObsolete (MemberInfo? mi) { if (mi is null) return false; @@ -859,9 +858,9 @@ public virtual void TypoTest () Assert.AreEqual (0, totalErrors, "Typos!"); } - string GetMessage (object attribute) + string? GetMessage (object attribute) { - string message = null; + string? message = null; if (attribute is AdviceAttribute) message = ((AdviceAttribute) attribute).Message; if (attribute is ObsoleteAttribute) @@ -876,7 +875,7 @@ void AttributesMessageTypoRules (MemberInfo mi, string typeName, ref int totalEr return; foreach (object ca in mi.GetCustomAttributes ()) { - string message = GetMessage (ca); + var message = GetMessage (ca); if (message is not null) { var memberAndTypeFormat = mi.Name == typeName ? "Type: {0}" : "Member name: {1}, Type: {0}"; var memberAndType = string.Format (memberAndTypeFormat, typeName, mi.Name); @@ -929,8 +928,7 @@ void AttributesMessageTypoRules (MemberInfo mi, string typeName, ref int totalEr Dictionary cached_typoes = new Dictionary (); string GetCachedTypo (string txt) { - string rv; - if (!cached_typoes.TryGetValue (txt, out rv)) + if (!cached_typoes.TryGetValue (txt, out var rv)) cached_typoes [txt] = rv = GetTypo (txt); return rv; } @@ -964,7 +962,7 @@ static string NameCleaner (string name) return clean.ToString (); } - bool CheckLibrary (string lib) + bool CheckLibrary (string? lib) { #if MONOMAC // on macOS the file should exist on the specified path diff --git a/tests/introspection/ApiWeakPropertyTest.cs b/tests/introspection/ApiWeakPropertyTest.cs index 681d3a145b0b..230e7ed8f1a8 100644 --- a/tests/introspection/ApiWeakPropertyTest.cs +++ b/tests/introspection/ApiWeakPropertyTest.cs @@ -1,8 +1,7 @@ using System.IO; using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { [Preserve (AllMembers = true)] @@ -33,20 +32,20 @@ protected virtual bool Skip (PropertyInfo property) switch (property.Name) { // the selector starts with `weak` case "WeakRelatedUniqueIdentifier": - return property.DeclaringType.Name == "CSSearchableItemAttributeSet"; + return property.DeclaringType!.Name == "CSSearchableItemAttributeSet"; // this is a weakly typed API (not a weak reference) with a [NotImplemented] so there's no [Export] case "WeakSignificantEvent": - return property.DeclaringType.Name == "HMSignificantTimeEvent"; + return property.DeclaringType!.Name == "HMSignificantTimeEvent"; case "WeakMeasurementUnits": // this is a weakly typed API (not a weak reference), so there's no [Export] - return property.DeclaringType.Name == "NSRulerView"; + return property.DeclaringType!.Name == "NSRulerView"; #if !XAMCORE_5_0 case "WeakEnabled": // this is from a strongly typed dictionary, and "Weak" here means nullable (bool) as opposed to a plain bool - and this is fixed in XAMCORE_5_0 so that the Enabled property is nullable and thus we won't need the WeakEnabled version anymore. - return property.DeclaringType.Name == "CTFontDescriptorAttributes"; + return property.DeclaringType!.Name == "CTFontDescriptorAttributes"; #endif case "WeakDynamicRangePolicy": - switch (property.DeclaringType.Name) { + switch (property.DeclaringType!.Name) { case "AVAssetImageGenerator": // This is a weakly typed version of a NSString enum property, so not overridable [Export] (the property is [Sealed]) return true; @@ -54,7 +53,7 @@ protected virtual bool Skip (PropertyInfo property) return false; } - switch (property.DeclaringType.Name) { + switch (property.DeclaringType!.Name) { case "CHHapticPatternDefinition": return property.Name == "WeakParameterCurve" || property.Name == "WeakParameterCurveControlPoints"; } @@ -65,7 +64,7 @@ protected virtual bool Skip (PropertyInfo property) [Test] public void WeakPropertiesHaveArgumentSemantic () { - var failed_properties = new List (); + var failed_properties = new List (); Errors = 0; int c = 0, n = 0; @@ -91,12 +90,11 @@ public void WeakPropertiesHaveArgumentSemantic () if (!name.StartsWith ("Weak", StringComparison.Ordinal)) continue; - string error; - if (CheckArgumentSemantic (p.GetMethod, out error)) { + if (CheckArgumentSemantic (p.GetMethod!, out var error)) { ReportError (error); failed_properties.Add (p.ToString ()); } - if (CheckArgumentSemantic (p.SetMethod, out error)) { + if (CheckArgumentSemantic (p.SetMethod!, out error)) { ReportError (error); failed_properties.Add (p.ToString ()); } @@ -106,12 +104,12 @@ public void WeakPropertiesHaveArgumentSemantic () Assert.AreEqual (0, Errors, "{0} errors found in {1} fields validated: {2}", Errors, n, string.Join (", ", failed_properties)); } - bool CheckArgumentSemantic (MethodInfo meth, out string error) + bool CheckArgumentSemantic (MethodInfo meth, [NotNullWhen (true)] out string? error) { error = null; var export = meth.GetCustomAttribute (); if (export is null) { - error = String.Format ("{0}.{1} has no [Export]", meth.DeclaringType.FullName, meth.Name); + error = String.Format ("{0}.{1} has no [Export]", meth.DeclaringType?.FullName, meth.Name); return true; } @@ -122,7 +120,7 @@ bool CheckArgumentSemantic (MethodInfo meth, out string error) case ArgumentSemantic.Weak: return false; default: - error = String.Format ("{0}.{1} has incorrect ArgumentSemantics: {2}", meth.DeclaringType.FullName, meth.Name, export.ArgumentSemantic); + error = String.Format ("{0}.{1} has incorrect ArgumentSemantics: {2}", meth.DeclaringType?.FullName, meth.Name, export.ArgumentSemantic); return true; } } diff --git a/tests/introspection/CoreSelectorTest.cs b/tests/introspection/CoreSelectorTest.cs index 3cd36baf84ea..be8f2be7d23d 100644 --- a/tests/introspection/CoreSelectorTest.cs +++ b/tests/introspection/CoreSelectorTest.cs @@ -9,8 +9,7 @@ using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -21,7 +20,7 @@ protected override bool CheckResponse (bool value, Type actualType, MethodBase m if (value) return true; - var declaredType = method.DeclaringType; + var declaredType = method.DeclaringType!; switch (declaredType.Name) { case "NSUrlSessionTaskMetrics": @@ -122,9 +121,9 @@ protected override bool TryGetClassForType (Type type, out IntPtr cls) case "MTLVertexAttributeDescriptor": case "MTLVertexBufferLayoutDescriptor": case "MTLVertexDescriptor": - var ctor = type.GetConstructor (Type.EmptyTypes); + var ctor = type.GetConstructor (Type.EmptyTypes)!; using (var obj = ctor.Invoke (null) as NSObject) { - cls = IntPtr_objc_msgSend (obj.Handle, Selector.GetHandle ("class")); + cls = IntPtr_objc_msgSend (obj!.Handle, Selector.GetHandle ("class")); return true; } } diff --git a/tests/introspection/MacApiPInvokeTest.cs b/tests/introspection/MacApiPInvokeTest.cs index 006c72fb8b3f..1c0eca19b36b 100644 --- a/tests/introspection/MacApiPInvokeTest.cs +++ b/tests/introspection/MacApiPInvokeTest.cs @@ -7,7 +7,7 @@ namespace Introspection { [TestFixture] public class MacApiPInvokeTest : ApiPInvokeTest { - protected override bool SkipLibrary (string libraryName) + protected override bool SkipLibrary (string? libraryName) { switch (libraryName) { case "/System/Library/Frameworks/OpenGL.framework/OpenGL": diff --git a/tests/introspection/iOSApiFieldTest.cs b/tests/introspection/iOSApiFieldTest.cs index 00cdfde8dbef..7150bb442cc1 100644 --- a/tests/introspection/iOSApiFieldTest.cs +++ b/tests/introspection/iOSApiFieldTest.cs @@ -10,8 +10,7 @@ using System.Reflection; using UIKit; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -33,7 +32,7 @@ protected override bool Skip (Type type) protected override bool Skip (PropertyInfo p) { - switch (p.DeclaringType.Namespace) { + switch (p.DeclaringType!.Namespace) { case "CoreAudioKit": case "MonoTouch.CoreAudioKit": case "Metal": diff --git a/tests/introspection/iOSApiSelectorTest.cs b/tests/introspection/iOSApiSelectorTest.cs index ebea412a6b87..868a3c427855 100644 --- a/tests/introspection/iOSApiSelectorTest.cs +++ b/tests/introspection/iOSApiSelectorTest.cs @@ -13,8 +13,7 @@ using WatchConnectivity; #endif -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -128,7 +127,7 @@ protected override bool CheckResponse (bool value, Type actualType, MethodBase m if (value) return true; - var declaredType = method.DeclaringType; + var declaredType = method.DeclaringType!; switch (declaredType.Name) { #if __MACCATALYST__ diff --git a/tests/introspection/iOSApiSignatureTest.cs b/tests/introspection/iOSApiSignatureTest.cs index 72dad7db9554..c180c6c9aa59 100644 --- a/tests/introspection/iOSApiSignatureTest.cs +++ b/tests/introspection/iOSApiSignatureTest.cs @@ -11,8 +11,7 @@ using UIKit; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -114,7 +113,7 @@ protected override bool Check (char encodedType, Type type) // documented (web and header file) as NSInteger // UIImageView 'instance Void set_AnimationRepeatCount(Int32)' selector: setAnimationRepeatCount: == v12@0:4f8 case "System.Int32": - return CurrentType.FullName == "MonoTouch.UIKit.UIImageView"; + return CurrentType!.FullName == "MonoTouch.UIKit.UIImageView"; } break; case 'i': @@ -197,7 +196,7 @@ protected override bool IgnoreAsync (MethodInfo m) switch (m.Name) { // Called by the OS, i.e. meant to be overridden (not called) by user code. case "DidReceiveNotification": - return m.DeclaringType.Name == "WKUserNotificationInterfaceController"; + return m.DeclaringType!.Name == "WKUserNotificationInterfaceController"; case "AddCompletion": return true; // comes from NSFilePresenter protocol, where we cannot put [Async] today @@ -205,9 +204,9 @@ protected override bool IgnoreAsync (MethodInfo m) case "AccommodatePresentedItemDeletion": case "AccommodatePresentedSubitemDeletion": case "SavePresentedItemChanges": - return m.DeclaringType.Name == "UIDocument"; + return m.DeclaringType!.Name == "UIDocument"; case "PostNotification": // completion handler is not always called - return m.DeclaringType.Name == "ICNotificationManager"; + return m.DeclaringType!.Name == "ICNotificationManager"; } return base.IgnoreAsync (m); } diff --git a/tests/introspection/iOSApiWeakPropertyTest.cs b/tests/introspection/iOSApiWeakPropertyTest.cs index 245a7359c9a0..ddedfe965b5e 100644 --- a/tests/introspection/iOSApiWeakPropertyTest.cs +++ b/tests/introspection/iOSApiWeakPropertyTest.cs @@ -1,7 +1,6 @@ using System.Reflection; -// Disable until we get around to enable + fix any issues. -#nullable disable +#nullable enable namespace Introspection { @@ -17,7 +16,7 @@ public iOSApiWeakPropertyTest () protected override bool Skip (PropertyInfo property) { - switch (property.DeclaringType.Name) { + switch (property.DeclaringType!.Name) { // WeakVideoGravity is an NSString that we could/should provide a better binding (e.g. enum) case "AVPlayerViewController": return property.Name == "WeakVideoGravity"; diff --git a/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs b/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs index 82623be6d8dc..0038e0aa175f 100644 --- a/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs +++ b/tests/rgen/Microsoft.Macios.Generator.Tests/BaseGeneratorTestClass.cs @@ -70,7 +70,7 @@ protected IEnumerable GetPlatformDefines (TargetFramework targetFramewor protected CompilationResult CreateCompilation (ApplePlatform platform, [CallerMemberName] string name = "", params string [] sources) { // get the dotnet bcl and fully load it for the test. - var references = Directory.GetFiles (Configuration.DotNetBclDir, "*.dll") + var references = Directory.GetFiles (Configuration.DotNetBclDir!, "*.dll") .Select (assembly => MetadataReference.CreateFromFile (assembly)).ToList (); // get the dll for the current platform var targetFramework = TargetFramework.GetTargetFramework (platform); diff --git a/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs b/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs index fcd1c85b77c4..9ff86f5b609d 100644 --- a/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs +++ b/tests/rgen/Microsoft.Macios.Transformer.Tests/BaseTransformerTestClass.cs @@ -47,7 +47,7 @@ protected Compilation CreateCompilation (ApplePlatform platform, [CallerMemberNa .WithPreprocessorSymbols (preprocessorDirectives) .WithDocumentationMode (DocumentationMode.None); - var references = parseResult.GetReferences (workingDirectory, Configuration.DotNetBclDir).ToList (); + var references = parseResult.GetReferences (workingDirectory, Configuration.DotNetBclDir!).ToList (); // add the mono cecil assembly, which we are missing in the api compilation rsp references.Add (MetadataReference.CreateFromFile (typeof (Mono.Cecil.Cil.OpCode).Assembly.Location)); var parsedSource = parseResult.GetSourceFiles (updatedParseOptions).ToList ();