From 2e7c233f6c9bf6430672b39f970a3324deba79dd Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 6 Apr 2022 21:48:55 -0400 Subject: enable nullable annotations by default (#837) This adds `#nullable disable` to all existing code (except where null is impossible like enum files), so it can be migrated incrementally. --- src/SMAPI/Framework/Logging/InterceptingTextWriter.cs | 2 ++ src/SMAPI/Framework/Logging/LogFileManager.cs | 2 ++ src/SMAPI/Framework/Logging/LogManager.cs | 2 ++ 3 files changed, 6 insertions(+) (limited to 'src/SMAPI/Framework/Logging') diff --git a/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs b/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs index bad69a2a..a0957b90 100644 --- a/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs +++ b/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.IO; using System.Text; diff --git a/src/SMAPI/Framework/Logging/LogFileManager.cs b/src/SMAPI/Framework/Logging/LogFileManager.cs index 6ab2bdfb..0b6f9ad2 100644 --- a/src/SMAPI/Framework/Logging/LogFileManager.cs +++ b/src/SMAPI/Framework/Logging/LogFileManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.IO; diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index a8a8b6ee..dab7f554 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -1,3 +1,5 @@ +#nullable disable + using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -- cgit From f39da383a17b368e92fd243cf155b27ba42671f3 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 13 Apr 2022 20:24:14 -0400 Subject: enable nullable annotations in SMAPI where no logic changes are needed (#837) --- src/SMAPI.Tests/Core/AssetNameTests.cs | 2 +- src/SMAPI.Tests/Core/TranslationTests.cs | 4 +- .../Framework/ModData/ModDataRecord.cs | 2 +- src/SMAPI/Constants.cs | 26 +++++----- src/SMAPI/Events/AssetRequestedEventArgs.cs | 14 +++--- src/SMAPI/Events/MenuChangedEventArgs.cs | 16 +++---- src/SMAPI/Framework/Command.cs | 6 +-- .../Framework/Commands/HarmonySummaryCommand.cs | 20 ++++---- src/SMAPI/Framework/Content/AssetData.cs | 7 ++- .../Framework/Content/AssetDataForDictionary.cs | 4 +- src/SMAPI/Framework/Content/AssetDataForImage.cs | 4 +- src/SMAPI/Framework/Content/AssetDataForObject.cs | 4 +- src/SMAPI/Framework/Content/AssetEditOperation.cs | 6 +-- src/SMAPI/Framework/Content/AssetInfo.cs | 12 ++--- .../Framework/Content/AssetInterceptorChange.cs | 7 ++- src/SMAPI/Framework/Content/AssetLoadOperation.cs | 6 +-- src/SMAPI/Framework/ContentCoordinator.cs | 35 +++++++------- .../ContentManagers/GameContentManager.cs | 34 +++++++------ .../GameContentManagerForAssetPropagation.cs | 4 +- .../Framework/ContentManagers/IContentManager.cs | 13 ++--- src/SMAPI/Framework/ContentPack.cs | 9 ++-- src/SMAPI/Framework/CursorPosition.cs | 4 +- src/SMAPI/Framework/Events/ManagedEvent.cs | 8 ++-- src/SMAPI/Framework/Events/ManagedEventHandler.cs | 4 +- .../Framework/Exceptions/SContentLoadException.cs | 4 +- src/SMAPI/Framework/GameVersion.cs | 10 ++-- src/SMAPI/Framework/IModMetadata.cs | 26 +++++----- src/SMAPI/Framework/Logging/LogFileManager.cs | 4 +- src/SMAPI/Framework/ModHelpers/ContentHelper.cs | 9 ++-- src/SMAPI/Framework/ModHelpers/DataHelper.cs | 28 ++++++----- .../Framework/ModHelpers/GameContentHelper.cs | 8 ++-- src/SMAPI/Framework/ModHelpers/ModContentHelper.cs | 6 +-- .../Framework/ModHelpers/ModRegistryHelper.cs | 13 +++-- .../Framework/ModHelpers/MultiplayerHelper.cs | 8 ++-- src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs | 26 +++++----- .../ModLoading/AssemblyDefinitionResolver.cs | 8 ++-- .../Framework/ModLoading/Finders/EventFinder.cs | 4 +- .../Framework/ModLoading/Finders/FieldFinder.cs | 4 +- .../Framework/ModLoading/Finders/MethodFinder.cs | 4 +- .../Framework/ModLoading/Finders/PropertyFinder.cs | 4 +- .../ReferenceToMemberWithUnexpectedTypeFinder.cs | 15 +++--- .../Finders/ReferenceToMissingMemberFinder.cs | 13 +++-- .../ModLoading/Finders/TypeAssemblyFinder.cs | 6 +-- .../Framework/ModLoading/Finders/TypeFinder.cs | 8 ++-- .../ModLoading/Framework/BaseInstructionHandler.cs | 4 +- .../ModLoading/Framework/RecursiveRewriter.cs | 25 +++++----- .../ModLoading/Framework/RewriteHelper.cs | 10 ++-- .../ModLoading/InvalidModStateException.cs | 4 +- src/SMAPI/Framework/ModLoading/ModMetadata.cs | 38 ++++++++------- .../ModLoading/RewriteFacades/AccessToolsFacade.cs | 6 +-- .../RewriteFacades/HarmonyInstanceFacade.cs | 9 ++-- .../RewriteFacades/HarmonyMethodFacade.cs | 6 +-- .../ModLoading/Rewriters/HarmonyRewriter.cs | 16 +++---- .../ModLoading/Rewriters/HeuristicFieldRewriter.cs | 19 ++++---- .../Rewriters/HeuristicMethodRewriter.cs | 15 +++--- .../ModLoading/Rewriters/MethodParentRewriter.cs | 13 +++-- .../ModLoading/Rewriters/TypeReferenceRewriter.cs | 6 +-- .../ModLoading/Symbols/SymbolReaderProvider.cs | 6 +-- .../Framework/ModLoading/TypeReferenceComparer.cs | 14 +++--- src/SMAPI/Framework/ModRegistry.cs | 16 +++---- src/SMAPI/Framework/Reflection/ReflectedField.cs | 16 +++---- src/SMAPI/Framework/Reflection/ReflectedMethod.cs | 18 ++++--- .../Framework/Reflection/ReflectedProperty.cs | 18 ++++--- src/SMAPI/Framework/Rendering/SDisplayDevice.cs | 8 ++-- src/SMAPI/Framework/Rendering/SXnaDisplayDevice.cs | 4 +- src/SMAPI/Framework/SGame.cs | 27 +++++------ src/SMAPI/Framework/SModHooks.cs | 4 +- src/SMAPI/Framework/SnapshotDiff.cs | 6 +-- src/SMAPI/Framework/SnapshotItemListDiff.cs | 5 +- src/SMAPI/Framework/SnapshotListDiff.cs | 4 +- src/SMAPI/Framework/StateTracking/ChestTracker.cs | 5 +- .../StateTracking/Comparers/EquatableComparer.cs | 4 +- .../Comparers/GenericEqualsComparer.cs | 4 +- .../Comparers/ObjectReferenceComparer.cs | 4 +- .../FieldWatchers/NetDictionaryWatcher.cs | 3 +- .../FieldWatchers/ObservableCollectionWatcher.cs | 8 ++-- .../StateTracking/FieldWatchers/WatcherFactory.cs | 15 +++--- .../Framework/StateTracking/LocationTracker.cs | 14 +++--- .../StateTracking/Snapshots/LocationSnapshot.cs | 4 +- .../StateTracking/Snapshots/WatcherSnapshot.cs | 6 +-- .../Snapshots/WorldLocationsSnapshot.cs | 4 +- .../StateTracking/WorldLocationsTracker.cs | 23 ++++----- src/SMAPI/Framework/Translator.cs | 20 ++++---- .../Framework/Utilities/TickCacheDictionary.cs | 5 +- src/SMAPI/Framework/WatcherCore.cs | 4 +- src/SMAPI/IAssetData.cs | 3 +- src/SMAPI/IAssetInfo.cs | 4 +- src/SMAPI/IAssetName.cs | 12 ++--- src/SMAPI/IContentHelper.cs | 14 +++--- src/SMAPI/IContentPack.cs | 11 +++-- src/SMAPI/IDataHelper.cs | 20 ++++---- src/SMAPI/IGameContentHelper.cs | 14 +++--- src/SMAPI/IMod.cs | 4 +- src/SMAPI/IModContentHelper.cs | 8 ++-- src/SMAPI/IModRegistry.cs | 9 ++-- src/SMAPI/IMultiplayerHelper.cs | 6 +-- src/SMAPI/IMultiplayerPeer.cs | 10 ++-- src/SMAPI/IReflectedField.cs | 6 +-- src/SMAPI/IReflectedMethod.cs | 6 +-- src/SMAPI/IReflectedProperty.cs | 6 +-- src/SMAPI/IReflectionHelper.cs | 30 ++++++++---- src/SMAPI/Metadata/InstructionMetadata.cs | 24 +++++----- src/SMAPI/Mod.cs | 12 ++--- src/SMAPI/Patches/Game1Patcher.cs | 6 +-- src/SMAPI/Patches/TitleMenuPatcher.cs | 4 +- src/SMAPI/Program.cs | 22 ++++----- src/SMAPI/Translation.cs | 30 ++++++------ src/SMAPI/Utilities/CaseInsensitivePathCache.cs | 4 +- src/SMAPI/Utilities/Keybind.cs | 5 +- src/SMAPI/Utilities/KeybindList.cs | 11 ++--- src/SMAPI/Utilities/SDate.cs | 55 ++++++++++------------ 111 files changed, 558 insertions(+), 677 deletions(-) (limited to 'src/SMAPI/Framework/Logging') diff --git a/src/SMAPI.Tests/Core/AssetNameTests.cs b/src/SMAPI.Tests/Core/AssetNameTests.cs index 8018442c..a1712726 100644 --- a/src/SMAPI.Tests/Core/AssetNameTests.cs +++ b/src/SMAPI.Tests/Core/AssetNameTests.cs @@ -56,7 +56,7 @@ namespace SMAPI.Tests.Core public void Constructor_NullOrWhitespace(string? name) { // act - ArgumentException exception = Assert.Throws(() => _ = AssetName.Parse(name!, null))!; + ArgumentException exception = Assert.Throws(() => _ = AssetName.Parse(name!, _ => null))!; // assert exception.ParamName.Should().Be("rawName"); diff --git a/src/SMAPI.Tests/Core/TranslationTests.cs b/src/SMAPI.Tests/Core/TranslationTests.cs index a65bf772..ced1525a 100644 --- a/src/SMAPI.Tests/Core/TranslationTests.cs +++ b/src/SMAPI.Tests/Core/TranslationTests.cs @@ -134,9 +134,9 @@ namespace SMAPI.Tests.Core // assert if (translation.HasValue()) - Assert.AreEqual(text, (string)translation, "The translation returned an unexpected value given a valid input."); + Assert.AreEqual(text, (string?)translation, "The translation returned an unexpected value given a valid input."); else - Assert.AreEqual(this.GetPlaceholderText("key"), (string)translation, "The translation returned an unexpected value given a null or empty input."); + Assert.AreEqual(this.GetPlaceholderText("key"), (string?)translation, "The translation returned an unexpected value given a null or empty input."); } [Test(Description = "Assert that the translation returns the expected text given a use-placeholder setting.")] diff --git a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs index e9ece387..ab0e4377 100644 --- a/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs +++ b/src/SMAPI.Toolkit/Framework/ModData/ModDataRecord.cs @@ -80,7 +80,7 @@ namespace StardewModdingAPI.Toolkit.Framework.ModData /// Get a parsed representation of the which match a given manifest. /// The manifest to match. - public ModDataRecordVersionedFields GetVersionedFields(IManifest manifest) + public ModDataRecordVersionedFields GetVersionedFields(IManifest? manifest) { ModDataRecordVersionedFields parsed = new(this); foreach (ModDataField field in this.Fields.Where(field => field.IsMatch(manifest))) diff --git a/src/SMAPI/Constants.cs b/src/SMAPI/Constants.cs index 2d9ab666..fd2b813a 100644 --- a/src/SMAPI/Constants.cs +++ b/src/SMAPI/Constants.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -33,7 +31,7 @@ namespace StardewModdingAPI ** Accessors *********/ /// The path to the game folder. - public static string GamePath { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + public static string GamePath { get; } = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; /// The absolute path to the folder containing SMAPI's internal files. public static readonly string InternalFilesPath = Path.Combine(EarlyConstants.GamePath, "smapi-internal"); @@ -69,8 +67,8 @@ namespace StardewModdingAPI /// The minimum supported version of Stardew Valley. public static ISemanticVersion MinimumGameVersion { get; } = new GameVersion("1.5.6"); - /// The maximum supported version of Stardew Valley. - public static ISemanticVersion MaximumGameVersion { get; } = null; + /// The maximum supported version of Stardew Valley, if any. + public static ISemanticVersion? MaximumGameVersion { get; } = null; /// The target game platform. public static GamePlatform TargetPlatform { get; } = EarlyConstants.Platform; @@ -111,10 +109,10 @@ namespace StardewModdingAPI public static string SavesPath { get; } = Path.Combine(Constants.DataPath, "Saves"); /// The name of the current save folder (if save info is available, regardless of whether the save file exists yet). - public static string SaveFolderName => Constants.GetSaveFolderName(); + public static string? SaveFolderName => Constants.GetSaveFolderName(); /// The absolute path to the current save folder (if save info is available and the save file exists). - public static string CurrentSavePath => Constants.GetSaveFolderPathIfExists(); + public static string? CurrentSavePath => Constants.GetSaveFolderPathIfExists(); /**** ** Internal @@ -164,7 +162,7 @@ namespace StardewModdingAPI internal static string DefaultModsPath { get; } = Path.Combine(Constants.GamePath, "Mods"); /// The actual full path to search for mods. - internal static string ModsPath { get; set; } + internal static string ModsPath { get; set; } = null!; // initialized early during SMAPI startup /// The game's current semantic version. internal static ISemanticVersion GameVersion { get; } = new GameVersion(Game1.version); @@ -179,7 +177,7 @@ namespace StardewModdingAPI /// Get the SMAPI version to recommend for an older game version, if any. /// The game version to search. /// Returns the compatible SMAPI version, or null if none was found. - internal static ISemanticVersion GetCompatibleApiVersion(ISemanticVersion version) + internal static ISemanticVersion? GetCompatibleApiVersion(ISemanticVersion version) { // This covers all officially supported public game updates. It might seem like version // ranges would be better, but the given SMAPI versions may not be compatible with @@ -337,22 +335,22 @@ namespace StardewModdingAPI } /// Get the name of the save folder, if any. - private static string GetSaveFolderName() + private static string? GetSaveFolderName() { return Constants.GetSaveFolder()?.Name; } /// Get the absolute path to the current save folder, if any. - private static string GetSaveFolderPathIfExists() + private static string? GetSaveFolderPathIfExists() { - DirectoryInfo saveFolder = Constants.GetSaveFolder(); + DirectoryInfo? saveFolder = Constants.GetSaveFolder(); return saveFolder?.Exists == true ? saveFolder.FullName : null; } /// Get the current save folder, if any. - private static DirectoryInfo GetSaveFolder() + private static DirectoryInfo? GetSaveFolder() { // save not available if (Context.LoadStage == LoadStage.None) @@ -365,7 +363,7 @@ namespace StardewModdingAPI : Game1.uniqueIDForThisGame; // get best match (accounting for rare case where folder name isn't sanitized) - DirectoryInfo folder = null; + DirectoryInfo? folder = null; foreach (string saveName in new[] { rawSaveName, new string(rawSaveName.Where(char.IsLetterOrDigit).ToArray()) }) { try diff --git a/src/SMAPI/Events/AssetRequestedEventArgs.cs b/src/SMAPI/Events/AssetRequestedEventArgs.cs index 3c51c95d..3bcf83b9 100644 --- a/src/SMAPI/Events/AssetRequestedEventArgs.cs +++ b/src/SMAPI/Events/AssetRequestedEventArgs.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Events private readonly IModMetadata Mod; /// Get the mod metadata for a content pack, if it's a valid content pack for the mod. - private readonly Func GetOnBehalfOf; + private readonly Func GetOnBehalfOf; /********* @@ -51,7 +49,7 @@ namespace StardewModdingAPI.Events /// The requested data type. /// The with any locale codes stripped. /// Get the mod metadata for a content pack, if it's a valid content pack for the mod. - internal AssetRequestedEventArgs(IModMetadata mod, IAssetName name, IAssetName nameWithoutLocale, Type dataType, Func getOnBehalfOf) + internal AssetRequestedEventArgs(IModMetadata mod, IAssetName name, IAssetName nameWithoutLocale, Type dataType, Func getOnBehalfOf) { this.Mod = mod; this.Name = name; @@ -71,7 +69,7 @@ namespace StardewModdingAPI.Events /// Each asset can logically only have one initial instance. If multiple loads apply at the same time, SMAPI will use the parameter to decide what happens. If you're making changes to the existing asset instead of replacing it, you should use instead to avoid those limitations and improve mod compatibility. /// /// - public void LoadFrom(Func load, AssetLoadPriority priority, string onBehalfOf = null) + public void LoadFrom(Func load, AssetLoadPriority priority, string? onBehalfOf = null) { this.LoadOperations.Add( new AssetLoadOperation( @@ -95,13 +93,15 @@ namespace StardewModdingAPI.Events /// /// public void LoadFromModFile(string relativePath, AssetLoadPriority priority) + where TAsset : notnull { this.LoadOperations.Add( new AssetLoadOperation( mod: this.Mod, priority: priority, onBehalfOf: null, - _ => this.Mod.Mod.Helper.ModContent.Load(relativePath)) + _ => this.Mod.Mod!.Helper.ModContent.Load(relativePath) + ) ); } @@ -116,7 +116,7 @@ namespace StardewModdingAPI.Events /// You can apply any number of edits to the asset. Each edit will be applied on top of the previous one (i.e. it'll see the merged asset from all previous edits as its input). /// /// - public void Edit(Action apply, AssetEditPriority priority = AssetEditPriority.Default, string onBehalfOf = null) + public void Edit(Action apply, AssetEditPriority priority = AssetEditPriority.Default, string? onBehalfOf = null) { this.EditOperations.Add( new AssetEditOperation( diff --git a/src/SMAPI/Events/MenuChangedEventArgs.cs b/src/SMAPI/Events/MenuChangedEventArgs.cs index 362accec..c37fd216 100644 --- a/src/SMAPI/Events/MenuChangedEventArgs.cs +++ b/src/SMAPI/Events/MenuChangedEventArgs.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewValley.Menus; @@ -11,20 +9,20 @@ namespace StardewModdingAPI.Events /********* ** Accessors *********/ - /// The previous menu. - public IClickableMenu OldMenu { get; } + /// The previous menu, if any. + public IClickableMenu? OldMenu { get; } - /// The current menu. - public IClickableMenu NewMenu { get; } + /// The current menu, if any. + public IClickableMenu? NewMenu { get; } /********* ** Public methods *********/ /// Construct an instance. - /// The previous menu. - /// The current menu. - internal MenuChangedEventArgs(IClickableMenu oldMenu, IClickableMenu newMenu) + /// The previous menu, if any. + /// The current menu, if any. + internal MenuChangedEventArgs(IClickableMenu? oldMenu, IClickableMenu? newMenu) { this.OldMenu = oldMenu; this.NewMenu = newMenu; diff --git a/src/SMAPI/Framework/Command.cs b/src/SMAPI/Framework/Command.cs index 776ba238..dca1dd09 100644 --- a/src/SMAPI/Framework/Command.cs +++ b/src/SMAPI/Framework/Command.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI.Framework @@ -11,7 +9,7 @@ namespace StardewModdingAPI.Framework ** Accessor *********/ /// The mod that registered the command (or null if registered by SMAPI). - public IModMetadata Mod { get; } + public IModMetadata? Mod { get; } /// The command name, which the user must type to trigger it. public string Name { get; } @@ -31,7 +29,7 @@ namespace StardewModdingAPI.Framework /// The command name, which the user must type to trigger it. /// The human-readable documentation shown when the player runs the built-in 'help' command. /// The method to invoke when the command is triggered. This method is passed the command name and arguments submitted by the user. - public Command(IModMetadata mod, string name, string documentation, Action callback) + public Command(IModMetadata? mod, string name, string documentation, Action callback) { this.Mod = mod; this.Name = name; diff --git a/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs b/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs index fcfa928e..6dc6f131 100644 --- a/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs +++ b/src/SMAPI/Framework/Commands/HarmonySummaryCommand.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -73,9 +71,9 @@ namespace StardewModdingAPI.Framework.Commands private IEnumerable FilterPatches(string[] searchTerms) { bool hasSearch = searchTerms.Any(); - bool IsMatch(string target) => !hasSearch || searchTerms.Any(search => target != null && target.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); + bool IsMatch(string? target) => !hasSearch || searchTerms.Any(search => target != null && target.IndexOf(search, StringComparison.OrdinalIgnoreCase) > -1); - foreach (var patch in this.GetAllPatches()) + foreach (SearchResult patch in this.GetAllPatches()) { // matches entire patch if (IsMatch(patch.MethodDescription)) @@ -85,10 +83,10 @@ namespace StardewModdingAPI.Framework.Commands } // matches individual patchers - foreach (var pair in patch.PatchTypesByOwner.ToArray()) + foreach ((string patcherId, ISet patchTypes) in patch.PatchTypesByOwner.ToArray()) { - if (!IsMatch(pair.Key) && !pair.Value.Any(type => IsMatch(type.ToString()))) - patch.PatchTypesByOwner.Remove(pair.Key); + if (!IsMatch(patcherId) && !patchTypes.Any(type => IsMatch(type.ToString()))) + patch.PatchTypesByOwner.Remove(patcherId); } if (patch.PatchTypesByOwner.Any()) @@ -114,13 +112,13 @@ namespace StardewModdingAPI.Framework.Commands // get patch types by owner var typesByOwner = new Dictionary>(); - foreach (var group in patchGroups) + foreach ((PatchType type, IReadOnlyCollection patches) in patchGroups) { - foreach (var patch in group.Value) + foreach (Patch patch in patches) { - if (!typesByOwner.TryGetValue(patch.owner, out ISet patchTypes)) + if (!typesByOwner.TryGetValue(patch.owner, out ISet? patchTypes)) typesByOwner[patch.owner] = patchTypes = new HashSet(); - patchTypes.Add(group.Key); + patchTypes.Add(type); } } diff --git a/src/SMAPI/Framework/Content/AssetData.cs b/src/SMAPI/Framework/Content/AssetData.cs index be4a7ce6..0367e999 100644 --- a/src/SMAPI/Framework/Content/AssetData.cs +++ b/src/SMAPI/Framework/Content/AssetData.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI.Framework.Content @@ -7,12 +5,13 @@ namespace StardewModdingAPI.Framework.Content /// Base implementation for a content helper which encapsulates access and changes to content being read from a data file. /// The interface value type. internal class AssetData : AssetInfo, IAssetData + where TValue : notnull { /********* ** Fields *********/ /// A callback to invoke when the data is replaced (if any). - private readonly Action OnDataReplaced; + private readonly Action? OnDataReplaced; /********* @@ -31,7 +30,7 @@ namespace StardewModdingAPI.Framework.Content /// The content data being read. /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetData(string locale, IAssetName assetName, TValue data, Func getNormalizedPath, Action onDataReplaced) + public AssetData(string? locale, IAssetName assetName, TValue data, Func getNormalizedPath, Action? onDataReplaced) : base(locale, assetName, data.GetType(), getNormalizedPath) { this.Data = data; diff --git a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs index 06dbe259..d9bfa7bf 100644 --- a/src/SMAPI/Framework/Content/AssetDataForDictionary.cs +++ b/src/SMAPI/Framework/Content/AssetDataForDictionary.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; @@ -17,7 +15,7 @@ namespace StardewModdingAPI.Framework.Content /// The content data being read. /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetDataForDictionary(string locale, IAssetName assetName, IDictionary data, Func getNormalizedPath, Action> onDataReplaced) + public AssetDataForDictionary(string? locale, IAssetName assetName, IDictionary data, Func getNormalizedPath, Action> onDataReplaced) : base(locale, assetName, data, getNormalizedPath, onDataReplaced) { } } } diff --git a/src/SMAPI/Framework/Content/AssetDataForImage.cs b/src/SMAPI/Framework/Content/AssetDataForImage.cs index 8e59cd27..97729c95 100644 --- a/src/SMAPI/Framework/Content/AssetDataForImage.cs +++ b/src/SMAPI/Framework/Content/AssetDataForImage.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; @@ -27,7 +25,7 @@ namespace StardewModdingAPI.Framework.Content /// The content data being read. /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). - public AssetDataForImage(string locale, IAssetName assetName, Texture2D data, Func getNormalizedPath, Action onDataReplaced) + public AssetDataForImage(string? locale, IAssetName assetName, Texture2D data, Func getNormalizedPath, Action onDataReplaced) : base(locale, assetName, data, getNormalizedPath, onDataReplaced) { } /// diff --git a/src/SMAPI/Framework/Content/AssetDataForObject.cs b/src/SMAPI/Framework/Content/AssetDataForObject.cs index bb3966b9..e508ca30 100644 --- a/src/SMAPI/Framework/Content/AssetDataForObject.cs +++ b/src/SMAPI/Framework/Content/AssetDataForObject.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; @@ -27,7 +25,7 @@ namespace StardewModdingAPI.Framework.Content /// The content data being read. /// Normalizes an asset key to match the cache key. /// Simplifies access to private code. - public AssetDataForObject(string locale, IAssetName assetName, object data, Func getNormalizedPath, Reflector reflection) + public AssetDataForObject(string? locale, IAssetName assetName, object data, Func getNormalizedPath, Reflector reflection) : base(locale, assetName, data, getNormalizedPath, onDataReplaced: null) { this.Reflection = reflection; diff --git a/src/SMAPI/Framework/Content/AssetEditOperation.cs b/src/SMAPI/Framework/Content/AssetEditOperation.cs index 1b7d0c93..464948b0 100644 --- a/src/SMAPI/Framework/Content/AssetEditOperation.cs +++ b/src/SMAPI/Framework/Content/AssetEditOperation.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewModdingAPI.Events; @@ -18,7 +16,7 @@ namespace StardewModdingAPI.Framework.Content public AssetEditPriority Priority { get; } /// The content pack on whose behalf the edit is being applied, if any. - public IModMetadata OnBehalfOf { get; } + public IModMetadata? OnBehalfOf { get; } /// Apply the edit to an asset. public Action ApplyEdit { get; } @@ -32,7 +30,7 @@ namespace StardewModdingAPI.Framework.Content /// If there are multiple edits that apply to the same asset, the priority with which this one should be applied. /// The content pack on whose behalf the edit is being applied, if any. /// Apply the edit to an asset. - public AssetEditOperation(IModMetadata mod, AssetEditPriority priority, IModMetadata onBehalfOf, Action applyEdit) + public AssetEditOperation(IModMetadata mod, AssetEditPriority priority, IModMetadata? onBehalfOf, Action applyEdit) { this.Mod = mod; this.Priority = priority; diff --git a/src/SMAPI/Framework/Content/AssetInfo.cs b/src/SMAPI/Framework/Content/AssetInfo.cs index 51dcc61f..0f0e9bf3 100644 --- a/src/SMAPI/Framework/Content/AssetInfo.cs +++ b/src/SMAPI/Framework/Content/AssetInfo.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Framework.Content ** Accessors *********/ /// - public string Locale { get; } + public string? Locale { get; } /// public IAssetName Name { get; } @@ -28,7 +26,7 @@ namespace StardewModdingAPI.Framework.Content public IAssetName NameWithoutLocale { get; } /// - [Obsolete($"Use {nameof(Name)} or {nameof(NameWithoutLocale)} instead. This property will be removed in SMAPI 4.0.0.")] + [Obsolete($"Use {nameof(AssetInfo.Name)} or {nameof(AssetInfo.NameWithoutLocale)} instead. This property will be removed in SMAPI 4.0.0.")] public string AssetName { get @@ -56,7 +54,7 @@ namespace StardewModdingAPI.Framework.Content /// The asset name being read. /// The content type being read. /// Normalizes an asset key to match the cache key. - public AssetInfo(string locale, IAssetName assetName, Type type, Func getNormalizedPath) + public AssetInfo(string? locale, IAssetName assetName, Type type, Func getNormalizedPath) { this.Locale = locale; this.Name = assetName; @@ -66,7 +64,7 @@ namespace StardewModdingAPI.Framework.Content } /// - [Obsolete($"Use {nameof(Name)}.{nameof(IAssetName.IsEquivalentTo)} or {nameof(NameWithoutLocale)}.{nameof(IAssetName.IsEquivalentTo)} instead. This method will be removed in SMAPI 4.0.0.")] + [Obsolete($"Use {nameof(Name)}.{nameof(IAssetName.IsEquivalentTo)} or {nameof(AssetInfo.NameWithoutLocale)}.{nameof(IAssetName.IsEquivalentTo)} instead. This method will be removed in SMAPI 4.0.0.")] public bool AssetNameEquals(string path) { SCore.DeprecationManager.Warn( @@ -106,7 +104,7 @@ namespace StardewModdingAPI.Framework.Content return "string"; // default - return type.FullName; + return type.FullName!; } } } diff --git a/src/SMAPI/Framework/Content/AssetInterceptorChange.cs b/src/SMAPI/Framework/Content/AssetInterceptorChange.cs index 7f53db9b..fc8199e8 100644 --- a/src/SMAPI/Framework/Content/AssetInterceptorChange.cs +++ b/src/SMAPI/Framework/Content/AssetInterceptorChange.cs @@ -1,9 +1,8 @@ -#nullable disable - using System; using System.Reflection; using StardewModdingAPI.Internal; +#pragma warning disable CS0618 // obsolete asset interceptors deliberately supported here namespace StardewModdingAPI.Framework.Content { /// A wrapper for and for internal cache invalidation. @@ -46,11 +45,11 @@ namespace StardewModdingAPI.Framework.Content /// Basic metadata about the asset being loaded. public bool CanIntercept(IAssetInfo asset) { - MethodInfo canIntercept = this.GetType().GetMethod(nameof(this.CanInterceptImpl), BindingFlags.Instance | BindingFlags.NonPublic); + MethodInfo? canIntercept = this.GetType().GetMethod(nameof(this.CanInterceptImpl), BindingFlags.Instance | BindingFlags.NonPublic); if (canIntercept == null) throw new InvalidOperationException($"SMAPI couldn't access the {nameof(AssetInterceptorChange)}.{nameof(this.CanInterceptImpl)} implementation."); - return (bool)canIntercept.MakeGenericMethod(asset.DataType).Invoke(this, new object[] { asset }); + return (bool)canIntercept.MakeGenericMethod(asset.DataType).Invoke(this, new object[] { asset })!; } diff --git a/src/SMAPI/Framework/Content/AssetLoadOperation.cs b/src/SMAPI/Framework/Content/AssetLoadOperation.cs index 73e60e24..b6cdec27 100644 --- a/src/SMAPI/Framework/Content/AssetLoadOperation.cs +++ b/src/SMAPI/Framework/Content/AssetLoadOperation.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewModdingAPI.Events; @@ -15,7 +13,7 @@ namespace StardewModdingAPI.Framework.Content public IModMetadata Mod { get; } /// The content pack on whose behalf the asset is being loaded, if any. - public IModMetadata OnBehalfOf { get; } + public IModMetadata? OnBehalfOf { get; } /// If there are multiple loads that apply to the same asset, the priority with which this one should be applied. public AssetLoadPriority Priority { get; } @@ -32,7 +30,7 @@ namespace StardewModdingAPI.Framework.Content /// If there are multiple loads that apply to the same asset, the priority with which this one should be applied. /// The content pack on whose behalf the asset is being loaded, if any. /// Load the initial value for an asset. - public AssetLoadOperation(IModMetadata mod, AssetLoadPriority priority, IModMetadata onBehalfOf, Func getData) + public AssetLoadOperation(IModMetadata mod, AssetLoadPriority priority, IModMetadata? onBehalfOf, Func getData) { this.Mod = mod; this.Priority = priority; diff --git a/src/SMAPI/Framework/ContentCoordinator.cs b/src/SMAPI/Framework/ContentCoordinator.cs index 4e48b08c..92452224 100644 --- a/src/SMAPI/Framework/ContentCoordinator.cs +++ b/src/SMAPI/Framework/ContentCoordinator.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -71,7 +69,7 @@ namespace StardewModdingAPI.Framework private readonly ReaderWriterLockSlim ContentManagerLock = new(); /// A cache of ordered tilesheet IDs used by vanilla maps. - private readonly Dictionary VanillaTilesheets = new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary VanillaTilesheets = new(StringComparer.OrdinalIgnoreCase); /// An unmodified content manager which doesn't intercept assets, used to compare asset data. private readonly LocalizedContentManager VanillaContentManager; @@ -230,7 +228,7 @@ namespace StardewModdingAPI.Framework public void OnAdditionalLanguagesInitialized() { // update locale cache for custom languages, and load it now (since languages added later won't work) - var customLanguages = this.MainContentManager.Load>("Data/AdditionalLanguages"); + var customLanguages = this.MainContentManager.Load>("Data/AdditionalLanguages"); this.LocaleCodes = new Lazy>(() => this.GetLocaleCodes(customLanguages)); _ = this.LocaleCodes.Value; } @@ -303,7 +301,7 @@ namespace StardewModdingAPI.Framework /// The unique name for the content manager which should load this asset. /// The asset name within the mod folder. /// Returns whether the asset was parsed successfully. - public bool TryParseManagedAssetKey(string key, out string contentManagerID, out IAssetName relativePath) + public bool TryParseManagedAssetKey(string key, [NotNullWhen(true)] out string? contentManagerID, [NotNullWhen(true)] out IAssetName? relativePath) { contentManagerID = null; relativePath = null; @@ -333,9 +331,10 @@ namespace StardewModdingAPI.Framework /// The unique name for the content manager which should load this asset. /// The asset name within the mod folder. public bool DoesManagedAssetExist(string contentManagerID, IAssetName assetName) + where T : notnull { // get content manager - IContentManager contentManager = this.ContentManagerLock.InReadLock(() => + IContentManager? contentManager = this.ContentManagerLock.InReadLock(() => this.ContentManagers.FirstOrDefault(p => p.IsNamespaced && p.Name == contentManagerID) ); if (contentManager == null) @@ -350,9 +349,10 @@ namespace StardewModdingAPI.Framework /// The unique name for the content manager which should load this asset. /// The asset name within the mod folder. public T LoadManagedAsset(string contentManagerID, IAssetName relativePath) + where T : notnull { // get content manager - IContentManager contentManager = this.ContentManagerLock.InReadLock(() => + IContentManager? contentManager = this.ContentManagerLock.InReadLock(() => this.ContentManagers.FirstOrDefault(p => p.IsNamespaced && p.Name == contentManagerID) ); if (contentManager == null) @@ -461,6 +461,7 @@ namespace StardewModdingAPI.Framework /// The asset type. /// The asset info to load or edit. public IEnumerable GetAssetOperations(IAssetInfo info) + where T : notnull { return this.AssetOperationsByKey.GetOrSet( info.Name, @@ -491,7 +492,7 @@ namespace StardewModdingAPI.Framework { rootPath = PathUtilities.NormalizePath(rootPath); - if (!this.CaseInsensitivePathCaches.TryGetValue(rootPath, out CaseInsensitivePathCache cache)) + if (!this.CaseInsensitivePathCaches.TryGetValue(rootPath, out CaseInsensitivePathCache? cache)) this.CaseInsensitivePathCaches[rootPath] = cache = new CaseInsensitivePathCache(rootPath); return cache; @@ -501,9 +502,9 @@ namespace StardewModdingAPI.Framework /// The asset path relative to the loader root directory, not including the .xnb extension. public TilesheetReference[] GetVanillaTilesheetIds(string assetName) { - if (!this.VanillaTilesheets.TryGetValue(assetName, out TilesheetReference[] tilesheets)) + if (!this.VanillaTilesheets.TryGetValue(assetName, out TilesheetReference[]? tilesheets)) { - tilesheets = this.TryLoadVanillaAsset(assetName, out Map map) + tilesheets = this.TryLoadVanillaAsset(assetName, out Map? map) ? map.TileSheets.Select((sheet, index) => new TilesheetReference(index, sheet.Id, sheet.ImageSource, sheet.SheetSize, sheet.TileSize)).ToArray() : null; @@ -516,7 +517,7 @@ namespace StardewModdingAPI.Framework /// Get the locale code which corresponds to a language enum (e.g. fr-FR given ). /// The language enum to search. - public string GetLocaleCode(LocalizedContentManager.LanguageCode language) + public string? GetLocaleCode(LocalizedContentManager.LanguageCode language) { if (language == LocalizedContentManager.LanguageCode.mod && LocalizedContentManager.CurrentModLanguage == null) return null; @@ -535,7 +536,7 @@ namespace StardewModdingAPI.Framework foreach (IContentManager contentManager in this.ContentManagers) contentManager.Dispose(); this.ContentManagers.Clear(); - this.MainContentManager = null; + this.MainContentManager = null!; // instance no longer usable this.ContentManagerLock.Dispose(); } @@ -560,7 +561,8 @@ namespace StardewModdingAPI.Framework /// The type of asset to load. /// The asset path relative to the loader root directory, not including the .xnb extension. /// The loaded asset data. - private bool TryLoadVanillaAsset(string assetName, out T asset) + private bool TryLoadVanillaAsset(string assetName, [NotNullWhen(true)] out T? asset) + where T : notnull { try { @@ -576,12 +578,12 @@ namespace StardewModdingAPI.Framework /// Get the language enums (like ) indexed by locale code (like ja-JP). /// The custom languages to add to the lookup. - private Dictionary GetLocaleCodes(IEnumerable customLanguages) + private Dictionary GetLocaleCodes(IEnumerable customLanguages) { var map = new Dictionary(StringComparer.OrdinalIgnoreCase); // custom languages - foreach (ModLanguage language in customLanguages) + foreach (ModLanguage? language in customLanguages) { if (!string.IsNullOrWhiteSpace(language?.LanguageCode)) map[language.LanguageCode] = LocalizedContentManager.LanguageCode.mod; @@ -590,7 +592,7 @@ namespace StardewModdingAPI.Framework // vanilla languages (override custom language if they conflict) foreach (LocalizedContentManager.LanguageCode code in Enum.GetValues(typeof(LocalizedContentManager.LanguageCode))) { - string locale = this.GetLocaleCode(code); + string? locale = this.GetLocaleCode(code); if (locale != null) map[locale] = code; } @@ -602,6 +604,7 @@ namespace StardewModdingAPI.Framework /// The asset type. /// The asset info to load or edit. private IEnumerable GetAssetOperationsWithoutCache(IAssetInfo info) + where T : notnull { IAssetInfo legacyInfo = this.GetLegacyAssetInfo(info); diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs index e494559d..6469fea4 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManager.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; @@ -70,7 +69,7 @@ namespace StardewModdingAPI.Framework.ContentManagers return true; // managed asset - if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string contentManagerID, out IAssetName relativePath)) + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) return this.Coordinator.DoesManagedAssetExist(contentManagerID, relativePath); // custom asset from a loader @@ -78,7 +77,7 @@ namespace StardewModdingAPI.Framework.ContentManagers IAssetInfo info = new AssetInfo(locale, assetName, typeof(T), this.AssertAndNormalizeAssetName); AssetLoadOperation[] loaders = this.GetLoaders(info).ToArray(); - if (!this.AssertMaxOneRequiredLoader(info, loaders, out string error)) + if (!this.AssertMaxOneRequiredLoader(info, loaders, out string? error)) { this.Monitor.Log(error, LogLevel.Warn); return false; @@ -102,7 +101,7 @@ namespace StardewModdingAPI.Framework.ContentManagers return this.RawLoad(assetName, useCache: true); // get managed asset - if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string contentManagerID, out IAssetName relativePath)) + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) { T managedAsset = this.Coordinator.LoadManagedAsset(contentManagerID, relativePath); this.TrackAsset(assetName, managedAsset, useCache); @@ -151,14 +150,15 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Load the initial asset from the registered loaders. /// The basic asset metadata. /// Returns the loaded asset metadata, or null if no loader matched. - private IAssetData ApplyLoader(IAssetInfo info) + private IAssetData? ApplyLoader(IAssetInfo info) + where T : notnull { // find matching loader - AssetLoadOperation loader; + AssetLoadOperation? loader; { AssetLoadOperation[] loaders = this.GetLoaders(info).OrderByDescending(p => p.Priority).ToArray(); - if (!this.AssertMaxOneRequiredLoader(info, loaders, out string error)) + if (!this.AssertMaxOneRequiredLoader(info, loaders, out string? error)) { this.Monitor.Log(error, LogLevel.Warn); return null; @@ -196,20 +196,21 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The basic asset metadata. /// The loaded asset. private IAssetData ApplyEditors(IAssetInfo info, IAssetData asset) + where T : notnull { IAssetData GetNewData(object data) => new AssetDataForObject(info, data, this.AssertAndNormalizeAssetName, this.Reflection); // special case: if the asset was loaded with a more general type like 'object', call editors with the actual type instead. { Type actualType = asset.Data.GetType(); - Type actualOpenType = actualType.IsGenericType ? actualType.GetGenericTypeDefinition() : null; + Type? actualOpenType = actualType.IsGenericType ? actualType.GetGenericTypeDefinition() : null; if (typeof(T) != actualType && (actualOpenType == typeof(Dictionary<,>) || actualOpenType == typeof(List<>) || actualType == typeof(Texture2D) || actualType == typeof(Map))) { return (IAssetData)this.GetType() .GetMethod(nameof(this.ApplyEditors), BindingFlags.NonPublic | BindingFlags.Instance)! .MakeGenericMethod(actualType) - .Invoke(this, new object[] { info, asset }); + .Invoke(this, new object[] { info, asset })!; } } @@ -232,6 +233,7 @@ namespace StardewModdingAPI.Framework.ContentManagers } // validate edit + // ReSharper disable once ConditionIsAlwaysTrueOrFalse -- it's only guaranteed non-null after this method if (asset.Data == null) { mod.LogAsMod($"Mod incorrectly set asset '{info.Name}'{this.GetOnBehalfOfLabel(editor.OnBehalfOf)} to a null value; ignoring override.", LogLevel.Warn); @@ -252,6 +254,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset type. /// The basic asset metadata. private IEnumerable GetLoaders(IAssetInfo info) + where T : notnull { return this.Coordinator .GetAssetOperations(info) @@ -262,6 +265,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset type. /// The basic asset metadata. private IEnumerable GetEditors(IAssetInfo info) + where T : notnull { return this.Coordinator .GetAssetOperations(info) @@ -273,7 +277,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset loaders to apply. /// The error message to show to the user, if the method returns false. /// Returns true if only one loader will apply, else false. - private bool AssertMaxOneRequiredLoader(IAssetInfo info, AssetLoadOperation[] loaders, out string error) + private bool AssertMaxOneRequiredLoader(IAssetInfo info, AssetLoadOperation[] loaders, [NotNullWhen(false)] out string? error) { AssetLoadOperation[] required = loaders.Where(p => p.Priority == AssetLoadPriority.Exclusive).ToArray(); if (required.Length <= 1) @@ -299,7 +303,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The content pack on whose behalf the action is being performed. /// whether to format the label as a parenthetical shown after the mod name like (for the 'X' content pack), instead of a standalone label like the 'X' content pack. /// Returns the on-behalf-of label if applicable, else null. - private string GetOnBehalfOfLabel(IModMetadata onBehalfOf, bool parenthetical = true) + [return: NotNullIfNotNull("onBehalfOf")] + private string? GetOnBehalfOfLabel(IModMetadata? onBehalfOf, bool parenthetical = true) { if (onBehalfOf == null) return null; @@ -315,7 +320,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The loaded asset data. /// The loader which loaded the asset. /// Returns whether the asset passed validation checks (after any fixes were applied). - private bool TryFixAndValidateLoadedAsset(IAssetInfo info, T data, AssetLoadOperation loader) + private bool TryFixAndValidateLoadedAsset(IAssetInfo info, [NotNullWhen(true)] T? data, AssetLoadOperation loader) + where T : notnull { IModMetadata mod = loader.Mod; @@ -335,7 +341,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // add missing tilesheet if (loadedMap.GetTileSheet(vanillaSheet.Id) == null) { - mod.Monitor.LogOnce("SMAPI fixed maps loaded by this mod to prevent errors. See the log file for details.", LogLevel.Warn); + mod.Monitor!.LogOnce("SMAPI fixed maps loaded by this mod to prevent errors. See the log file for details.", LogLevel.Warn); this.Monitor.Log($"Fixed broken map replacement: {mod.DisplayName} loaded '{info.Name}' without a required tilesheet (id: {vanillaSheet.Id}, source: {vanillaSheet.ImageSource})."); loadedMap.AddTileSheet(new TileSheet(vanillaSheet.Id, loadedMap, vanillaSheet.ImageSource, vanillaSheet.SheetSize, vanillaSheet.TileSize)); diff --git a/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs b/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs index 46d5d24e..1b0e1016 100644 --- a/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs +++ b/src/SMAPI/Framework/ContentManagers/GameContentManagerForAssetPropagation.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Globalization; using Microsoft.Xna.Framework.Graphics; @@ -39,7 +37,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Get whether a texture was loaded by this content manager. /// The texture to check. - public bool IsResponsibleFor(Texture2D texture) + public bool IsResponsibleFor(Texture2D? texture) { return texture?.Tag is string tag diff --git a/src/SMAPI/Framework/ContentManagers/IContentManager.cs b/src/SMAPI/Framework/ContentManagers/IContentManager.cs index c8b2ae64..ac67cad5 100644 --- a/src/SMAPI/Framework/ContentManagers/IContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/IContentManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Microsoft.Xna.Framework.Content; @@ -33,25 +31,28 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Get whether an asset exists and can be loaded. /// The expected asset type. /// The normalized asset name. - bool DoesAssetExist(IAssetName assetName); + bool DoesAssetExist(IAssetName assetName) + where T: notnull; /// Load an asset through the content pipeline, using a localized variant of the if available. /// The type of asset to load. /// The asset name relative to the loader root directory. /// The language for which to load the asset. /// Whether to read/write the loaded asset to the asset cache. - T LoadLocalized(IAssetName assetName, LocalizedContentManager.LanguageCode language, bool useCache); + T LoadLocalized(IAssetName assetName, LocalizedContentManager.LanguageCode language, bool useCache) + where T : notnull; /// Load an asset through the content pipeline, using the exact asset name without checking for localized variants. /// The type of asset to load. /// The asset name relative to the loader root directory. /// Whether to read/write the loaded asset to the asset cache. - T LoadExact(IAssetName assetName, bool useCache); + T LoadExact(IAssetName assetName, bool useCache) + where T : notnull; /// Assert that the given key has a valid format and return a normalized form consistent with the underlying cache. /// The asset key to check. /// The asset key is empty or contains invalid characters. - string AssertAndNormalizeAssetName(string assetName); + string AssertAndNormalizeAssetName(string? assetName); /// Get the current content locale. string GetLocale(); diff --git a/src/SMAPI/Framework/ContentPack.cs b/src/SMAPI/Framework/ContentPack.cs index 2d33a22e..2cfd5cce 100644 --- a/src/SMAPI/Framework/ContentPack.cs +++ b/src/SMAPI/Framework/ContentPack.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.IO; using StardewModdingAPI.Framework.ModHelpers; @@ -69,12 +67,12 @@ namespace StardewModdingAPI.Framework } /// - public TModel ReadJsonFile(string path) where TModel : class + public TModel? ReadJsonFile(string path) where TModel : class { path = PathUtilities.NormalizePath(path); FileInfo file = this.GetFile(path); - return file.Exists && this.JsonHelper.ReadJsonFileIfExists(file.FullName, out TModel model) + return file.Exists && this.JsonHelper.ReadJsonFileIfExists(file.FullName, out TModel? model) ? model : null; } @@ -93,6 +91,7 @@ namespace StardewModdingAPI.Framework /// [Obsolete] public T LoadAsset(string key) + where T : notnull { return this.ModContent.Load(key); } @@ -101,7 +100,7 @@ namespace StardewModdingAPI.Framework [Obsolete] public string GetActualAssetKey(string key) { - return this.ModContent.GetInternalAssetName(key)?.Name; + return this.ModContent.GetInternalAssetName(key).Name; } diff --git a/src/SMAPI/Framework/CursorPosition.cs b/src/SMAPI/Framework/CursorPosition.cs index 8f36a554..24084830 100644 --- a/src/SMAPI/Framework/CursorPosition.cs +++ b/src/SMAPI/Framework/CursorPosition.cs @@ -1,5 +1,3 @@ -#nullable disable - using Microsoft.Xna.Framework; using StardewValley; @@ -41,7 +39,7 @@ namespace StardewModdingAPI.Framework } /// - public bool Equals(ICursorPosition other) + public bool Equals(ICursorPosition? other) { return other != null && this.AbsolutePixels == other.AbsolutePixels; } diff --git a/src/SMAPI/Framework/Events/ManagedEvent.cs b/src/SMAPI/Framework/Events/ManagedEvent.cs index 8fa31165..4b8a770d 100644 --- a/src/SMAPI/Framework/Events/ManagedEvent.cs +++ b/src/SMAPI/Framework/Events/ManagedEvent.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -23,7 +21,7 @@ namespace StardewModdingAPI.Framework.Events private readonly List> Handlers = new(); /// A cached snapshot of , or null to rebuild it next raise. - private ManagedEventHandler[] CachedHandlers = Array.Empty>(); + private ManagedEventHandler[]? CachedHandlers = Array.Empty>(); /// The total number of event handlers registered for this events, regardless of whether they're still registered. private int RegistrationIndex; @@ -100,7 +98,7 @@ namespace StardewModdingAPI.Framework.Events /// Raise the event and notify all handlers. /// The event arguments to pass. /// A lambda which returns true if the event should be raised for the given mod. - public void Raise(TEventArgs args, Func match = null) + public void Raise(TEventArgs args, Func? match = null) { this.Raise((_, invoke) => invoke(args), match); } @@ -108,7 +106,7 @@ namespace StardewModdingAPI.Framework.Events /// Raise the event and notify all handlers. /// Invoke an event handler. This receives the mod which registered the handler, and should invoke the callback with the event arguments to pass it. /// A lambda which returns true if the event should be raised for the given mod. - public void Raise(Action> invoke, Func match = null) + public void Raise(Action> invoke, Func? match = null) { // skip if no handlers if (this.Handlers.Count == 0) diff --git a/src/SMAPI/Framework/Events/ManagedEventHandler.cs b/src/SMAPI/Framework/Events/ManagedEventHandler.cs index f31bc04d..d32acdb9 100644 --- a/src/SMAPI/Framework/Events/ManagedEventHandler.cs +++ b/src/SMAPI/Framework/Events/ManagedEventHandler.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewModdingAPI.Events; @@ -42,7 +40,7 @@ namespace StardewModdingAPI.Framework.Events } /// - public int CompareTo(object obj) + public int CompareTo(object? obj) { if (obj is not ManagedEventHandler other) throw new ArgumentException("Can't compare to an unrelated object type."); diff --git a/src/SMAPI/Framework/Exceptions/SContentLoadException.cs b/src/SMAPI/Framework/Exceptions/SContentLoadException.cs index c21a6b0e..be1fe748 100644 --- a/src/SMAPI/Framework/Exceptions/SContentLoadException.cs +++ b/src/SMAPI/Framework/Exceptions/SContentLoadException.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework.Content; @@ -14,7 +12,7 @@ namespace StardewModdingAPI.Framework.Exceptions /// Construct an instance. /// The error message. /// The underlying exception, if any. - public SContentLoadException(string message, Exception ex = null) + public SContentLoadException(string message, Exception? ex = null) : base(message, ex) { } } } diff --git a/src/SMAPI/Framework/GameVersion.cs b/src/SMAPI/Framework/GameVersion.cs index aa91d8f3..542c1345 100644 --- a/src/SMAPI/Framework/GameVersion.cs +++ b/src/SMAPI/Framework/GameVersion.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; @@ -55,7 +53,7 @@ namespace StardewModdingAPI.Framework private static string GetSemanticVersionString(string gameVersion) { // mapped version - return GameVersion.VersionMap.TryGetValue(gameVersion, out string semanticVersion) + return GameVersion.VersionMap.TryGetValue(gameVersion, out string? semanticVersion) ? semanticVersion : gameVersion; } @@ -64,10 +62,10 @@ namespace StardewModdingAPI.Framework /// The semantic version string. private static string GetGameVersionString(string semanticVersion) { - foreach (var mapping in GameVersion.VersionMap) + foreach ((string gameVersion, string equivalentSemanticVersion) in GameVersion.VersionMap) { - if (mapping.Value.Equals(semanticVersion, StringComparison.OrdinalIgnoreCase)) - return mapping.Key; + if (equivalentSemanticVersion.Equals(semanticVersion, StringComparison.OrdinalIgnoreCase)) + return gameVersion; } return semanticVersion; diff --git a/src/SMAPI/Framework/IModMetadata.cs b/src/SMAPI/Framework/IModMetadata.cs index 800b198a..7cee20b9 100644 --- a/src/SMAPI/Framework/IModMetadata.cs +++ b/src/SMAPI/Framework/IModMetadata.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using StardewModdingAPI.Framework.ModHelpers; @@ -29,7 +27,7 @@ namespace StardewModdingAPI.Framework string RelativeDirectoryPath { get; } /// Metadata about the mod from SMAPI's internal data (if any). - ModDataRecordVersionedFields DataRecord { get; } + ModDataRecordVersionedFields? DataRecord { get; } /// The metadata resolution status. ModMetadataStatus Status { get; } @@ -41,31 +39,31 @@ namespace StardewModdingAPI.Framework ModWarning Warnings { get; } /// The reason the metadata is invalid, if any. - string Error { get; } + string? Error { get; } /// A detailed technical message for , if any. - public string ErrorDetails { get; } + string? ErrorDetails { get; } /// Whether the mod folder should be ignored. This is true if it was found within a folder whose name starts with a dot. bool IsIgnored { get; } /// The mod instance (if loaded and is false). - IMod Mod { get; } + IMod? Mod { get; } /// The content pack instance (if loaded and is true). - IContentPack ContentPack { get; } + IContentPack? ContentPack { get; } /// The translations for this mod (if loaded). - TranslationHelper Translations { get; } + TranslationHelper? Translations { get; } /// Writes messages to the console and log file as this mod. - IMonitor Monitor { get; } + IMonitor? Monitor { get; } /// The mod-provided API (if any). - object Api { get; } + object? Api { get; } /// The update-check metadata for this mod (if any). - ModEntryModel UpdateCheckData { get; } + ModEntryModel? UpdateCheckData { get; } /// The fake content packs created by this mod, if any. ISet> FakeContentPacks { get; } @@ -84,7 +82,7 @@ namespace StardewModdingAPI.Framework /// The reason the metadata is invalid, if any. /// A detailed technical message, if any. /// Return the instance for chaining. - IModMetadata SetStatus(ModMetadataStatus status, ModFailReason reason, string error, string errorDetails = null); + IModMetadata SetStatus(ModMetadataStatus status, ModFailReason reason, string? error, string? errorDetails = null); /// Set a warning flag for the mod. /// The warning to set. @@ -103,7 +101,7 @@ namespace StardewModdingAPI.Framework /// Set the mod-provided API instance. /// The mod-provided API. - IModMetadata SetApi(object api); + IModMetadata SetApi(object? api); /// Set the update-check metadata for this mod. /// The update-check metadata. @@ -117,7 +115,7 @@ namespace StardewModdingAPI.Framework /// Whether the mod has the given ID. /// The mod ID to check. - bool HasID(string id); + bool HasID(string? id); /// Get the defined update keys. /// Only return valid update keys. diff --git a/src/SMAPI/Framework/Logging/LogFileManager.cs b/src/SMAPI/Framework/Logging/LogFileManager.cs index 0b6f9ad2..b396091a 100644 --- a/src/SMAPI/Framework/Logging/LogFileManager.cs +++ b/src/SMAPI/Framework/Logging/LogFileManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.IO; @@ -32,7 +30,7 @@ namespace StardewModdingAPI.Framework.Logging this.Path = path; // create log directory if needed - string logDir = System.IO.Path.GetDirectoryName(path); + string? logDir = System.IO.Path.GetDirectoryName(path); if (logDir == null) throw new ArgumentException($"The log path '{path}' is not valid."); Directory.CreateDirectory(logDir); diff --git a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs index 12ef0439..b610b395 100644 --- a/src/SMAPI/Framework/ModHelpers/ContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -114,6 +112,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public T Load(string key, ContentSource source = ContentSource.ModFolder) + where T : notnull { IAssetName assetName = this.ContentCore.ParseAssetName(key, allowLocales: source == ContentSource.GameContent); @@ -140,7 +139,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// [Pure] - public string NormalizeAssetName(string assetName) + public string NormalizeAssetName(string? assetName) { return this.ModContentManager.AssertAndNormalizeAssetName(assetName); } @@ -171,6 +170,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public bool InvalidateCache() + where T : notnull { this.Monitor.Log($"Requested cache invalidation for all assets of type {typeof(T)}. This is an expensive operation and should be avoided if possible."); return this.ContentCore.InvalidateCache((_, _, type) => typeof(T).IsAssignableFrom(type)).Any(); @@ -184,7 +184,8 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public IAssetData GetPatchHelper(T data, string assetName = null) + public IAssetData GetPatchHelper(T data, string? assetName = null) + where T : notnull { if (data == null) throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value."); diff --git a/src/SMAPI/Framework/ModHelpers/DataHelper.cs b/src/SMAPI/Framework/ModHelpers/DataHelper.cs index 86a34ee8..92b3b398 100644 --- a/src/SMAPI/Framework/ModHelpers/DataHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/DataHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -42,19 +40,21 @@ namespace StardewModdingAPI.Framework.ModHelpers ** JSON file ****/ /// - public TModel ReadJsonFile(string path) where TModel : class + public TModel? ReadJsonFile(string path) + where TModel : class { if (!PathUtilities.IsSafeRelativePath(path)) throw new InvalidOperationException($"You must call {nameof(IModHelper.Data)}.{nameof(this.ReadJsonFile)} with a relative path."); path = Path.Combine(this.ModFolderPath, PathUtilities.NormalizePath(path)); - return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data) + return this.JsonHelper.ReadJsonFileIfExists(path, out TModel? data) ? data : null; } /// - public void WriteJsonFile(string path, TModel data) where TModel : class + public void WriteJsonFile(string path, TModel? data) + where TModel : class { if (!PathUtilities.IsSafeRelativePath(path)) throw new InvalidOperationException($"You must call {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteJsonFile)} with a relative path (without directory climbing)."); @@ -71,7 +71,8 @@ namespace StardewModdingAPI.Framework.ModHelpers ** Save file ****/ /// - public TModel ReadSaveData(string key) where TModel : class + public TModel? ReadSaveData(string key) + where TModel : class { if (Context.LoadStage == LoadStage.None) throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.ReadSaveData)} when a save file isn't loaded."); @@ -82,14 +83,15 @@ namespace StardewModdingAPI.Framework.ModHelpers string internalKey = this.GetSaveFileKey(key); foreach (IDictionary dataField in this.GetDataFields(Context.LoadStage)) { - if (dataField.TryGetValue(internalKey, out string value)) + if (dataField.TryGetValue(internalKey, out string? value)) return this.JsonHelper.Deserialize(value); } return null; } /// - public void WriteSaveData(string key, TModel model) where TModel : class + public void WriteSaveData(string key, TModel? model) + where TModel : class { if (Context.LoadStage == LoadStage.None) throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteSaveData)} when a save file isn't loaded."); @@ -97,7 +99,7 @@ namespace StardewModdingAPI.Framework.ModHelpers throw new InvalidOperationException($"Can't use {nameof(IMod.Helper)}.{nameof(IModHelper.Data)}.{nameof(this.WriteSaveData)} when connected to a remote host. (Save files are stored on the main player's computer.)"); string internalKey = this.GetSaveFileKey(key); - string data = model != null + string? data = model != null ? this.JsonHelper.Serialize(model, Formatting.None) : null; @@ -114,16 +116,18 @@ namespace StardewModdingAPI.Framework.ModHelpers ** Global app data ****/ /// - public TModel ReadGlobalData(string key) where TModel : class + public TModel? ReadGlobalData(string key) + where TModel : class { string path = this.GetGlobalDataPath(key); - return this.JsonHelper.ReadJsonFileIfExists(path, out TModel data) + return this.JsonHelper.ReadJsonFileIfExists(path, out TModel? data) ? data : null; } /// - public void WriteGlobalData(string key, TModel data) where TModel : class + public void WriteGlobalData(string key, TModel? data) + where TModel : class { string path = this.GetGlobalDataPath(key); if (data != null) diff --git a/src/SMAPI/Framework/ModHelpers/GameContentHelper.cs b/src/SMAPI/Framework/ModHelpers/GameContentHelper.cs index 6d0c2f5f..4c1cde02 100644 --- a/src/SMAPI/Framework/ModHelpers/GameContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/GameContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Linq; using StardewModdingAPI.Framework.Content; @@ -71,6 +69,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public T Load(string key) + where T : notnull { IAssetName assetName = this.ContentCore.ParseAssetName(key, allowLocales: true); return this.Load(assetName); @@ -78,6 +77,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public T Load(IAssetName assetName) + where T : notnull { try { @@ -105,6 +105,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public bool InvalidateCache() + where T : notnull { this.Monitor.Log($"Requested cache invalidation for all assets of type {typeof(T)}. This is an expensive operation and should be avoided if possible."); return this.ContentCore.InvalidateCache((_, _, type) => typeof(T).IsAssignableFrom(type)).Any(); @@ -118,7 +119,8 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public IAssetData GetPatchHelper(T data, string assetName = null) + public IAssetData GetPatchHelper(T data, string? assetName = null) + where T : notnull { if (data == null) throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value."); diff --git a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs index b149ed82..fc47f269 100644 --- a/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework.Content; using StardewModdingAPI.Framework.Content; @@ -57,6 +55,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// public T Load(string relativePath) + where T : notnull { relativePath = this.RelativePathCache.GetAssetName(relativePath); @@ -80,7 +79,8 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public IAssetData GetPatchHelper(T data, string relativePath = null) + public IAssetData GetPatchHelper(T data, string? relativePath = null) + where T : notnull { if (data == null) throw new ArgumentNullException(nameof(data), "Can't get a patch helper for a null value."); diff --git a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs index e277e6fa..84899610 100644 --- a/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ModRegistryHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using StardewModdingAPI.Framework.Reflection; @@ -47,7 +45,7 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public IModInfo Get(string uniqueID) + public IModInfo? Get(string uniqueID) { return this.Registry.Get(uniqueID); } @@ -59,7 +57,7 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public object GetApi(string uniqueID) + public object? GetApi(string uniqueID) { // validate ready if (!this.Registry.AreAllModsInitialized) @@ -69,17 +67,18 @@ namespace StardewModdingAPI.Framework.ModHelpers } // get raw API - IModMetadata mod = this.Registry.Get(uniqueID); + IModMetadata? mod = this.Registry.Get(uniqueID); if (mod?.Api != null && this.AccessedModApis.Add(mod.Manifest.UniqueID)) this.Monitor.Log($"Accessed mod-provided API for {mod.DisplayName}."); return mod?.Api; } /// - public TInterface GetApi(string uniqueID) where TInterface : class + public TInterface? GetApi(string uniqueID) + where TInterface : class { // get raw API - object api = this.GetApi(uniqueID); + object? api = this.GetApi(uniqueID); if (api == null) return null; diff --git a/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs b/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs index 96b074e2..a419327e 100644 --- a/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/MultiplayerHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using StardewModdingAPI.Framework.Networking; using StardewValley; @@ -41,9 +39,9 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public IMultiplayerPeer GetConnectedPlayer(long id) + public IMultiplayerPeer? GetConnectedPlayer(long id) { - return this.Multiplayer.Peers.TryGetValue(id, out MultiplayerPeer peer) + return this.Multiplayer.Peers.TryGetValue(id, out MultiplayerPeer? peer) ? peer : null; } @@ -55,7 +53,7 @@ namespace StardewModdingAPI.Framework.ModHelpers } /// - public void SendMessage(TMessage message, string messageType, string[] modIDs = null, long[] playerIDs = null) + public void SendMessage(TMessage message, string messageType, string[]? modIDs = null, long[]? playerIDs = null) { this.Multiplayer.BroadcastModMessage( message: message, diff --git a/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs b/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs index 24cbd01c..af018c87 100644 --- a/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/ReflectionHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Reflection; using StardewModdingAPI.Framework.Reflection; @@ -39,7 +37,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetField(obj, name, required) - ); + )!; } /// @@ -47,7 +45,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetField(type, name, required) - ); + )!; } /// @@ -55,7 +53,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetProperty(obj, name, required) - ); + )!; } /// @@ -63,7 +61,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetProperty(type, name, required) - ); + )!; } /// @@ -71,7 +69,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetMethod(obj, name, required) - ); + )!; } /// @@ -79,7 +77,7 @@ namespace StardewModdingAPI.Framework.ModHelpers { return this.AssertAccessAllowed( this.Reflector.GetMethod(type, name, required) - ); + )!; } @@ -90,7 +88,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The field value type. /// The field being accessed. /// Returns the same field instance for convenience. - private IReflectedField AssertAccessAllowed(IReflectedField field) + private IReflectedField? AssertAccessAllowed(IReflectedField? field) { this.AssertAccessAllowed(field?.FieldInfo); return field; @@ -100,7 +98,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The property value type. /// The property being accessed. /// Returns the same property instance for convenience. - private IReflectedProperty AssertAccessAllowed(IReflectedProperty property) + private IReflectedProperty? AssertAccessAllowed(IReflectedProperty? property) { this.AssertAccessAllowed(property?.PropertyInfo.GetMethod?.GetBaseDefinition()); this.AssertAccessAllowed(property?.PropertyInfo.SetMethod?.GetBaseDefinition()); @@ -110,7 +108,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// Assert that mods can use the reflection helper to access the given member. /// The method being accessed. /// Returns the same method instance for convenience. - private IReflectedMethod AssertAccessAllowed(IReflectedMethod method) + private IReflectedMethod? AssertAccessAllowed(IReflectedMethod? method) { this.AssertAccessAllowed(method?.MethodInfo.GetBaseDefinition()); return method; @@ -118,18 +116,18 @@ namespace StardewModdingAPI.Framework.ModHelpers /// Assert that mods can use the reflection helper to access the given member. /// The member being accessed. - private void AssertAccessAllowed(MemberInfo member) + private void AssertAccessAllowed(MemberInfo? member) { if (member == null) return; // get type which defines the member - Type declaringType = member.DeclaringType; + Type? declaringType = member.DeclaringType; if (declaringType == null) throw new InvalidOperationException($"Can't validate access to {member.MemberType} {member.Name} because it has no declaring type."); // should never happen // validate access - string rootNamespace = typeof(Program).Namespace; + string? rootNamespace = typeof(Program).Namespace; if (declaringType.Namespace == rootNamespace || declaringType.Namespace?.StartsWith(rootNamespace + ".") == true) throw new InvalidOperationException($"SMAPI blocked access by {this.ModName} to its internals through the reflection API. Accessing the SMAPI internals is strongly discouraged since they're subject to change, which means the mod can break without warning. (Detected access to {declaringType.FullName}.{member.Name}.)"); } diff --git a/src/SMAPI/Framework/ModLoading/AssemblyDefinitionResolver.cs b/src/SMAPI/Framework/ModLoading/AssemblyDefinitionResolver.cs index 1d4ddf72..b3378ad1 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyDefinitionResolver.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyDefinitionResolver.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using Mono.Cecil; @@ -38,6 +36,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Resolve an assembly reference. /// The assembly name. + /// The assembly can't be resolved. public override AssemblyDefinition Resolve(AssemblyNameReference name) { return this.ResolveName(name.Name) ?? base.Resolve(name); @@ -46,6 +45,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Resolve an assembly reference. /// The assembly name. /// The assembly reader parameters. + /// The assembly can't be resolved. public override AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) { return this.ResolveName(name.Name) ?? base.Resolve(name, parameters); @@ -57,9 +57,9 @@ namespace StardewModdingAPI.Framework.ModLoading *********/ /// Resolve a known assembly definition based on its short or full name. /// The assembly's short or full name. - private AssemblyDefinition ResolveName(string name) + private AssemblyDefinition? ResolveName(string name) { - return this.Lookup.TryGetValue(name, out AssemblyDefinition match) + return this.Lookup.TryGetValue(name, out AssemblyDefinition? match) ? match : null; } diff --git a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs index 7c94beb7..f5d449c5 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/EventFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Linq; using Mono.Cecil; @@ -57,7 +55,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders { if (this.MethodNames.Any()) { - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null && methodRef.DeclaringType.FullName == this.FullTypeName && this.MethodNames.Contains(methodRef.Name)) { string eventName = methodRef.Name.Split(new[] { '_' }, 2)[1]; diff --git a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs index 96b4098a..7fe4abec 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/FieldFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Linq; using Mono.Cecil; @@ -51,7 +49,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders { if (this.FieldNames.Any()) { - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null && fieldRef.DeclaringType.FullName == this.FullTypeName && this.FieldNames.Contains(fieldRef.Name)) { this.FieldNames.Remove(fieldRef.Name); diff --git a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs index 7d3c1fd7..e8fdc8c7 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/MethodFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -54,7 +52,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The IL instruction. protected bool IsMatch(Instruction instruction) { - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); return methodRef != null && methodRef.DeclaringType.FullName == this.FullTypeName diff --git a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs index b2f2e193..2af76f55 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/PropertyFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -54,7 +52,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The IL instruction. protected bool IsMatch(Instruction instruction) { - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); return methodRef != null && methodRef.DeclaringType.FullName == this.FullTypeName diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs index 81f90498..f34542c3 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMemberWithUnexpectedTypeFinder.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -34,11 +33,11 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null && this.ShouldValidate(fieldRef.DeclaringType)) { // get target field - FieldDefinition targetField = fieldRef.DeclaringType.Resolve()?.Fields.FirstOrDefault(p => p.Name == fieldRef.Name); + FieldDefinition? targetField = fieldRef.DeclaringType.Resolve()?.Fields.FirstOrDefault(p => p.Name == fieldRef.Name); if (targetField == null) return false; @@ -51,16 +50,16 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders } // method reference - MethodReference methodReference = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodReference = RewriteHelper.AsMethodReference(instruction); if (methodReference != null && !this.IsUnsupported(methodReference) && this.ShouldValidate(methodReference.DeclaringType)) { // get potential targets - MethodDefinition[] candidateMethods = methodReference.DeclaringType.Resolve()?.Methods.Where(found => found.Name == methodReference.Name).ToArray(); + MethodDefinition[]? candidateMethods = methodReference.DeclaringType.Resolve()?.Methods.Where(found => found.Name == methodReference.Name).ToArray(); if (candidateMethods == null || !candidateMethods.Any()) return false; // compare return types - MethodDefinition methodDef = methodReference.Resolve(); + MethodDefinition? methodDef = methodReference.Resolve(); if (methodDef == null) return false; // validated by ReferenceToMissingMemberFinder @@ -80,7 +79,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Whether references to the given type should be validated. /// The type reference. - private bool ShouldValidate(TypeReference type) + private bool ShouldValidate([NotNullWhen(true)] TypeReference? type) { return type != null && this.ValidateReferencesToAssemblies.Contains(type.Scope.Name); } diff --git a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs index 001d1986..fae7fb12 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/ReferenceToMissingMemberFinder.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -33,10 +32,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null && this.ShouldValidate(fieldRef.DeclaringType)) { - FieldDefinition target = fieldRef.Resolve(); + FieldDefinition? target = fieldRef.Resolve(); if (target == null || target.HasConstant) { this.MarkFlag(InstructionHandleResult.NotCompatible, $"reference to {fieldRef.DeclaringType.FullName}.{fieldRef.Name} (no such field)"); @@ -45,10 +44,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders } // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null && this.ShouldValidate(methodRef.DeclaringType) && !this.IsUnsupported(methodRef)) { - MethodDefinition target = methodRef.Resolve(); + MethodDefinition? target = methodRef.Resolve(); if (target == null) { string phrase; @@ -73,7 +72,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders *********/ /// Whether references to the given type should be validated. /// The type reference. - private bool ShouldValidate(TypeReference type) + private bool ShouldValidate([NotNullWhen(true)] TypeReference? type) { return type != null && this.ValidateReferencesToAssemblies.Contains(type.Scope.Name); } diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs index 4c589ed8..17acbf9a 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeAssemblyFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Mono.Cecil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; /// Get whether a matched type should be ignored. - private readonly Func ShouldIgnore; + private readonly Func? ShouldIgnore; /********* @@ -29,7 +27,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The full assembly name to which to find references. /// The result to return for matching instructions. /// Get whether a matched type should be ignored. - public TypeAssemblyFinder(string assemblyName, InstructionHandleResult result, Func shouldIgnore = null) + public TypeAssemblyFinder(string assemblyName, InstructionHandleResult result, Func? shouldIgnore = null) : base(defaultPhrase: $"{assemblyName} assembly") { this.AssemblyName = assemblyName; diff --git a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs index 04a5b970..77762f41 100644 --- a/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs +++ b/src/SMAPI/Framework/ModLoading/Finders/TypeFinder.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Mono.Cecil; @@ -20,7 +18,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders private readonly InstructionHandleResult Result; /// Get whether a matched type should be ignored. - private readonly Func ShouldIgnore; + private readonly Func? ShouldIgnore; /********* @@ -30,7 +28,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The full type names to match. /// The result to return for matching instructions. /// Get whether a matched type should be ignored. - public TypeFinder(string[] fullTypeNames, InstructionHandleResult result, Func shouldIgnore = null) + public TypeFinder(string[] fullTypeNames, InstructionHandleResult result, Func? shouldIgnore = null) : base(defaultPhrase: $"{string.Join(", ", fullTypeNames)} type{(fullTypeNames.Length != 1 ? "s" : "")}") // default phrase should never be used { this.FullTypeNames = new HashSet(fullTypeNames); @@ -42,7 +40,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Finders /// The full type name to match. /// The result to return for matching instructions. /// Get whether a matched type should be ignored. - public TypeFinder(string fullTypeName, InstructionHandleResult result, Func shouldIgnore = null) + public TypeFinder(string fullTypeName, InstructionHandleResult result, Func? shouldIgnore = null) : this(new[] { fullTypeName }, result, shouldIgnore) { } /// diff --git a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs index bea786cd..865bf076 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/BaseInstructionHandler.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using Mono.Cecil; @@ -59,7 +57,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The result flag to set. /// The result message to add. /// Returns true for convenience. - protected bool MarkFlag(InstructionHandleResult flag, string resultMessage = null) + protected bool MarkFlag(InstructionHandleResult flag, string? resultMessage = null) { this.Flags.Add(flag); if (resultMessage != null) diff --git a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs index 09ff78f7..55369602 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RecursiveRewriter.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -10,6 +9,7 @@ using Mono.Collections.Generic; namespace StardewModdingAPI.Framework.ModLoading.Framework { /// Handles recursively rewriting loaded assembly code. + [SuppressMessage("ReSharper", "AccessToModifiedClosure", Justification = "Rewrite callbacks are invoked immediately.")] internal class RecursiveRewriter { /********* @@ -77,7 +77,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework { changed |= this.RewriteModuleImpl(this.Module); - foreach (var type in types) + foreach (TypeDefinition type in types) changed |= this.RewriteTypeDefinition(type); } catch (Exception ex) @@ -129,9 +129,10 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework ILProcessor cil = method.Body.GetILProcessor(); Collection instructions = cil.Body.Instructions; bool addedInstructions = false; + // ReSharper disable once ForCanBeConvertedToForeach -- deliberate to allow changing the collection for (int i = 0; i < instructions.Count; i++) { - var instruction = instructions[i]; + Instruction instruction = instructions[i]; if (instruction.OpCode.Code == Code.Nop) continue; @@ -174,7 +175,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework bool rewritten = false; // field reference - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null) { rewritten |= this.RewriteTypeReference(fieldRef.DeclaringType, newType => fieldRef.DeclaringType = newType); @@ -182,7 +183,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework } // method reference - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef != null) this.RewriteMethodReference(methodRef); @@ -212,7 +213,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework }); rewritten |= this.RewriteTypeReference(methodRef.ReturnType, newType => methodRef.ReturnType = newType); - foreach (var parameter in methodRef.Parameters) + foreach (ParameterDefinition parameter in methodRef.Parameters) rewritten |= this.RewriteTypeReference(parameter.ParameterType, newType => parameter.ParameterType = newType); if (methodRef is GenericInstanceMethod genericRef) @@ -264,7 +265,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework bool curChanged = false; // attribute type - TypeReference newAttrType = null; + TypeReference? newAttrType = null; rewritten |= this.RewriteTypeReference(attribute.AttributeType, newType => { newAttrType = newType; @@ -289,9 +290,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework if (curChanged) { // get constructor - MethodDefinition constructor = (newAttrType ?? attribute.AttributeType) + MethodDefinition? constructor = (newAttrType ?? attribute.AttributeType) .Resolve() - .Methods + ?.Methods .Where(method => method.IsConstructor) .FirstOrDefault(ctor => RewriteHelper.HasMatchingSignature(ctor, attribute.Constructor)); if (constructor == null) @@ -301,9 +302,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework var newAttr = new CustomAttribute(this.Module.ImportReference(constructor)); for (int i = 0; i < argTypes.Length; i++) newAttr.ConstructorArguments.Add(new CustomAttributeArgument(argTypes[i], attribute.ConstructorArguments[i].Value)); - foreach (var prop in attribute.Properties) + foreach (CustomAttributeNamedArgument prop in attribute.Properties) newAttr.Properties.Add(new CustomAttributeNamedArgument(prop.Name, prop.Argument)); - foreach (var field in attribute.Fields) + foreach (CustomAttributeNamedArgument field in attribute.Fields) newAttr.Fields.Add(new CustomAttributeNamedArgument(field.Name, field.Argument)); // swap attribute diff --git a/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs b/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs index 8f47fbdd..15f71251 100644 --- a/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs +++ b/src/SMAPI/Framework/ModLoading/Framework/RewriteHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Linq; using System.Reflection; @@ -23,7 +21,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework *********/ /// Get the field reference from an instruction if it matches. /// The IL instruction. - public static FieldReference AsFieldReference(Instruction instruction) + public static FieldReference? AsFieldReference(Instruction instruction) { return instruction.OpCode == OpCodes.Ldfld || instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Stfld || instruction.OpCode == OpCodes.Stsfld ? (FieldReference)instruction.Operand @@ -32,7 +30,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Get the method reference from an instruction if it matches. /// The IL instruction. - public static MethodReference AsMethodReference(Instruction instruction) + public static MethodReference? AsMethodReference(Instruction instruction) { return instruction.OpCode == OpCodes.Call || instruction.OpCode == OpCodes.Callvirt || instruction.OpCode == OpCodes.Newobj ? (MethodReference)instruction.Operand @@ -42,7 +40,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// Get the CIL instruction to load a value onto the stack. /// The constant value to inject. /// Returns the instruction, or null if the value type isn't supported. - public static Instruction GetLoadValueInstruction(object rawValue) + public static Instruction? GetLoadValueInstruction(object? rawValue) { return rawValue switch { @@ -151,7 +149,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Framework /// The type ID to compare. /// The other type ID to compare. /// true if the type IDs look like the same type, false if not. - public static bool LooksLikeSameType(TypeReference typeA, TypeReference typeB) + public static bool LooksLikeSameType(TypeReference? typeA, TypeReference? typeB) { return RewriteHelper.TypeDefinitionComparer.Equals(typeA, typeB); } diff --git a/src/SMAPI/Framework/ModLoading/InvalidModStateException.cs b/src/SMAPI/Framework/ModLoading/InvalidModStateException.cs index 9dca9bc4..b53a9886 100644 --- a/src/SMAPI/Framework/ModLoading/InvalidModStateException.cs +++ b/src/SMAPI/Framework/ModLoading/InvalidModStateException.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI.Framework.ModLoading @@ -10,7 +8,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Construct an instance. /// The error message. /// The underlying exception, if any. - public InvalidModStateException(string message, Exception ex = null) + public InvalidModStateException(string message, Exception? ex = null) : base(message, ex) { } } } diff --git a/src/SMAPI/Framework/ModLoading/ModMetadata.cs b/src/SMAPI/Framework/ModLoading/ModMetadata.cs index 0e698bfd..fe54634b 100644 --- a/src/SMAPI/Framework/ModLoading/ModMetadata.cs +++ b/src/SMAPI/Framework/ModLoading/ModMetadata.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using StardewModdingAPI.Framework.ModHelpers; @@ -44,7 +43,7 @@ namespace StardewModdingAPI.Framework.ModLoading public IManifest Manifest { get; } /// - public ModDataRecordVersionedFields DataRecord { get; } + public ModDataRecordVersionedFields? DataRecord { get; } /// public ModMetadataStatus Status { get; private set; } @@ -56,33 +55,35 @@ namespace StardewModdingAPI.Framework.ModLoading public ModWarning Warnings => this.ActualWarnings & ~(this.DataRecord?.DataRecord.SuppressWarnings ?? ModWarning.None); /// - public string Error { get; private set; } + public string? Error { get; private set; } /// - public string ErrorDetails { get; private set; } + public string? ErrorDetails { get; private set; } /// public bool IsIgnored { get; } /// - public IMod Mod { get; private set; } + public IMod? Mod { get; private set; } /// - public IContentPack ContentPack { get; private set; } + public IContentPack? ContentPack { get; private set; } /// - public TranslationHelper Translations { get; private set; } + public TranslationHelper? Translations { get; private set; } /// - public IMonitor Monitor { get; private set; } + public IMonitor? Monitor { get; private set; } /// - public object Api { get; private set; } + public object? Api { get; private set; } /// - public ModEntryModel UpdateCheckData { get; private set; } + public ModEntryModel? UpdateCheckData { get; private set; } /// + [MemberNotNullWhen(true, nameof(ModMetadata.ContentPack))] + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "The manifest may be null for broken mods while loading.")] public bool IsContentPack => this.Manifest?.ContentPackFor != null; /// The fake content packs created by this mod, if any. @@ -99,13 +100,13 @@ namespace StardewModdingAPI.Framework.ModLoading /// The mod manifest. /// Metadata about the mod from SMAPI's internal data (if any). /// Whether the mod folder should be ignored. This should be true if it was found within a folder whose name starts with a dot. - public ModMetadata(string displayName, string directoryPath, string rootPath, IManifest manifest, ModDataRecordVersionedFields dataRecord, bool isIgnored) + public ModMetadata(string displayName, string directoryPath, string rootPath, IManifest? manifest, ModDataRecordVersionedFields? dataRecord, bool isIgnored) { this.DisplayName = displayName; this.DirectoryPath = directoryPath; this.RootPath = rootPath; this.RelativeDirectoryPath = PathUtilities.GetRelativePath(this.RootPath, this.DirectoryPath); - this.Manifest = manifest; + this.Manifest = manifest!; // manifest may be null in low-level SMAPI code, but won't be null once it's received by mods via IModInfo this.DataRecord = dataRecord; this.IsIgnored = isIgnored; @@ -121,7 +122,7 @@ namespace StardewModdingAPI.Framework.ModLoading } /// - public IModMetadata SetStatus(ModMetadataStatus status, ModFailReason reason, string error, string errorDetails = null) + public IModMetadata SetStatus(ModMetadataStatus status, ModFailReason reason, string? error, string? errorDetails = null) { this.Status = status; this.FailReason = reason; @@ -162,7 +163,7 @@ namespace StardewModdingAPI.Framework.ModLoading } /// - public IModMetadata SetApi(object api) + public IModMetadata SetApi(object? api) { this.Api = api; return this; @@ -176,6 +177,7 @@ namespace StardewModdingAPI.Framework.ModLoading } /// + [MemberNotNullWhen(true, nameof(IModInfo.Manifest))] public bool HasManifest() { return this.Manifest != null; @@ -190,7 +192,7 @@ namespace StardewModdingAPI.Framework.ModLoading } /// - public bool HasID(string id) + public bool HasID(string? id) { return this.HasID() @@ -245,7 +247,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// public string GetRelativePathWithRoot() { - string rootFolderName = Path.GetFileName(this.RootPath) ?? ""; + string rootFolderName = Path.GetFileName(this.RootPath); return Path.Combine(rootFolderName, this.RelativeDirectoryPath); } @@ -254,7 +256,7 @@ namespace StardewModdingAPI.Framework.ModLoading { foreach (var reference in this.FakeContentPacks.ToArray()) { - if (!reference.TryGetTarget(out ContentPack pack)) + if (!reference.TryGetTarget(out ContentPack? pack)) { this.FakeContentPacks.Remove(reference); continue; diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsFacade.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsFacade.cs index c05005b8..afe38bfd 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsFacade.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/AccessToolsFacade.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades /********* ** Public methods *********/ - public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null) + public static ConstructorInfo DeclaredConstructor(Type type, Type[]? parameters = null) { // Harmony 1.x matched both static and instance constructors return @@ -27,7 +25,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades ?? AccessTools.DeclaredConstructor(type, parameters, searchForStatic: true); } - public static ConstructorInfo Constructor(Type type, Type[] parameters = null) + public static ConstructorInfo Constructor(Type type, Type[]? parameters = null) { // Harmony 1.x matched both static and instance constructors return diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceFacade.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceFacade.cs index fea8c100..9c8ba2b0 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceFacade.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyInstanceFacade.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -30,7 +28,8 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades return new Harmony(id); } - public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) + [SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse", Justification = "If the user passes a null original method, we let it fail in the underlying Harmony instance instead of handling it here.")] + public DynamicMethod Patch(MethodBase original, HarmonyMethod? prefix = null, HarmonyMethod? postfix = null, HarmonyMethod? transpiler = null) { // In Harmony 1.x you could target a virtual method that's not implemented by the // target type, but in Harmony 2.0 you need to target the concrete implementation. @@ -60,7 +59,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades /// The prefix method, if any. /// The postfix method, if any. /// The transpiler method, if any. - private string GetPatchTypesLabel(HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null) + private string GetPatchTypesLabel(HarmonyMethod? prefix = null, HarmonyMethod? postfix = null, HarmonyMethod? transpiler = null) { var patchTypes = new List(); @@ -76,7 +75,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades /// Get a human-readable label for the method being patched. /// The method being patched. - private string GetMethodLabel(MethodBase method) + private string GetMethodLabel(MethodBase? method) { return method != null ? $"method {method.DeclaringType?.FullName}.{method.Name}" diff --git a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyMethodFacade.cs b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyMethodFacade.cs index 93124591..2b1ca54b 100644 --- a/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyMethodFacade.cs +++ b/src/SMAPI/Framework/ModLoading/RewriteFacades/HarmonyMethodFacade.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; @@ -23,7 +21,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades this.ImportMethodImpl(method); } - public HarmonyMethodFacade(Type type, string name, Type[] parameters = null) + public HarmonyMethodFacade(Type type, string name, Type[]? parameters = null) { this.ImportMethodImpl(AccessTools.Method(type, name, parameters)); } @@ -40,7 +38,7 @@ namespace StardewModdingAPI.Framework.ModLoading.RewriteFacades // internal code still handles null fine. For backwards compatibility, this bypasses // the new restriction when the mod hasn't been updated for Harmony 2.0 yet. - MethodInfo importMethod = typeof(HarmonyMethod).GetMethod("ImportMethod", BindingFlags.Instance | BindingFlags.NonPublic); + MethodInfo? importMethod = typeof(HarmonyMethod).GetMethod("ImportMethod", BindingFlags.Instance | BindingFlags.NonPublic); if (importMethod == null) throw new InvalidOperationException("Can't find 'HarmonyMethod.ImportMethod' method"); importMethod.Invoke(this, new object[] { methodInfo }); diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs index 92397c58..aea490c8 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HarmonyRewriter.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using HarmonyLib; using Mono.Cecil; @@ -59,7 +57,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters if (this.ShouldRewrite) { // rewrite Harmony 1.x methods to Harmony 2.0 - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (this.TryRewriteMethodsToFacade(module, methodRef)) { this.OnChanged(); @@ -67,7 +65,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters } // rewrite renamed fields - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef != null) { if (fieldRef.DeclaringType.FullName == "HarmonyLib.HarmonyMethod" && fieldRef.Name == "prioritiy") @@ -95,13 +93,13 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// Rewrite methods to use Harmony facades if needed. /// The assembly module containing the method reference. /// The method reference to map. - private bool TryRewriteMethodsToFacade(ModuleDefinition module, MethodReference methodRef) + private bool TryRewriteMethodsToFacade(ModuleDefinition module, MethodReference? methodRef) { if (!this.ReplacedTypes) return false; // not Harmony (or already using Harmony 2.0) // get facade type - Type toType = methodRef?.DeclaringType.FullName switch + Type? toType = methodRef?.DeclaringType.FullName switch { "HarmonyLib.Harmony" => typeof(HarmonyInstanceFacade), "HarmonyLib.AccessTools" => typeof(AccessToolsFacade), @@ -112,9 +110,9 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters return false; // map if there's a matching method - if (RewriteHelper.HasMatchingSignature(toType, methodRef)) + if (RewriteHelper.HasMatchingSignature(toType, methodRef!)) { - methodRef.DeclaringType = module.ImportReference(toType); + methodRef!.DeclaringType = module.ImportReference(toType); return true; } @@ -139,7 +137,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters { string fullName = type.FullName.Replace("Harmony.", "HarmonyLib."); string targetName = typeof(Harmony).AssemblyQualifiedName!.Replace(typeof(Harmony).FullName!, fullName); - return Type.GetType(targetName, throwOnError: true); + return Type.GetType(targetName, throwOnError: true)!; } } } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs index fc06e779..9c6a3980 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -33,17 +32,17 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { // get field ref - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); if (fieldRef == null || !this.ShouldValidate(fieldRef.DeclaringType)) return false; // skip if not broken - FieldDefinition fieldDefinition = fieldRef.Resolve(); + FieldDefinition? fieldDefinition = fieldRef.Resolve(); if (fieldDefinition?.HasConstant == false) return false; // rewrite if possible - TypeDefinition declaringType = fieldRef.DeclaringType.Resolve(); + TypeDefinition? declaringType = fieldRef.DeclaringType.Resolve(); bool isRead = instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld; return this.TryRewriteToProperty(module, instruction, fieldRef, declaringType, isRead) @@ -56,7 +55,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Whether references to the given type should be validated. /// The type reference. - private bool ShouldValidate(TypeReference type) + private bool ShouldValidate([NotNullWhen(true)] TypeReference? type) { return type != null && this.RewriteReferencesToAssemblies.Contains(type.Scope.Name); } @@ -70,8 +69,8 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters private bool TryRewriteToProperty(ModuleDefinition module, Instruction instruction, FieldReference fieldRef, TypeDefinition declaringType, bool isRead) { // get equivalent property - PropertyDefinition property = declaringType?.Properties.FirstOrDefault(p => p.Name == fieldRef.Name); - MethodDefinition method = isRead ? property?.GetMethod : property?.SetMethod; + PropertyDefinition? property = declaringType?.Properties.FirstOrDefault(p => p.Name == fieldRef.Name); + MethodDefinition? method = isRead ? property?.GetMethod : property?.SetMethod; if (method == null) return false; @@ -86,14 +85,14 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// Try rewriting the field into a matching const field. /// The CIL instruction to rewrite. /// The field definition. - private bool TryRewriteToConstField(Instruction instruction, FieldDefinition field) + private bool TryRewriteToConstField(Instruction instruction, FieldDefinition? field) { // must have been a static field read, and the new field must be const if (instruction.OpCode != OpCodes.Ldsfld || field?.HasConstant != true) return false; // get opcode for value type - Instruction loadInstruction = RewriteHelper.GetLoadValueInstruction(field.Constant); + Instruction? loadInstruction = RewriteHelper.GetLoadValueInstruction(field.Constant); if (loadInstruction == null) return false; diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs index 4860072c..601ecbbc 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicMethodRewriter.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -33,7 +32,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { // get method ref - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (methodRef == null || !this.ShouldValidate(methodRef.DeclaringType)) return false; @@ -42,13 +41,13 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters return false; // get type - var type = methodRef.DeclaringType.Resolve(); + TypeDefinition? type = methodRef.DeclaringType.Resolve(); if (type == null) return false; // get method definition - MethodDefinition method = null; - foreach (var match in type.Methods.Where(p => p.Name == methodRef.Name)) + MethodDefinition? method = null; + foreach (MethodDefinition match in type.Methods.Where(p => p.Name == methodRef.Name)) { // reference matches initial parameters of definition if (methodRef.Parameters.Count >= match.Parameters.Count || !this.InitialParametersMatch(methodRef, match)) @@ -72,7 +71,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters return false; // SMAPI needs to load the value onto the stack before the method call, but the optional parameter type wasn't recognized // rewrite method reference - foreach (Instruction loadInstruction in loadInstructions) + foreach (Instruction? loadInstruction in loadInstructions) cil.InsertBefore(instruction, loadInstruction); instruction.Operand = module.ImportReference(method); @@ -86,7 +85,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Whether references to the given type should be validated. /// The type reference. - private bool ShouldValidate(TypeReference type) + private bool ShouldValidate([NotNullWhen(true)] TypeReference? type) { return type != null && this.RewriteReferencesToAssemblies.Contains(type.Scope.Name); } diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs index 00daf337..2e2f6316 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs @@ -1,6 +1,5 @@ -#nullable disable - using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; @@ -28,7 +27,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type whose methods to remap. /// The type with methods to map to. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). - public MethodParentRewriter(string fromType, Type toType, string nounPhrase = null) + public MethodParentRewriter(string fromType, Type toType, string? nounPhrase = null) : base(nounPhrase ?? $"{fromType.Split('.').Last()} methods") { this.FromType = fromType; @@ -39,14 +38,14 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The type whose methods to remap. /// The type with methods to map to. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). - public MethodParentRewriter(Type fromType, Type toType, string nounPhrase = null) - : this(fromType.FullName, toType, nounPhrase) { } + public MethodParentRewriter(Type fromType, Type toType, string? nounPhrase = null) + : this(fromType.FullName!, toType, nounPhrase) { } /// public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { // get method ref - MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); + MethodReference? methodRef = RewriteHelper.AsMethodReference(instruction); if (!this.IsMatch(methodRef)) return false; @@ -61,7 +60,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters *********/ /// Get whether a CIL instruction matches. /// The method reference. - private bool IsMatch(MethodReference methodRef) + private bool IsMatch([NotNullWhen(true)] MethodReference? methodRef) { return methodRef != null diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs index bdc4c4f3..a81cb5be 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Mono.Cecil; using StardewModdingAPI.Framework.ModLoading.Framework; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters private readonly Type ToType; /// Get whether a matched type should be ignored. - private readonly Func ShouldIgnore; + private readonly Func? ShouldIgnore; /********* @@ -29,7 +27,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The full type name to which to find references. /// The new type to reference. /// Get whether a matched type should be ignored. - public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func shouldIgnore = null) + public TypeReferenceRewriter(string fromTypeFullName, Type toType, Func? shouldIgnore = null) : base($"{fromTypeFullName} type") { this.FromTypeName = fromTypeFullName; diff --git a/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs b/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs index 4af7c1e7..0d3aff9f 100644 --- a/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs +++ b/src/SMAPI/Framework/ModLoading/Symbols/SymbolReaderProvider.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -38,7 +36,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Symbols /// The assembly file name. public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName) { - return this.SymbolsByAssemblyPath.TryGetValue(module.Name, out Stream symbolData) + return this.SymbolsByAssemblyPath.TryGetValue(module.Name, out Stream? symbolData) ? new SymbolReader(module, symbolData) : this.BaseProvider.GetSymbolReader(module, fileName); } @@ -48,7 +46,7 @@ namespace StardewModdingAPI.Framework.ModLoading.Symbols /// The loaded symbol file stream. public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream) { - return this.SymbolsByAssemblyPath.TryGetValue(module.Name, out Stream symbolData) + return this.SymbolsByAssemblyPath.TryGetValue(module.Name, out Stream? symbolData) ? new SymbolReader(module, symbolData) : this.BaseProvider.GetSymbolReader(module, symbolStream); } diff --git a/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs b/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs index 248c29fc..d81d763e 100644 --- a/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs +++ b/src/SMAPI/Framework/ModLoading/TypeReferenceComparer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -18,7 +16,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// TKey in the above example). If all components are equal after substitution, and the /// tokens can all be mapped to the same generic type, the types are considered equal. /// - internal class TypeReferenceComparer : IEqualityComparer + internal class TypeReferenceComparer : IEqualityComparer { /********* ** Public methods @@ -26,7 +24,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Get whether the specified objects are equal. /// The first object to compare. /// The second object to compare. - public bool Equals(TypeReference a, TypeReference b) + public bool Equals(TypeReference? a, TypeReference? b) { if (a == null || b == null) return a == b; @@ -54,7 +52,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// The second type to compare. private bool HeuristicallyEquals(TypeReference typeA, TypeReference typeB) { - bool HeuristicallyEquals(string typeNameA, string typeNameB, IDictionary tokenMap) + bool HeuristicallyEqualsImpl(string typeNameA, string typeNameB, IDictionary tokenMap) { // analyze type names bool hasTokensA = typeNameA.Contains("!"); @@ -82,14 +80,14 @@ namespace StardewModdingAPI.Framework.ModLoading for (int i = 0; i < symbolsA.Length; i++) { - if (!HeuristicallyEquals(symbolsA[i], symbolsB[i], tokenMap)) + if (!HeuristicallyEqualsImpl(symbolsA[i], symbolsB[i], tokenMap)) return false; } return true; } - return HeuristicallyEquals(typeA.FullName, typeB.FullName, new Dictionary()); + return HeuristicallyEqualsImpl(typeA.FullName, typeB.FullName, new Dictionary()); } /// Map a generic type placeholder (like !0) to its actual type. @@ -99,7 +97,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// Returns the previously-mapped type if applicable, else the . private string MapPlaceholder(string placeholder, string type, IDictionary map) { - if (map.TryGetValue(placeholder, out string result)) + if (map.TryGetValue(placeholder, out string? result)) return result; map[placeholder] = type; diff --git a/src/SMAPI/Framework/ModRegistry.cs b/src/SMAPI/Framework/ModRegistry.cs index cae38637..de16a780 100644 --- a/src/SMAPI/Framework/ModRegistry.cs +++ b/src/SMAPI/Framework/ModRegistry.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics; @@ -42,7 +40,7 @@ namespace StardewModdingAPI.Framework /// The mod assembly. public void TrackAssemblies(IModMetadata metadata, Assembly modAssembly) { - this.ModNamesByAssembly[modAssembly.FullName] = metadata; + this.ModNamesByAssembly[modAssembly.FullName!] = metadata; } /// Get metadata for all loaded mods. @@ -62,7 +60,7 @@ namespace StardewModdingAPI.Framework /// Get metadata for a loaded mod. /// The mod's unique ID. /// Returns the matching mod's metadata, or null if not found. - public IModMetadata Get(string uniqueID) + public IModMetadata? Get(string uniqueID) { // normalize search ID if (string.IsNullOrWhiteSpace(uniqueID)) @@ -76,14 +74,14 @@ namespace StardewModdingAPI.Framework /// Get the mod metadata from one of its assemblies. /// The type to check. /// Returns the mod name, or null if the type isn't part of a known mod. - public IModMetadata GetFrom(Type type) + public IModMetadata? GetFrom(Type? type) { // null if (type == null) return null; // known type - string assemblyName = type.Assembly.FullName; + string assemblyName = type.Assembly.FullName!; if (this.ModNamesByAssembly.ContainsKey(assemblyName)) return this.ModNamesByAssembly[assemblyName]; @@ -93,7 +91,7 @@ namespace StardewModdingAPI.Framework /// Get the friendly name for the closest assembly registered as a source of deprecation warnings. /// Returns the source name, or null if no registered assemblies were found. - public IModMetadata GetFromStack() + public IModMetadata? GetFromStack() { // get stack frames StackTrace stack = new(); @@ -102,8 +100,8 @@ namespace StardewModdingAPI.Framework // search stack for a source assembly foreach (StackFrame frame in frames) { - MethodBase method = frame.GetMethod(); - IModMetadata mod = this.GetFrom(method.ReflectedType); + MethodBase? method = frame.GetMethod(); + IModMetadata? mod = this.GetFrom(method?.ReflectedType); if (mod != null) return mod; } diff --git a/src/SMAPI/Framework/Reflection/ReflectedField.cs b/src/SMAPI/Framework/Reflection/ReflectedField.cs index 921876b9..197a246e 100644 --- a/src/SMAPI/Framework/Reflection/ReflectedField.cs +++ b/src/SMAPI/Framework/Reflection/ReflectedField.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Reflection; @@ -15,8 +13,8 @@ namespace StardewModdingAPI.Framework.Reflection /// The type that has the field. private readonly Type ParentType; - /// The object that has the instance field (if applicable). - private readonly object Parent; + /// The object that has the instance field, or null for a static field. + private readonly object? Parent; /// The display name shown in error messages. private string DisplayName => $"{this.ParentType.FullName}::{this.FieldInfo.Name}"; @@ -34,12 +32,12 @@ namespace StardewModdingAPI.Framework.Reflection *********/ /// Construct an instance. /// The type that has the field. - /// The object that has the instance field (if applicable). + /// The object that has the instance field, or null for a static field. /// The reflection metadata. /// Whether the field is static. /// The or is null. /// The is null for a non-static field, or not null for a static field. - public ReflectedField(Type parentType, object obj, FieldInfo field, bool isStatic) + public ReflectedField(Type parentType, object? obj, FieldInfo field, bool isStatic) { // validate if (parentType == null) @@ -58,11 +56,11 @@ namespace StardewModdingAPI.Framework.Reflection } /// - public TValue GetValue() + public TValue? GetValue() { try { - return (TValue)this.FieldInfo.GetValue(this.Parent); + return (TValue?)this.FieldInfo.GetValue(this.Parent); } catch (InvalidCastException) { @@ -75,7 +73,7 @@ namespace StardewModdingAPI.Framework.Reflection } /// - public void SetValue(TValue value) + public void SetValue(TValue? value) { try { diff --git a/src/SMAPI/Framework/Reflection/ReflectedMethod.cs b/src/SMAPI/Framework/Reflection/ReflectedMethod.cs index 50f89b40..c245e843 100644 --- a/src/SMAPI/Framework/Reflection/ReflectedMethod.cs +++ b/src/SMAPI/Framework/Reflection/ReflectedMethod.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Reflection; @@ -14,8 +12,8 @@ namespace StardewModdingAPI.Framework.Reflection /// The type that has the method. private readonly Type ParentType; - /// The object that has the instance method (if applicable). - private readonly object Parent; + /// The object that has the instance method, or null for a static method. + private readonly object? Parent; /// The display name shown in error messages. private string DisplayName => $"{this.ParentType.FullName}::{this.MethodInfo.Name}"; @@ -33,12 +31,12 @@ namespace StardewModdingAPI.Framework.Reflection *********/ /// Construct an instance. /// The type that has the method. - /// The object that has the instance method(if applicable). + /// The object that has the instance method, or null for a static method. /// The reflection metadata. /// Whether the method is static. /// The or is null. /// The is null for a non-static method, or not null for a static method. - public ReflectedMethod(Type parentType, object obj, MethodInfo method, bool isStatic) + public ReflectedMethod(Type parentType, object? obj, MethodInfo method, bool isStatic) { // validate if (parentType == null) @@ -57,10 +55,10 @@ namespace StardewModdingAPI.Framework.Reflection } /// - public TValue Invoke(params object[] arguments) + public TValue? Invoke(params object?[] arguments) { // invoke method - object result; + object? result; try { result = this.MethodInfo.Invoke(this.Parent, arguments); @@ -77,7 +75,7 @@ namespace StardewModdingAPI.Framework.Reflection // cast return value try { - return (TValue)result; + return (TValue?)result; } catch (InvalidCastException) { @@ -86,7 +84,7 @@ namespace StardewModdingAPI.Framework.Reflection } /// - public void Invoke(params object[] arguments) + public void Invoke(params object?[] arguments) { // invoke method try diff --git a/src/SMAPI/Framework/Reflection/ReflectedProperty.cs b/src/SMAPI/Framework/Reflection/ReflectedProperty.cs index a6d8c75c..638953a3 100644 --- a/src/SMAPI/Framework/Reflection/ReflectedProperty.cs +++ b/src/SMAPI/Framework/Reflection/ReflectedProperty.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Reflection; @@ -16,10 +14,10 @@ namespace StardewModdingAPI.Framework.Reflection private readonly string DisplayName; /// The underlying property getter. - private readonly Func GetMethod; + private readonly Func? GetMethod; /// The underlying property setter. - private readonly Action SetMethod; + private readonly Action? SetMethod; /********* @@ -34,12 +32,12 @@ namespace StardewModdingAPI.Framework.Reflection *********/ /// Construct an instance. /// The type that has the property. - /// The object that has the instance property (if applicable). + /// The object that has the instance property, or null for a static property. /// The reflection metadata. /// Whether the property is static. /// The or is null. /// The is null for a non-static property, or not null for a static property. - public ReflectedProperty(Type parentType, object obj, PropertyInfo property, bool isStatic) + public ReflectedProperty(Type parentType, object? obj, PropertyInfo property, bool isStatic) { // validate input if (parentType == null) @@ -58,13 +56,13 @@ namespace StardewModdingAPI.Framework.Reflection this.PropertyInfo = property; if (this.PropertyInfo.GetMethod != null) - this.GetMethod = (Func)Delegate.CreateDelegate(typeof(Func), obj, this.PropertyInfo.GetMethod); + this.GetMethod = (Func)Delegate.CreateDelegate(typeof(Func), obj, this.PropertyInfo.GetMethod); if (this.PropertyInfo.SetMethod != null) - this.SetMethod = (Action)Delegate.CreateDelegate(typeof(Action), obj, this.PropertyInfo.SetMethod); + this.SetMethod = (Action)Delegate.CreateDelegate(typeof(Action), obj, this.PropertyInfo.SetMethod); } /// - public TValue GetValue() + public TValue? GetValue() { if (this.GetMethod == null) throw new InvalidOperationException($"The {this.DisplayName} property has no get method."); @@ -84,7 +82,7 @@ namespace StardewModdingAPI.Framework.Reflection } /// - public void SetValue(TValue value) + public void SetValue(TValue? value) { if (this.SetMethod == null) throw new InvalidOperationException($"The {this.DisplayName} property has no set method."); diff --git a/src/SMAPI/Framework/Rendering/SDisplayDevice.cs b/src/SMAPI/Framework/Rendering/SDisplayDevice.cs index 8718bcb1..37996b0f 100644 --- a/src/SMAPI/Framework/Rendering/SDisplayDevice.cs +++ b/src/SMAPI/Framework/Rendering/SDisplayDevice.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; @@ -27,7 +25,7 @@ namespace StardewModdingAPI.Framework.Rendering /// The tile to draw. /// The tile position to draw. /// The layer depth at which to draw. - public override void DrawTile(Tile tile, Location location, float layerDepth) + public override void DrawTile(Tile? tile, Location location, float layerDepth) { // identical to XnaDisplayDevice if (tile == null) @@ -58,7 +56,7 @@ namespace StardewModdingAPI.Framework.Rendering /// The tile being drawn. private SpriteEffects GetSpriteEffects(Tile tile) { - return tile.Properties.TryGetValue("@Flip", out PropertyValue propertyValue) && int.TryParse(propertyValue, out int value) + return tile.Properties.TryGetValue("@Flip", out PropertyValue? propertyValue) && int.TryParse(propertyValue, out int value) ? (SpriteEffects)value : SpriteEffects.None; } @@ -67,7 +65,7 @@ namespace StardewModdingAPI.Framework.Rendering /// The tile being drawn. private float GetRotation(Tile tile) { - if (!tile.Properties.TryGetValue("@Rotation", out PropertyValue propertyValue) || !int.TryParse(propertyValue, out int value)) + if (!tile.Properties.TryGetValue("@Rotation", out PropertyValue? propertyValue) || !int.TryParse(propertyValue, out int value)) return 0; value %= 360; diff --git a/src/SMAPI/Framework/Rendering/SXnaDisplayDevice.cs b/src/SMAPI/Framework/Rendering/SXnaDisplayDevice.cs index 21edaedd..94b13378 100644 --- a/src/SMAPI/Framework/Rendering/SXnaDisplayDevice.cs +++ b/src/SMAPI/Framework/Rendering/SXnaDisplayDevice.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -91,7 +89,7 @@ namespace StardewModdingAPI.Framework.Rendering /// The tile to draw. /// The tile position to draw. /// The layer depth at which to draw. - public virtual void DrawTile(Tile tile, Location location, float layerDepth) + public virtual void DrawTile(Tile? tile, Location location, float layerDepth) { if (tile == null) return; diff --git a/src/SMAPI/Framework/SGame.cs b/src/SMAPI/Framework/SGame.cs index 7ca89eec..4fa7fe7b 100644 --- a/src/SMAPI/Framework/SGame.cs +++ b/src/SMAPI/Framework/SGame.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; @@ -48,10 +46,10 @@ namespace StardewModdingAPI.Framework private readonly Action ExitGameImmediately; /// The initial override for . This value is null after initialization. - private SInputState InitialInput; + private SInputState? InitialInput; /// The initial override for . This value is null after initialization. - private SMultiplayer InitialMultiplayer; + private SMultiplayer? InitialMultiplayer; /// Raised when the instance is updating its state (roughly 60 times per second). private readonly Action OnUpdating; @@ -70,7 +68,7 @@ namespace StardewModdingAPI.Framework public Task NewDayTask => Game1._newDayTask; /// Monitors the entire game state for changes. - public WatcherCore Watchers { get; private set; } + public WatcherCore Watchers { get; private set; } = null!; // initialized on first update tick /// A snapshot of the current state. public WatcherSnapshot WatcherSnapshot { get; } = new(); @@ -94,7 +92,7 @@ namespace StardewModdingAPI.Framework /// Construct a content manager to read game content files. /// This must be static because the game accesses it before the constructor is called. [NonInstancedStatic] - public static Func CreateContentManagerImpl; + public static Func? CreateContentManagerImpl; /********* @@ -138,11 +136,10 @@ namespace StardewModdingAPI.Framework /// This is intended for use by and shouldn't be used directly in most cases. internal static SButtonState GetInputState(SButton button) { - SInputState input = Game1.input as SInputState; - if (input == null) + if (Game1.input is not SInputState inputHandler) throw new InvalidOperationException("SMAPI's input state is not in a ready state yet."); - return input.GetState(button); + return inputHandler.GetState(button); } /// @@ -172,13 +169,11 @@ namespace StardewModdingAPI.Framework { base.Initialize(); - // The game resets public static fields after the class is constructed (see - // GameRunner.SetInstanceDefaults), so SMAPI needs to re-override them here. + // The game resets public static fields after the class is constructed (see GameRunner.SetInstanceDefaults), so SMAPI needs to re-override them here. Game1.input = this.InitialInput; Game1.multiplayer = this.InitialMultiplayer; - // The Initial* fields should no longer be used after this point, since mods may - // further override them after initialization. + // The Initial* fields should no longer be used after this point, since mods may further override them after initialization. this.InitialInput = null; this.InitialMultiplayer = null; } @@ -251,6 +246,7 @@ namespace StardewModdingAPI.Framework Context.IsInDrawLoop = false; } +#nullable disable /// Replicate the game's draw logic with some changes for SMAPI. /// A snapshot of the game timing state. /// The render target, if any. @@ -258,6 +254,7 @@ namespace StardewModdingAPI.Framework [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "LocalVariableHidesMember", Justification = "copied from game code as-is")] + [SuppressMessage("ReSharper", "MergeIntoPattern", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "PossibleLossOfFraction", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "RedundantArgumentDefaultValue", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "RedundantBaseQualifier", Justification = "copied from game code as-is")] @@ -265,8 +262,9 @@ namespace StardewModdingAPI.Framework [SuppressMessage("ReSharper", "RedundantExplicitNullableCreation", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "RedundantTypeArgumentsOfMethod", Justification = "copied from game code as-is")] [SuppressMessage("ReSharper", "IdentifierTypo", Justification = "copied from game code as-is")] - [SuppressMessage("SMAPI.CommonErrors", "AvoidNetField", Justification = "copied from game code as-is")] + [SuppressMessage("ReSharper", "MergeIntoPattern", Justification = "copied from game code as-is")] [SuppressMessage("SMAPI.CommonErrors", "AvoidImplicitNetFieldCast", Justification = "copied from game code as-is")] + [SuppressMessage("SMAPI.CommonErrors", "AvoidNetField", Justification = "copied from game code as-is")] private void DrawImpl(GameTime gameTime, RenderTarget2D target_screen) { var events = this.Events; @@ -952,5 +950,6 @@ namespace StardewModdingAPI.Framework this.drawOverlays(Game1.spriteBatch); Game1.PopUIMode(); } +#nullable enable } } diff --git a/src/SMAPI/Framework/SModHooks.cs b/src/SMAPI/Framework/SModHooks.cs index 7941e102..a7736c8b 100644 --- a/src/SMAPI/Framework/SModHooks.cs +++ b/src/SMAPI/Framework/SModHooks.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Threading.Tasks; using StardewValley; @@ -35,7 +33,7 @@ namespace StardewModdingAPI.Framework /// The vanilla logic. public override void OnGame1_NewDayAfterFade(Action action) { - this.BeforeNewDayAfterFade?.Invoke(); + this.BeforeNewDayAfterFade(); action(); } diff --git a/src/SMAPI/Framework/SnapshotDiff.cs b/src/SMAPI/Framework/SnapshotDiff.cs index eb2aebe1..d659d2b4 100644 --- a/src/SMAPI/Framework/SnapshotDiff.cs +++ b/src/SMAPI/Framework/SnapshotDiff.cs @@ -1,5 +1,3 @@ -#nullable disable - using StardewModdingAPI.Framework.StateTracking; namespace StardewModdingAPI.Framework @@ -15,10 +13,10 @@ namespace StardewModdingAPI.Framework public bool IsChanged { get; private set; } /// The previous value. - public T Old { get; private set; } + public T? Old { get; private set; } /// The current value. - public T New { get; private set; } + public T? New { get; private set; } /********* diff --git a/src/SMAPI/Framework/SnapshotItemListDiff.cs b/src/SMAPI/Framework/SnapshotItemListDiff.cs index 97942783..76060db2 100644 --- a/src/SMAPI/Framework/SnapshotItemListDiff.cs +++ b/src/SMAPI/Framework/SnapshotItemListDiff.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Events; using StardewValley; @@ -48,7 +47,7 @@ namespace StardewModdingAPI.Framework /// The items with their previous stack sizes. /// The inventory changes, or null if nothing changed. /// Returns whether anything changed. - public static bool TryGetChanges(ISet added, ISet removed, IDictionary stackSizes, out SnapshotItemListDiff changes) + public static bool TryGetChanges(ISet added, ISet removed, IDictionary stackSizes, [NotNullWhen(true)] out SnapshotItemListDiff? changes) { KeyValuePair[] sizesChanged = stackSizes.Where(p => p.Key.Stack != p.Value).ToArray(); if (sizesChanged.Any() || added.Any() || removed.Any()) diff --git a/src/SMAPI/Framework/SnapshotListDiff.cs b/src/SMAPI/Framework/SnapshotListDiff.cs index 1d585c15..90066af1 100644 --- a/src/SMAPI/Framework/SnapshotListDiff.cs +++ b/src/SMAPI/Framework/SnapshotListDiff.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using StardewModdingAPI.Framework.StateTracking; @@ -39,7 +37,7 @@ namespace StardewModdingAPI.Framework /// Whether the value changed since the last update. /// The removed values. /// The added values. - public void Update(bool isChanged, IEnumerable removed, IEnumerable added) + public void Update(bool isChanged, IEnumerable? removed, IEnumerable? added) { this.IsChanged = isChanged; diff --git a/src/SMAPI/Framework/StateTracking/ChestTracker.cs b/src/SMAPI/Framework/StateTracking/ChestTracker.cs index 28335200..c33a7498 100644 --- a/src/SMAPI/Framework/StateTracking/ChestTracker.cs +++ b/src/SMAPI/Framework/StateTracking/ChestTracker.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Framework.StateTracking.Comparers; using StardewModdingAPI.Framework.StateTracking.FieldWatchers; @@ -86,7 +85,7 @@ namespace StardewModdingAPI.Framework.StateTracking /// Get the inventory changes since the last update, if anything changed. /// The inventory changes, or null if nothing changed. /// Returns whether anything changed. - public bool TryGetInventoryChanges(out SnapshotItemListDiff changes) + public bool TryGetInventoryChanges([NotNullWhen(true)] out SnapshotItemListDiff? changes) { return SnapshotItemListDiff.TryGetChanges(added: this.Added, removed: this.Removed, stackSizes: this.StackSizes, out changes); } diff --git a/src/SMAPI/Framework/StateTracking/Comparers/EquatableComparer.cs b/src/SMAPI/Framework/StateTracking/Comparers/EquatableComparer.cs index 987e1820..9d8559b4 100644 --- a/src/SMAPI/Framework/StateTracking/Comparers/EquatableComparer.cs +++ b/src/SMAPI/Framework/StateTracking/Comparers/EquatableComparer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -17,7 +15,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Comparers /// true if the specified objects are equal; otherwise, false. /// The first object to compare. /// The second object to compare. - public bool Equals(T x, T y) + public bool Equals(T? x, T? y) { if (x == null) return y == null; diff --git a/src/SMAPI/Framework/StateTracking/Comparers/GenericEqualsComparer.cs b/src/SMAPI/Framework/StateTracking/Comparers/GenericEqualsComparer.cs index f6b04583..41b17e10 100644 --- a/src/SMAPI/Framework/StateTracking/Comparers/GenericEqualsComparer.cs +++ b/src/SMAPI/Framework/StateTracking/Comparers/GenericEqualsComparer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -16,7 +14,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Comparers /// true if the specified objects are equal; otherwise, false. /// The first object to compare. /// The second object to compare. - public bool Equals(T x, T y) + public bool Equals(T? x, T? y) { if (x == null) return y == null; diff --git a/src/SMAPI/Framework/StateTracking/Comparers/ObjectReferenceComparer.cs b/src/SMAPI/Framework/StateTracking/Comparers/ObjectReferenceComparer.cs index 8d3a7eb9..e6ece854 100644 --- a/src/SMAPI/Framework/StateTracking/Comparers/ObjectReferenceComparer.cs +++ b/src/SMAPI/Framework/StateTracking/Comparers/ObjectReferenceComparer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Runtime.CompilerServices; @@ -16,7 +14,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Comparers /// true if the specified objects are equal; otherwise, false. /// The first object to compare. /// The second object to compare. - public bool Equals(T x, T y) + public bool Equals(T? x, T? y) { return object.ReferenceEquals(x, y); } diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/NetDictionaryWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/NetDictionaryWatcher.cs index 0d7f2ad2..f55e4cea 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/NetDictionaryWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/NetDictionaryWatcher.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using Netcode; @@ -12,6 +10,7 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// The serializable dictionary type that can store the keys and values. /// The net field instance type. internal class NetDictionaryWatcher : BaseDisposableWatcher, IDictionaryWatcher + where TKey : notnull where TField : class, INetObject, new() where TSerialDict : IDictionary, new() where TSelf : NetDictionary diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs index 82e5387e..97aedca8 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ObservableCollectionWatcher.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; @@ -81,7 +79,7 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// A callback invoked when an entry is added or removed from the collection. /// The event sender. /// The event arguments. - private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) + private void OnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Reset) { @@ -90,8 +88,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers } else { - TValue[] added = e.NewItems?.Cast().ToArray(); - TValue[] removed = e.OldItems?.Cast().ToArray(); + TValue[]? added = e.NewItems?.Cast().ToArray(); + TValue[]? removed = e.OldItems?.Cast().ToArray(); if (removed != null) { diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/WatcherFactory.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/WatcherFactory.cs index 0b99914c..c4a4d0b9 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/WatcherFactory.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/WatcherFactory.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -20,7 +18,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// Get a watcher which compares values using their method. This method should only be used when won't work, since this doesn't validate whether they're comparable. /// The value type. /// Get the current value. - public static IValueWatcher ForGenericEquality(Func getValue) where T : struct + public static IValueWatcher ForGenericEquality(Func getValue) + where T : struct { return new ComparableWatcher(getValue, new GenericEqualsComparer()); } @@ -28,7 +27,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// Get a watcher for an value. /// The value type. /// Get the current value. - public static IValueWatcher ForEquatable(Func getValue) where T : IEquatable + public static IValueWatcher ForEquatable(Func getValue) + where T : IEquatable { return new ComparableWatcher(getValue, new EquatableComparer()); } @@ -79,7 +79,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// Get a watcher for a net collection. /// The value type. /// The net collection. - public static ICollectionWatcher ForNetCollection(NetCollection collection) where T : class, INetObject + public static ICollectionWatcher ForNetCollection(NetCollection collection) + where T : class, INetObject { return new NetCollectionWatcher(collection); } @@ -87,7 +88,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// Get a watcher for a net list. /// The value type. /// The net list. - public static ICollectionWatcher ForNetList(NetList> collection) where T : class, INetObject + public static ICollectionWatcher ForNetList(NetList> collection) + where T : class, INetObject { return new NetListWatcher(collection); } @@ -100,6 +102,7 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers /// The net field instance type. /// The net field. public static NetDictionaryWatcher ForNetDictionary(NetDictionary field) + where TKey : notnull where TField : class, INetObject, new() where TSerialDict : IDictionary, new() where TSelf : NetDictionary diff --git a/src/SMAPI/Framework/StateTracking/LocationTracker.cs b/src/SMAPI/Framework/StateTracking/LocationTracker.cs index 9c2ff7f0..ff72a19b 100644 --- a/src/SMAPI/Framework/StateTracking/LocationTracker.cs +++ b/src/SMAPI/Framework/StateTracking/LocationTracker.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -132,20 +130,20 @@ namespace StardewModdingAPI.Framework.StateTracking private void UpdateChestWatcherList(IEnumerable> added, IEnumerable> removed) { // remove unused watchers - foreach (KeyValuePair pair in removed) + foreach ((Vector2 tile, SObject? obj) in removed) { - if (pair.Value is Chest && this.ChestWatchers.TryGetValue(pair.Key, out ChestTracker watcher)) + if (obj is Chest && this.ChestWatchers.TryGetValue(tile, out ChestTracker? watcher)) { watcher.Dispose(); - this.ChestWatchers.Remove(pair.Key); + this.ChestWatchers.Remove(tile); } } // add new watchers - foreach (KeyValuePair pair in added) + foreach ((Vector2 tile, SObject? obj) in added) { - if (pair.Value is Chest chest && !this.ChestWatchers.ContainsKey(pair.Key)) - this.ChestWatchers.Add(pair.Key, new ChestTracker(chest)); + if (obj is Chest chest && !this.ChestWatchers.ContainsKey(tile)) + this.ChestWatchers.Add(tile, new ChestTracker(chest)); } } } diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs index 3d13f92b..0d0469d7 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/LocationSnapshot.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using Microsoft.Xna.Framework; using StardewValley; @@ -70,7 +68,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots this.ChestItems.Clear(); foreach (ChestTracker tracker in watcher.ChestWatchers.Values) { - if (tracker.TryGetInventoryChanges(out SnapshotItemListDiff changes)) + if (tracker.TryGetInventoryChanges(out SnapshotItemListDiff? changes)) this.ChestItems[tracker.Chest] = changes; } } diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs index 1d43ef26..27a891de 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WatcherSnapshot.cs @@ -1,5 +1,3 @@ -#nullable disable - using Microsoft.Xna.Framework; using StardewValley; using StardewValley.Menus; @@ -16,7 +14,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots public SnapshotDiff WindowSize { get; } = new(); /// Tracks changes to the current player. - public PlayerSnapshot CurrentPlayer { get; private set; } + public PlayerSnapshot? CurrentPlayer { get; private set; } /// Tracks changes to the time of day (in 24-hour military format). public SnapshotDiff Time { get; } = new(); @@ -56,7 +54,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots // update snapshots this.WindowSize.Update(watchers.WindowSizeWatcher); this.Locale.Update(watchers.LocaleWatcher); - this.CurrentPlayer?.Update(watchers.CurrentPlayerTracker); + this.CurrentPlayer?.Update(watchers.CurrentPlayerTracker!); this.Time.Update(watchers.TimeWatcher); this.SaveID.Update(watchers.SaveIdWatcher); this.Locations.Update(watchers.LocationsWatcher); diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs index 88aac0df..59f94942 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/WorldLocationsSnapshot.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Linq; using StardewModdingAPI.Framework.StateTracking.Comparers; @@ -44,7 +42,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots // update locations foreach (LocationTracker locationWatcher in watcher.Locations) { - if (!this.LocationsDict.TryGetValue(locationWatcher.Location, out LocationSnapshot snapshot)) + if (!this.LocationsDict.TryGetValue(locationWatcher.Location, out LocationSnapshot? snapshot)) this.LocationsDict[locationWatcher.Location] = snapshot = new LocationSnapshot(locationWatcher.Location); snapshot.Update(locationWatcher); diff --git a/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs b/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs index ab02d7d5..817a6011 100644 --- a/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs +++ b/src/SMAPI/Framework/StateTracking/WorldLocationsTracker.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; @@ -27,10 +25,10 @@ namespace StardewModdingAPI.Framework.StateTracking private readonly ICollectionWatcher VolcanoLocationListWatcher; /// A lookup of the tracked locations. - private IDictionary LocationDict { get; } = new Dictionary(new ObjectReferenceComparer()); + private Dictionary LocationDict { get; } = new(new ObjectReferenceComparer()); /// A lookup of registered buildings and their indoor location. - private readonly IDictionary BuildingIndoors = new Dictionary(new ObjectReferenceComparer()); + private readonly Dictionary BuildingIndoors = new(new ObjectReferenceComparer()); /********* @@ -101,10 +99,9 @@ namespace StardewModdingAPI.Framework.StateTracking } // detect building interiors changed (e.g. construction completed) - foreach (KeyValuePair pair in this.BuildingIndoors.Where(p => !object.Equals(p.Key.indoors.Value, p.Value))) + foreach ((Building building, GameLocation? oldIndoors) in this.BuildingIndoors.Where(p => !object.Equals(p.Key.indoors.Value, p.Value))) { - GameLocation oldIndoors = pair.Value; - GameLocation newIndoors = pair.Key.indoors.Value; + GameLocation? newIndoors = building.indoors.Value; if (oldIndoors != null) this.Added.Add(oldIndoors); @@ -189,19 +186,19 @@ namespace StardewModdingAPI.Framework.StateTracking ****/ /// Add the given building. /// The building to add. - public void Add(Building building) + public void Add(Building? building) { if (building == null) return; - GameLocation indoors = building.indoors.Value; + GameLocation? indoors = building.indoors.Value; this.BuildingIndoors[building] = indoors; this.Add(indoors); } /// Add the given location. /// The location to add. - public void Add(GameLocation location) + public void Add(GameLocation? location) { if (location == null) return; @@ -220,7 +217,7 @@ namespace StardewModdingAPI.Framework.StateTracking /// Remove the given building. /// The building to remove. - public void Remove(Building building) + public void Remove(Building? building) { if (building == null) return; @@ -231,12 +228,12 @@ namespace StardewModdingAPI.Framework.StateTracking /// Remove the given location. /// The location to remove. - public void Remove(GameLocation location) + public void Remove(GameLocation? location) { if (location == null) return; - if (this.LocationDict.TryGetValue(location, out LocationTracker watcher)) + if (this.LocationDict.TryGetValue(location, out LocationTracker? watcher)) { // track change this.Removed.Add(location); diff --git a/src/SMAPI/Framework/Translator.cs b/src/SMAPI/Framework/Translator.cs index 144b043c..794e3cde 100644 --- a/src/SMAPI/Framework/Translator.cs +++ b/src/SMAPI/Framework/Translator.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewValley; @@ -23,7 +22,7 @@ namespace StardewModdingAPI.Framework /********* ** Accessors *********/ - /// The current locale. + /// The current locale code like fr-FR, or an empty string for English. public string Locale { get; private set; } /// The game's current language code. @@ -39,9 +38,10 @@ namespace StardewModdingAPI.Framework this.SetLocale(string.Empty, LocalizedContentManager.LanguageCode.en); } - /// Set the current locale and precache translations. + /// Set the current locale and pre-cache translations. /// The current locale. /// The game's current language code. + [MemberNotNull(nameof(Translator.ForLocale), nameof(Translator.Locale))] public void SetLocale(string locale, LocalizedContentManager.LanguageCode localeEnum) { this.Locale = locale.ToLower().Trim(); @@ -50,7 +50,7 @@ namespace StardewModdingAPI.Framework this.ForLocale = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string key in this.GetAllKeysRaw()) { - string text = this.GetRaw(key, locale, withFallback: true); + string? text = this.GetRaw(key, locale, withFallback: true); this.ForLocale.Add(key, new Translation(this.Locale, key, text)); } } @@ -65,7 +65,7 @@ namespace StardewModdingAPI.Framework /// The translation key. public Translation Get(string key) { - this.ForLocale.TryGetValue(key, out Translation translation); + this.ForLocale.TryGetValue(key, out Translation? translation); return translation ?? new Translation(this.Locale, key, null); } @@ -87,7 +87,7 @@ namespace StardewModdingAPI.Framework foreach (var localeSet in this.All) { string locale = localeSet.Key; - string text = this.GetRaw(key, locale, withFallback); + string? text = this.GetRaw(key, locale, withFallback); if (text != null) translations[locale] = new Translation(locale, key, text); @@ -128,13 +128,13 @@ namespace StardewModdingAPI.Framework /// The translation key. /// The locale to get. /// Whether to add duplicate translations for locale fallback. For example, if a translation is defined in default.json but not fr.json, setting this to true will add a fr entry which duplicates the default text. - private string GetRaw(string key, string locale, bool withFallback) + private string? GetRaw(string key, string locale, bool withFallback) { foreach (string next in this.GetRelevantLocales(locale)) { - string translation = null; + string? translation = null; bool hasTranslation = - this.All.TryGetValue(next, out IDictionary translations) + this.All.TryGetValue(next, out IDictionary? translations) && translations.TryGetValue(key, out translation); if (hasTranslation) diff --git a/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs index 94ce0069..20d206e2 100644 --- a/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs +++ b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; @@ -9,6 +7,7 @@ namespace StardewModdingAPI.Framework.Utilities /// The dictionary key type. /// The dictionary value type. internal class TickCacheDictionary + where TKey : notnull { /********* ** Fields @@ -36,7 +35,7 @@ namespace StardewModdingAPI.Framework.Utilities } // fetch value - if (!this.Cache.TryGetValue(cacheKey, out TValue cached)) + if (!this.Cache.TryGetValue(cacheKey, out TValue? cached)) this.Cache[cacheKey] = cached = get(); return cached; } diff --git a/src/SMAPI/Framework/WatcherCore.cs b/src/SMAPI/Framework/WatcherCore.cs index bd8d3367..5e20ac7b 100644 --- a/src/SMAPI/Framework/WatcherCore.cs +++ b/src/SMAPI/Framework/WatcherCore.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Xna.Framework; @@ -29,7 +27,7 @@ namespace StardewModdingAPI.Framework public readonly IValueWatcher WindowSizeWatcher; /// Tracks changes to the current player. - public PlayerTracker CurrentPlayerTracker; + public PlayerTracker? CurrentPlayerTracker; /// Tracks changes to the time of day (in 24-hour military format). public readonly IValueWatcher TimeWatcher; diff --git a/src/SMAPI/IAssetData.cs b/src/SMAPI/IAssetData.cs index f07340e4..1ec09d87 100644 --- a/src/SMAPI/IAssetData.cs +++ b/src/SMAPI/IAssetData.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI @@ -7,6 +5,7 @@ namespace StardewModdingAPI /// Generic metadata and methods for a content asset being loaded. /// The expected data type. public interface IAssetData : IAssetInfo + where TValue : notnull { /********* ** Accessors diff --git a/src/SMAPI/IAssetInfo.cs b/src/SMAPI/IAssetInfo.cs index 5b4ac479..4d651a72 100644 --- a/src/SMAPI/IAssetInfo.cs +++ b/src/SMAPI/IAssetInfo.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI @@ -11,7 +9,7 @@ namespace StardewModdingAPI ** Accessors *********/ /// The content's locale code, if the content is localized. - string Locale { get; } + string? Locale { get; } /// The asset name being read. /// NOTE: when reading this field from an or implementation, it's always equivalent to for backwards compatibility. diff --git a/src/SMAPI/IAssetName.cs b/src/SMAPI/IAssetName.cs index 22f5c6b7..71b6ed6b 100644 --- a/src/SMAPI/IAssetName.cs +++ b/src/SMAPI/IAssetName.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewValley; @@ -18,7 +16,7 @@ namespace StardewModdingAPI string BaseName { get; } /// The locale code specified in the , if it's a valid code recognized by the game content. - string LocaleCode { get; } + string? LocaleCode { get; } /// The language code matching the , if applicable. LocalizedContentManager.LanguageCode? LanguageCode { get; } @@ -30,23 +28,23 @@ namespace StardewModdingAPI /// Get whether the given asset name is equivalent, ignoring capitalization and formatting. /// The asset name to compare this instance to. /// Whether to compare the given name with the (if true) or (if false). This has no effect on any locale included in the given . - bool IsEquivalentTo(string assetName, bool useBaseName = false); + bool IsEquivalentTo(string? assetName, bool useBaseName = false); /// Get whether the given asset name is equivalent, ignoring capitalization and formatting. /// The asset name to compare this instance to. /// Whether to compare the given name with the (if true) or (if false). - bool IsEquivalentTo(IAssetName assetName, bool useBaseName = false); + bool IsEquivalentTo(IAssetName? assetName, bool useBaseName = false); /// Get whether the asset name starts with the given value, ignoring capitalization and formatting. This can be used with a trailing slash to test for an asset folder, like Data/. /// The prefix to match. /// Whether to match if the prefix occurs mid-word, so Data/AchievementsToIgnore matches prefix Data/Achievements. If this is false, the prefix only matches if the asset name starts with the prefix followed by a non-alphanumeric character (including ., /, or \\) or the end of string. /// Whether to match the prefix if there's a subfolder path after it, so Data/Achievements/Example matches prefix Data/Achievements. If this is false, the prefix only matches if the asset name has no / or \\ characters after the prefix. - bool StartsWith(string prefix, bool allowPartialWord = true, bool allowSubfolder = true); + bool StartsWith(string? prefix, bool allowPartialWord = true, bool allowSubfolder = true); /// Get whether the asset is directly within the given asset path. /// For example, Characters/Dialogue/Abigail is directly under Characters/Dialogue but not Characters or Characters/Dialogue/Ab. To allow sub-paths, use instead. /// The asset path to check. This doesn't need a trailing slash. - bool IsDirectlyUnderPath(string assetFolder); + bool IsDirectlyUnderPath(string? assetFolder); /// Get an asset name representing the without locale. internal IAssetName GetBaseAssetName(); diff --git a/src/SMAPI/IContentHelper.cs b/src/SMAPI/IContentHelper.cs index 0ad209ab..2cd0c1fc 100644 --- a/src/SMAPI/IContentHelper.cs +++ b/src/SMAPI/IContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.Contracts; @@ -42,12 +40,14 @@ namespace StardewModdingAPI /// Where to search for a matching content asset. /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). - T Load(string key, ContentSource source = ContentSource.ModFolder); + T Load(string key, ContentSource source = ContentSource.ModFolder) + where T : notnull; /// Normalize an asset name so it's consistent with those generated by the game. This is mainly useful for string comparisons like on generated asset names, and isn't necessary when passing asset names into other content helper methods. /// The asset key. + /// The asset key is empty or contains invalid characters. [Pure] - string NormalizeAssetName(string assetName); + string NormalizeAssetName(string? assetName); /// Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists. /// The asset key to fetch (if the is ), or the local path to a content file relative to the mod folder. @@ -64,7 +64,8 @@ namespace StardewModdingAPI /// Remove all assets of the given type from the cache so they're reloaded on the next request. This can be a very expensive operation and should only be used in very specific cases. This will reload core game assets if needed, but references to the former assets will still show the previous content. /// The asset type to remove from the cache. /// Returns whether any assets were invalidated. - bool InvalidateCache(); + bool InvalidateCache() + where T : notnull; /// Remove matching assets from the content cache so they're reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content. /// A predicate matching the assets to invalidate. @@ -75,6 +76,7 @@ namespace StardewModdingAPI /// The data type. /// The asset data. /// The asset name. This is only used for tracking purposes and has no effect on the patch helper. - IAssetData GetPatchHelper(T data, string assetName = null); + IAssetData GetPatchHelper(T data, string? assetName = null) + where T : notnull; } } diff --git a/src/SMAPI/IContentPack.cs b/src/SMAPI/IContentPack.cs index f853e2b4..1215fe0b 100644 --- a/src/SMAPI/IContentPack.cs +++ b/src/SMAPI/IContentPack.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; @@ -38,14 +36,16 @@ namespace StardewModdingAPI /// The relative file path within the content pack (case-insensitive). /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). - TModel ReadJsonFile(string path) where TModel : class; + TModel? ReadJsonFile(string path) + where TModel : class; /// Save data to a JSON file in the content pack's folder. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The relative file path within the content pack (case-insensitive). /// The arbitrary data to save. /// The is not relative or contains directory climbing (../). - void WriteJsonFile(string path, TModel data) where TModel : class; + void WriteJsonFile(string path, TModel data) + where TModel : class; /// Load content from the content pack folder (if not already cached), and return it. When loading a .png file, this must be called outside the game's draw loop. /// The expected data type. The main supported types are , , and dictionaries; other types may be supported by the game's content pipeline. @@ -53,7 +53,8 @@ namespace StardewModdingAPI /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). [Obsolete($"Use {nameof(IContentPack.ModContent)}.{nameof(IModContentHelper.Load)} instead. This method will be removed in SMAPI 4.0.0.")] - T LoadAsset(string key); + T LoadAsset(string key) + where T : notnull; /// Get the underlying key in the game's content cache for an asset. This can be used to load custom map tilesheets, but should be avoided when you can use the content API instead. This does not validate whether the asset exists. /// The relative file path within the content pack (case-insensitive). diff --git a/src/SMAPI/IDataHelper.cs b/src/SMAPI/IDataHelper.cs index 4c96367b..7ddf851e 100644 --- a/src/SMAPI/IDataHelper.cs +++ b/src/SMAPI/IDataHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI @@ -18,14 +16,16 @@ namespace StardewModdingAPI /// The file path relative to the mod folder. /// Returns the deserialized model, or null if the file doesn't exist or is empty. /// The is not relative or contains directory climbing (../). - TModel ReadJsonFile(string path) where TModel : class; + TModel? ReadJsonFile(string path) + where TModel : class; /// Save data to a JSON file in the mod's folder. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The file path relative to the mod folder. /// The arbitrary data to save, or null to delete the file. /// The is not relative or contains directory climbing (../). - void WriteJsonFile(string path, TModel data) where TModel : class; + void WriteJsonFile(string path, TModel? data) + where TModel : class; /**** ** Save file @@ -35,14 +35,16 @@ namespace StardewModdingAPI /// The unique key identifying the data. /// Returns the parsed data, or null if the entry doesn't exist or is empty. /// The player hasn't loaded a save file yet or isn't the main player. - TModel ReadSaveData(string key) where TModel : class; + TModel? ReadSaveData(string key) + where TModel : class; /// Save arbitrary data to the current save slot. This is only possible if a save has been loaded, and the data will be lost if the player exits without saving the current day. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The unique key identifying the data. /// The arbitrary data to save, or null to remove the entry. /// The player hasn't loaded a save file yet or isn't the main player. - void WriteSaveData(string key, TModel data) where TModel : class; + void WriteSaveData(string key, TModel? data) + where TModel : class; /**** @@ -52,12 +54,14 @@ namespace StardewModdingAPI /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The unique key identifying the data. /// Returns the parsed data, or null if the entry doesn't exist or is empty. - TModel ReadGlobalData(string key) where TModel : class; + TModel? ReadGlobalData(string key) + where TModel : class; /// Save arbitrary data to the local computer, synchronised by GOG/Steam if applicable. /// The model type. This should be a plain class that has public properties for the data you want. The properties can be complex types. /// The unique key identifying the data. /// The arbitrary data to save, or null to delete the file. - void WriteGlobalData(string key, TModel data) where TModel : class; + void WriteGlobalData(string key, TModel? data) + where TModel : class; } } diff --git a/src/SMAPI/IGameContentHelper.cs b/src/SMAPI/IGameContentHelper.cs index 4b967993..d40d0c82 100644 --- a/src/SMAPI/IGameContentHelper.cs +++ b/src/SMAPI/IGameContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; @@ -35,14 +33,16 @@ namespace StardewModdingAPI /// The asset name to load. /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). - T Load(string assetName); + T Load(string assetName) + where T : notnull; /// Load content from the game folder or mod folder (if not already cached), and return it. When loading a .png file, this must be called outside the game's draw loop. /// The expected data type. The main supported types are , , dictionaries, and lists; other types may be supported by the game's content pipeline. /// The asset name to load. /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). - T Load(IAssetName assetName); + T Load(IAssetName assetName) + where T : notnull; /// Remove an asset from the content cache so it's reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content. /// The asset key to invalidate in the content folder. @@ -59,7 +59,8 @@ namespace StardewModdingAPI /// Remove all assets of the given type from the cache so they're reloaded on the next request. This can be a very expensive operation and should only be used in very specific cases. This will reload core game assets if needed, but references to the former assets will still show the previous content. /// The asset type to remove from the cache. /// Returns whether any assets were invalidated. - bool InvalidateCache(); + bool InvalidateCache() + where T : notnull; /// Remove matching assets from the content cache so they're reloaded on the next request. This will reload core game assets if needed, but references to the former asset will still show the previous content. /// A predicate matching the assets to invalidate. @@ -70,6 +71,7 @@ namespace StardewModdingAPI /// The data type. /// The asset data. /// The asset name. This is only used for tracking purposes and has no effect on the patch helper. - IAssetData GetPatchHelper(T data, string assetName = null); + IAssetData GetPatchHelper(T data, string? assetName = null) + where T : notnull; } } diff --git a/src/SMAPI/IMod.cs b/src/SMAPI/IMod.cs index 0de4961e..b81ba0e3 100644 --- a/src/SMAPI/IMod.cs +++ b/src/SMAPI/IMod.cs @@ -1,5 +1,3 @@ -#nullable disable - namespace StardewModdingAPI { /// The implementation for a Stardew Valley mod. @@ -26,6 +24,6 @@ namespace StardewModdingAPI void Entry(IModHelper helper); /// Get an API that other mods can access. This is always called after . - object GetApi(); + object? GetApi(); } } diff --git a/src/SMAPI/IModContentHelper.cs b/src/SMAPI/IModContentHelper.cs index 815d6848..f1f6ce94 100644 --- a/src/SMAPI/IModContentHelper.cs +++ b/src/SMAPI/IModContentHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; @@ -18,7 +16,8 @@ namespace StardewModdingAPI /// The local path to a content file relative to the mod folder. /// The is empty or contains invalid characters. /// The content asset couldn't be loaded (e.g. because it doesn't exist). - T Load(string relativePath); + T Load(string relativePath) + where T : notnull; /// Get the internal asset name which allows loading a mod file through any of the game's content managers. This can be used when passing asset names directly to the game (e.g. for map tilesheets), but should be avoided if you can use instead. This does not validate whether the asset exists. /// The local path to a content file relative to the mod folder. @@ -29,6 +28,7 @@ namespace StardewModdingAPI /// The data type. /// The asset data. /// The local path to the content file being edited relative to the mod folder. This is only used for tracking purposes and has no effect on the patch helper. - IAssetData GetPatchHelper(T data, string relativePath = null); + IAssetData GetPatchHelper(T data, string? relativePath = null) + where T : notnull; } } diff --git a/src/SMAPI/IModRegistry.cs b/src/SMAPI/IModRegistry.cs index 9cab08a1..cf60bc29 100644 --- a/src/SMAPI/IModRegistry.cs +++ b/src/SMAPI/IModRegistry.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; namespace StardewModdingAPI @@ -13,7 +11,7 @@ namespace StardewModdingAPI /// Get metadata for a loaded mod. /// The mod's unique ID. /// Returns the matching mod's metadata, or null if not found. - IModInfo Get(string uniqueID); + IModInfo? Get(string uniqueID); /// Get whether a mod has been loaded. /// The mod's unique ID. @@ -21,11 +19,12 @@ namespace StardewModdingAPI /// Get the API provided by a mod, or null if it has none. This signature requires using the API to access the API's properties and methods. /// The mod's unique ID. - object GetApi(string uniqueID); + object? GetApi(string uniqueID); /// Get the API provided by a mod, mapped to a given interface which specifies the expected properties and methods. If the mod has no API or it's not compatible with the given interface, get null. /// The interface which matches the properties and methods you intend to access. /// The mod's unique ID. - TInterface GetApi(string uniqueID) where TInterface : class; + TInterface? GetApi(string uniqueID) + where TInterface : class; } } diff --git a/src/SMAPI/IMultiplayerHelper.cs b/src/SMAPI/IMultiplayerHelper.cs index 77a0f3f4..bb851410 100644 --- a/src/SMAPI/IMultiplayerHelper.cs +++ b/src/SMAPI/IMultiplayerHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using StardewValley; @@ -18,7 +16,7 @@ namespace StardewModdingAPI /// Get a connected player. /// The player's unique ID. /// Returns the connected player, or null if no such player is connected. - IMultiplayerPeer GetConnectedPlayer(long id); + IMultiplayerPeer? GetConnectedPlayer(long id); /// Get all connected players. IEnumerable GetConnectedPlayers(); @@ -30,6 +28,6 @@ namespace StardewModdingAPI /// The mod IDs which should receive the message on the destination computers, or null for all mods. Specifying mod IDs is recommended to improve performance, unless it's a general-purpose broadcast. /// The values for the players who should receive the message, or null for all players. If you don't need to broadcast to all players, specifying player IDs is recommended to reduce latency. /// The or is null. - void SendMessage(TMessage message, string messageType, string[] modIDs = null, long[] playerIDs = null); + void SendMessage(TMessage message, string messageType, string[]? modIDs = null, long[]? playerIDs = null); } } diff --git a/src/SMAPI/IMultiplayerPeer.cs b/src/SMAPI/IMultiplayerPeer.cs index e487f100..8b0062b5 100644 --- a/src/SMAPI/IMultiplayerPeer.cs +++ b/src/SMAPI/IMultiplayerPeer.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace StardewModdingAPI { @@ -20,6 +19,7 @@ namespace StardewModdingAPI bool IsSplitScreen { get; } /// Whether the player has SMAPI installed. + [MemberNotNullWhen(true, nameof(IMultiplayerPeer.Platform), nameof(IMultiplayerPeer.GameVersion), nameof(IMultiplayerPeer.ApiVersion), nameof(IMultiplayerPeer.Mods))] bool HasSmapi { get; } /// The player's screen ID, if applicable. @@ -30,10 +30,10 @@ namespace StardewModdingAPI GamePlatform? Platform { get; } /// The installed version of Stardew Valley, if is true. - ISemanticVersion GameVersion { get; } + ISemanticVersion? GameVersion { get; } /// The installed version of SMAPI, if is true. - ISemanticVersion ApiVersion { get; } + ISemanticVersion? ApiVersion { get; } /// The installed mods, if is true. IEnumerable Mods { get; } @@ -45,6 +45,6 @@ namespace StardewModdingAPI /// Get metadata for a mod installed by the player. /// The unique mod ID. /// Returns the mod info, or null if the player doesn't have that mod. - IMultiplayerPeerMod GetMod(string id); + IMultiplayerPeerMod? GetMod(string? id); } } diff --git a/src/SMAPI/IReflectedField.cs b/src/SMAPI/IReflectedField.cs index 94dbe6a3..5a24b3dc 100644 --- a/src/SMAPI/IReflectedField.cs +++ b/src/SMAPI/IReflectedField.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Reflection; namespace StardewModdingAPI @@ -19,10 +17,10 @@ namespace StardewModdingAPI ** Public methods *********/ /// Get the field value. - TValue GetValue(); + TValue? GetValue(); /// Set the field value. //// The value to set. - void SetValue(TValue value); + void SetValue(TValue? value); } } diff --git a/src/SMAPI/IReflectedMethod.cs b/src/SMAPI/IReflectedMethod.cs index 78e66cb1..6d87966a 100644 --- a/src/SMAPI/IReflectedMethod.cs +++ b/src/SMAPI/IReflectedMethod.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Reflection; namespace StardewModdingAPI @@ -20,10 +18,10 @@ namespace StardewModdingAPI /// Invoke the method. /// The return type. /// The method arguments to pass in. - TValue Invoke(params object[] arguments); + TValue? Invoke(params object?[] arguments); /// Invoke the method. /// The method arguments to pass in. - void Invoke(params object[] arguments); + void Invoke(params object?[] arguments); } } diff --git a/src/SMAPI/IReflectedProperty.cs b/src/SMAPI/IReflectedProperty.cs index edbf0b21..ad55b9a1 100644 --- a/src/SMAPI/IReflectedProperty.cs +++ b/src/SMAPI/IReflectedProperty.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Reflection; namespace StardewModdingAPI @@ -19,10 +17,10 @@ namespace StardewModdingAPI ** Public methods *********/ /// Get the property value. - TValue GetValue(); + TValue? GetValue(); /// Set the property value. //// The value to set. - void SetValue(TValue value); + void SetValue(TValue? value); } } diff --git a/src/SMAPI/IReflectionHelper.cs b/src/SMAPI/IReflectionHelper.cs index bf7270cf..b8fb877f 100644 --- a/src/SMAPI/IReflectionHelper.cs +++ b/src/SMAPI/IReflectionHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI @@ -14,40 +12,52 @@ namespace StardewModdingAPI /// The field type. /// The object which has the field. /// The field name. - /// Whether to throw an exception if the field is not found. + /// Whether to throw an exception if the field isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the field doesn't exist. + /// The target field doesn't exist, and is true. IReflectedField GetField(object obj, string name, bool required = true); /// Get a static field. /// The field type. /// The type which has the field. /// The field name. - /// Whether to throw an exception if the field is not found. + /// Whether to throw an exception if the field isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the field doesn't exist. + /// The target field doesn't exist, and is true. IReflectedField GetField(Type type, string name, bool required = true); /// Get an instance property. /// The property type. /// The object which has the property. /// The property name. - /// Whether to throw an exception if the property is not found. + /// Whether to throw an exception if the property isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the property doesn't exist. + /// The target property doesn't exist, and is true. IReflectedProperty GetProperty(object obj, string name, bool required = true); /// Get a static property. /// The property type. /// The type which has the property. /// The property name. - /// Whether to throw an exception if the property is not found. + /// Whether to throw an exception if the property isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the property doesn't exist. + /// The target property doesn't exist, and is true. IReflectedProperty GetProperty(Type type, string name, bool required = true); /// Get an instance method. /// The object which has the method. - /// The field name. - /// Whether to throw an exception if the field is not found. + /// The method name. + /// Whether to throw an exception if the method isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the method doesn't exist. + /// The target method doesn't exist, and is true. IReflectedMethod GetMethod(object obj, string name, bool required = true); /// Get a static method. /// The type which has the method. - /// The field name. - /// Whether to throw an exception if the field is not found. + /// The method name. + /// Whether to throw an exception if the method isn't found. Due to limitations with nullable reference types, setting this to false will still mark the return value non-nullable. + /// Returns the method wrapper, or null if is false and the method doesn't exist. + /// The target method doesn't exist, and is true. IReflectedMethod GetMethod(Type type, string name, bool required = true); } } diff --git a/src/SMAPI/Metadata/InstructionMetadata.cs b/src/SMAPI/Metadata/InstructionMetadata.cs index 5617fd13..9b56f963 100644 --- a/src/SMAPI/Metadata/InstructionMetadata.cs +++ b/src/SMAPI/Metadata/InstructionMetadata.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI.Events; @@ -70,8 +68,8 @@ namespace StardewModdingAPI.Metadata ** detect code which may impact game stability ****/ yield return new TypeFinder("System.Runtime.CompilerServices.CallSite", InstructionHandleResult.DetectedDynamic); - yield return new FieldFinder(typeof(SaveGame).FullName, new[] { nameof(SaveGame.serializer), nameof(SaveGame.farmerSerializer), nameof(SaveGame.locationSerializer) }, InstructionHandleResult.DetectedSaveSerializer); - yield return new EventFinder(typeof(ISpecializedEvents).FullName, new[] { nameof(ISpecializedEvents.UnvalidatedUpdateTicked), nameof(ISpecializedEvents.UnvalidatedUpdateTicking) }, InstructionHandleResult.DetectedUnvalidatedUpdateTick); + yield return new FieldFinder(typeof(SaveGame).FullName!, new[] { nameof(SaveGame.serializer), nameof(SaveGame.farmerSerializer), nameof(SaveGame.locationSerializer) }, InstructionHandleResult.DetectedSaveSerializer); + yield return new EventFinder(typeof(ISpecializedEvents).FullName!, new[] { nameof(ISpecializedEvents.UnvalidatedUpdateTicked), nameof(ISpecializedEvents.UnvalidatedUpdateTicking) }, InstructionHandleResult.DetectedUnvalidatedUpdateTick); /**** ** detect paranoid issues @@ -79,23 +77,23 @@ namespace StardewModdingAPI.Metadata if (paranoidMode) { // filesystem access - yield return new TypeFinder(typeof(System.Console).FullName, InstructionHandleResult.DetectedConsoleAccess); + yield return new TypeFinder(typeof(System.Console).FullName!, InstructionHandleResult.DetectedConsoleAccess); yield return new TypeFinder( new[] { - typeof(System.IO.File).FullName, - typeof(System.IO.FileStream).FullName, - typeof(System.IO.FileInfo).FullName, - typeof(System.IO.Directory).FullName, - typeof(System.IO.DirectoryInfo).FullName, - typeof(System.IO.DriveInfo).FullName, - typeof(System.IO.FileSystemWatcher).FullName + typeof(System.IO.File).FullName!, + typeof(System.IO.FileStream).FullName!, + typeof(System.IO.FileInfo).FullName!, + typeof(System.IO.Directory).FullName!, + typeof(System.IO.DirectoryInfo).FullName!, + typeof(System.IO.DriveInfo).FullName!, + typeof(System.IO.FileSystemWatcher).FullName! }, InstructionHandleResult.DetectedFilesystemAccess ); // shell access - yield return new TypeFinder(typeof(System.Diagnostics.Process).FullName, InstructionHandleResult.DetectedShellAccess); + yield return new TypeFinder(typeof(System.Diagnostics.Process).FullName!, InstructionHandleResult.DetectedShellAccess); } } } diff --git a/src/SMAPI/Mod.cs b/src/SMAPI/Mod.cs index 2b3750d5..cffe2998 100644 --- a/src/SMAPI/Mod.cs +++ b/src/SMAPI/Mod.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI @@ -11,13 +9,13 @@ namespace StardewModdingAPI ** Accessors *********/ /// - public IModHelper Helper { get; internal set; } + public IModHelper Helper { get; internal set; } = null!; /// - public IMonitor Monitor { get; internal set; } + public IMonitor Monitor { get; internal set; } = null!; /// - public IManifest ModManifest { get; internal set; } + public IManifest ModManifest { get; internal set; } = null!; /********* @@ -27,7 +25,7 @@ namespace StardewModdingAPI public abstract void Entry(IModHelper helper); /// - public virtual object GetApi() + public virtual object? GetApi() { return null; } @@ -35,7 +33,7 @@ namespace StardewModdingAPI /// Release or reset unmanaged resources. public void Dispose() { - (this.Helper as IDisposable)?.Dispose(); // deliberate do this outside overridable dispose method so mods don't accidentally suppress it + (this.Helper as IDisposable)?.Dispose(); // deliberately do this outside overridable dispose method so mods don't accidentally suppress it this.Dispose(true); GC.SuppressFinalize(this); } diff --git a/src/SMAPI/Patches/Game1Patcher.cs b/src/SMAPI/Patches/Game1Patcher.cs index c5d98e9e..8f806790 100644 --- a/src/SMAPI/Patches/Game1Patcher.cs +++ b/src/SMAPI/Patches/Game1Patcher.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Diagnostics.CodeAnalysis; using HarmonyLib; @@ -22,10 +20,10 @@ namespace StardewModdingAPI.Patches ** Fields *********/ /// Simplifies access to private code. - private static Reflector Reflection; + private static Reflector Reflection = null!; // initialized in constructor /// A callback to invoke when the load stage changes. - private static Action OnStageChanged; + private static Action OnStageChanged = null!; // initialized in constructor /// Whether the game is running running the code in . private static bool IsInLoadForNewGame; diff --git a/src/SMAPI/Patches/TitleMenuPatcher.cs b/src/SMAPI/Patches/TitleMenuPatcher.cs index 56e5597c..18f1a830 100644 --- a/src/SMAPI/Patches/TitleMenuPatcher.cs +++ b/src/SMAPI/Patches/TitleMenuPatcher.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Diagnostics.CodeAnalysis; using HarmonyLib; @@ -19,7 +17,7 @@ namespace StardewModdingAPI.Patches ** Fields *********/ /// A callback to invoke when the load stage changes. - private static Action OnStageChanged; + private static Action OnStageChanged = null!; // initialized in constructor /********* diff --git a/src/SMAPI/Program.cs b/src/SMAPI/Program.cs index b2e213fe..a6861bca 100644 --- a/src/SMAPI/Program.cs +++ b/src/SMAPI/Program.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -22,7 +20,7 @@ namespace StardewModdingAPI private static readonly string DllSearchPath = EarlyConstants.InternalFilesPath; /// The assembly paths in the search folders indexed by assembly name. - private static Dictionary AssemblyPathsByName; + private static Dictionary? AssemblyPathsByName; /********* @@ -61,7 +59,7 @@ namespace StardewModdingAPI /// Method called when assembly resolution fails, which may return a manually resolved assembly. /// The event sender. /// The event arguments. - private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e) + private static Assembly? CurrentDomain_AssemblyResolve(object? sender, ResolveEventArgs e) { // cache assembly paths by name if (Program.AssemblyPathsByName == null) @@ -74,7 +72,7 @@ namespace StardewModdingAPI { try { - string curName = AssemblyName.GetAssemblyName(dllPath).Name; + string? curName = AssemblyName.GetAssemblyName(dllPath).Name; if (curName != null) Program.AssemblyPathsByName[curName] = dllPath; } @@ -89,8 +87,8 @@ namespace StardewModdingAPI // resolve try { - string searchName = new AssemblyName(e.Name).Name; - return searchName != null && Program.AssemblyPathsByName.TryGetValue(searchName, out string assemblyPath) + string? searchName = new AssemblyName(e.Name).Name; + return searchName != null && Program.AssemblyPathsByName.TryGetValue(searchName, out string? assemblyPath) ? Assembly.LoadFrom(assemblyPath) : null; } @@ -129,7 +127,7 @@ namespace StardewModdingAPI // min version if (Constants.GameVersion.IsOlderThan(Constants.MinimumGameVersion)) { - ISemanticVersion suggestedApiVersion = Constants.GetCompatibleApiVersion(Constants.GameVersion); + ISemanticVersion? suggestedApiVersion = Constants.GetCompatibleApiVersion(Constants.GameVersion); Program.PrintErrorAndExit(suggestedApiVersion != null ? $"Oops! You're running Stardew Valley {Constants.GameVersion}, but the oldest supported version is {Constants.MinimumGameVersion}. You can install SMAPI {suggestedApiVersion} instead to fix this error, or update your game to the latest version." : $"Oops! You're running Stardew Valley {Constants.GameVersion}, but the oldest supported version is {Constants.MinimumGameVersion}. Please update your game before using SMAPI." @@ -152,7 +150,7 @@ namespace StardewModdingAPI foreach (var type in new[] { typeof(IManifest), typeof(Manifest) }) { AssemblyName assemblyName = type.Assembly.GetName(); - ISemanticVersion assemblyVersion = new SemanticVersion(assemblyName.Version); + ISemanticVersion assemblyVersion = new SemanticVersion(assemblyName.Version!); if (!assemblyVersion.Equals(smapiVersion)) Program.PrintErrorAndExit($"Oops! The 'smapi-internal/{assemblyName.Name}.dll' file is version {assemblyVersion} instead of the required {Constants.ApiVersion}. SMAPI doesn't seem to be installed correctly."); } @@ -184,7 +182,7 @@ namespace StardewModdingAPI bool? developerMode = null; string modsPath; { - string rawModsPath = null; + string? rawModsPath = null; // get mods path from command line args int pathIndex = Array.LastIndexOf(args, "--mods-path") + 1; @@ -202,7 +200,7 @@ namespace StardewModdingAPI rawModsPath = Environment.GetEnvironmentVariable("SMAPI_MODS_PATH"); if (developerMode is null) { - string rawDeveloperMode = Environment.GetEnvironmentVariable("SMAPI_DEVELOPER_MODE"); + string? rawDeveloperMode = Environment.GetEnvironmentVariable("SMAPI_DEVELOPER_MODE"); if (rawDeveloperMode != null) developerMode = bool.Parse(rawDeveloperMode); } @@ -221,7 +219,7 @@ namespace StardewModdingAPI /// Write an error directly to the console and exit. /// The error message to display. /// An additional message to log with technical details. - private static void PrintErrorAndExit(string message, string technicalMessage = null) + private static void PrintErrorAndExit(string message, string? technicalMessage = null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(message); diff --git a/src/SMAPI/Translation.cs b/src/SMAPI/Translation.cs index ef98a00f..2a0d2ce8 100644 --- a/src/SMAPI/Translation.cs +++ b/src/SMAPI/Translation.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections; using System.Collections.Generic; @@ -17,14 +15,14 @@ namespace StardewModdingAPI /// The placeholder text when the translation is null or empty, where {0} is the translation key. internal const string PlaceholderText = "(no translation:{0})"; - /// The locale for which the translation was fetched. + /// The locale for which the translation was fetched like fr-FR, or an empty string for English. private readonly string Locale; /// The underlying translation text. - private readonly string Text; + private readonly string? Text; /// The value to return if the translations is undefined. - private readonly string Placeholder; + private readonly string? Placeholder; /********* @@ -41,12 +39,12 @@ namespace StardewModdingAPI /// The locale for which the translation was fetched. /// The translation key. /// The underlying translation text. - internal Translation(string locale, string key, string text) + internal Translation(string locale, string key, string? text) : this(locale, key, text, string.Format(Translation.PlaceholderText, key)) { } /// Replace the text if it's null or empty. If you set a null or empty value, the translation will show the fallback "no translation" placeholder (see if you want to disable that). Returns a new instance if changed. /// The default value. - public Translation Default(string @default) + public Translation Default(string? @default) { return this.HasValue() ? this @@ -54,7 +52,7 @@ namespace StardewModdingAPI } /// Whether to return a "no translation" placeholder if the translation is null or empty. Returns a new instance. - /// Whether to return a placeholder. + /// Whether to return a placeholder. Due to limitations with nullable reference types, setting this to false will still mark the text non-nullable. public Translation UsePlaceholder(bool use) { return new Translation(this.Locale, this.Key, this.Text, use ? string.Format(Translation.PlaceholderText, this.Key) : null); @@ -63,20 +61,20 @@ namespace StardewModdingAPI /// Replace tokens in the text like {{value}} with the given values. Returns a new instance. /// An object containing token key/value pairs. This can be an anonymous object (like new { value = 42, name = "Cranberries" }), a dictionary, or a class instance. /// The argument is null. - public Translation Tokens(object tokens) + public Translation Tokens(object? tokens) { if (string.IsNullOrWhiteSpace(this.Text) || tokens == null) return this; // get dictionary of tokens - IDictionary tokenLookup = new Dictionary(StringComparer.OrdinalIgnoreCase); + Dictionary tokenLookup = new(StringComparer.OrdinalIgnoreCase); { // from dictionary if (tokens is IDictionary inputLookup) { foreach (DictionaryEntry entry in inputLookup) { - string key = entry.Key.ToString()?.Trim(); + string? key = entry.Key.ToString()?.Trim(); if (key != null) tokenLookup[key] = entry.Value?.ToString(); } @@ -97,7 +95,7 @@ namespace StardewModdingAPI string text = Regex.Replace(this.Text, @"{{([ \w\.\-]+)}}", match => { string key = match.Groups[1].Value.Trim(); - return tokenLookup.TryGetValue(key, out string value) + return tokenLookup.TryGetValue(key, out string? value) ? value : match.Value; }); @@ -111,18 +109,20 @@ namespace StardewModdingAPI } /// Get the translation text. Calling this method isn't strictly necessary, since you can assign a value directly to a string. + /// Limitation with nullable reference types: if there's no text and you disabled the fallback via , this will return null but the return value will still be marked non-nullable. public override string ToString() { return this.Placeholder != null && !this.HasValue() ? this.Placeholder - : this.Text; + : this.Text!; } /// Get a string representation of the given translation. /// The translation key. + /// Limitation with nullable reference types: if there's no text and you disabled the fallback via , this will return null but the return value will still be marked non-nullable. public static implicit operator string(Translation translation) { - return translation?.ToString(); + return translation.ToString(); } @@ -134,7 +134,7 @@ namespace StardewModdingAPI /// The translation key. /// The underlying translation text. /// The value to return if the translations is undefined. - private Translation(string locale, string key, string text, string placeholder) + private Translation(string locale, string key, string? text, string? placeholder) { this.Locale = locale; this.Key = key; diff --git a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs b/src/SMAPI/Utilities/CaseInsensitivePathCache.cs index 4596fdce..2ac1b9f9 100644 --- a/src/SMAPI/Utilities/CaseInsensitivePathCache.cs +++ b/src/SMAPI/Utilities/CaseInsensitivePathCache.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -81,7 +79,7 @@ namespace StardewModdingAPI.Utilities return relativePath; // already cached - if (this.RelativePathCache.Value.TryGetValue(relativePath, out string resolved)) + if (this.RelativePathCache.Value.TryGetValue(relativePath, out string? resolved)) return resolved; // file exists but isn't cached for some reason diff --git a/src/SMAPI/Utilities/Keybind.cs b/src/SMAPI/Utilities/Keybind.cs index 7b1acf1d..3455ce77 100644 --- a/src/SMAPI/Utilities/Keybind.cs +++ b/src/SMAPI/Utilities/Keybind.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Framework; @@ -44,7 +43,7 @@ namespace StardewModdingAPI.Utilities /// The keybind string. See remarks on for format details. /// The parsed keybind, if valid. /// The parse errors, if any. - public static bool TryParse(string input, out Keybind parsed, out string[] errors) + public static bool TryParse(string input, [NotNullWhen(true)] out Keybind? parsed, out string[] errors) { // empty input if (string.IsNullOrWhiteSpace(input)) diff --git a/src/SMAPI/Utilities/KeybindList.cs b/src/SMAPI/Utilities/KeybindList.cs index 7b2c396b..18eeb9fd 100644 --- a/src/SMAPI/Utilities/KeybindList.cs +++ b/src/SMAPI/Utilities/KeybindList.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Toolkit.Serialization; @@ -42,7 +41,7 @@ namespace StardewModdingAPI.Utilities /// The format is invalid. public static KeybindList Parse(string input) { - return KeybindList.TryParse(input, out KeybindList parsed, out string[] errors) + return KeybindList.TryParse(input, out KeybindList? parsed, out string[] errors) ? parsed : throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{input}'.\n{string.Join("\n", errors)}"); } @@ -51,7 +50,7 @@ namespace StardewModdingAPI.Utilities /// The keybind string. See remarks on for format details. /// The parsed keybind list, if valid. /// The errors that occurred while parsing the input, if any. - public static bool TryParse(string input, out KeybindList parsed, out string[] errors) + public static bool TryParse(string input, [NotNullWhen(true)] out KeybindList? parsed, out string[] errors) { // empty input if (string.IsNullOrWhiteSpace(input)) @@ -69,7 +68,7 @@ namespace StardewModdingAPI.Utilities if (string.IsNullOrWhiteSpace(rawSet)) continue; - if (!Keybind.TryParse(rawSet, out Keybind keybind, out string[] curErrors)) + if (!Keybind.TryParse(rawSet, out Keybind? keybind, out string[] curErrors)) rawErrors.AddRange(curErrors); else keybinds.Add(keybind); @@ -151,7 +150,7 @@ namespace StardewModdingAPI.Utilities } /// Get the keybind which is currently down, if any. If there are multiple keybinds down, the first one is returned. - public Keybind GetKeybindCurrentlyDown() + public Keybind? GetKeybindCurrentlyDown() { return this.Keybinds.FirstOrDefault(p => p.GetState().IsDown()); } diff --git a/src/SMAPI/Utilities/SDate.cs b/src/SMAPI/Utilities/SDate.cs index b10bc3da..1d4e4489 100644 --- a/src/SMAPI/Utilities/SDate.cs +++ b/src/SMAPI/Utilities/SDate.cs @@ -1,6 +1,5 @@ -#nullable disable - using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Newtonsoft.Json; using StardewModdingAPI.Framework; @@ -24,7 +23,7 @@ namespace StardewModdingAPI.Utilities private readonly int DaysInSeason = 28; /// The core SMAPI translations. - internal static Translator Translations; + internal static Translator? Translations; /********* @@ -94,7 +93,8 @@ namespace StardewModdingAPI.Utilities /// Get a date from a game date instance. /// The world date. - public static SDate From(WorldDate date) + [return: NotNullIfNotNull("date")] + public static SDate? From(WorldDate? date) { if (date == null) return null; @@ -170,14 +170,14 @@ namespace StardewModdingAPI.Utilities ****/ /// Get whether this instance is equal to another. /// The other value to compare. - public bool Equals(SDate other) + public bool Equals(SDate? other) { return this == other; } /// Get whether this instance is equal to another. /// The other value to compare. - public override bool Equals(object obj) + public override bool Equals(object? obj) { return obj is SDate other && this == other; } @@ -195,7 +195,7 @@ namespace StardewModdingAPI.Utilities /// The base date to compare. /// The other date to compare. /// The equality of the dates - public static bool operator ==(SDate date, SDate other) + public static bool operator ==(SDate? date, SDate? other) { return date?.DaysSinceStart == other?.DaysSinceStart; } @@ -203,7 +203,7 @@ namespace StardewModdingAPI.Utilities /// Get whether one date is not equal to another. /// The base date to compare. /// The other date to compare. - public static bool operator !=(SDate date, SDate other) + public static bool operator !=(SDate? date, SDate? other) { return date?.DaysSinceStart != other?.DaysSinceStart; } @@ -211,7 +211,7 @@ namespace StardewModdingAPI.Utilities /// Get whether one date is more than another. /// The base date to compare. /// The other date to compare. - public static bool operator >(SDate date, SDate other) + public static bool operator >(SDate? date, SDate? other) { return date?.DaysSinceStart > other?.DaysSinceStart; } @@ -219,7 +219,7 @@ namespace StardewModdingAPI.Utilities /// Get whether one date is more than or equal to another. /// The base date to compare. /// The other date to compare. - public static bool operator >=(SDate date, SDate other) + public static bool operator >=(SDate? date, SDate? other) { return date?.DaysSinceStart >= other?.DaysSinceStart; } @@ -227,7 +227,7 @@ namespace StardewModdingAPI.Utilities /// Get whether one date is less than or equal to another. /// The base date to compare. /// The other date to compare. - public static bool operator <=(SDate date, SDate other) + public static bool operator <=(SDate? date, SDate? other) { return date?.DaysSinceStart <= other?.DaysSinceStart; } @@ -235,7 +235,7 @@ namespace StardewModdingAPI.Utilities /// Get whether one date is less than another. /// The base date to compare. /// The other date to compare. - public static bool operator <(SDate date, SDate other) + public static bool operator <(SDate? date, SDate? other) { return date?.DaysSinceStart < other?.DaysSinceStart; } @@ -250,9 +250,10 @@ namespace StardewModdingAPI.Utilities /// The year. /// Whether to allow 0 spring Y1 as a valid date. /// One of the arguments has an invalid value (like day 35). + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "The nullability is validated in this constructor.")] private SDate(int day, string season, int year, bool allowDayZero) { - season = season?.Trim().ToLowerInvariant(); + season = season?.Trim().ToLowerInvariant()!; // null-checked below // validate if (season == null) @@ -288,25 +289,17 @@ namespace StardewModdingAPI.Utilities /// The day of month. private DayOfWeek GetDayOfWeek(int day) { - switch (day % 7) + return (day % 7) switch { - case 0: - return DayOfWeek.Sunday; - case 1: - return DayOfWeek.Monday; - case 2: - return DayOfWeek.Tuesday; - case 3: - return DayOfWeek.Wednesday; - case 4: - return DayOfWeek.Thursday; - case 5: - return DayOfWeek.Friday; - case 6: - return DayOfWeek.Saturday; - default: - return 0; - } + 0 => DayOfWeek.Sunday, + 1 => DayOfWeek.Monday, + 2 => DayOfWeek.Tuesday, + 3 => DayOfWeek.Wednesday, + 4 => DayOfWeek.Thursday, + 5 => DayOfWeek.Friday, + 6 => DayOfWeek.Saturday, + _ => 0 + }; } /// Get the number of days since the game began (starting at 1 for the first day of spring in Y1). -- cgit From 4adf8611131a5d86b15f017a42a0366837d14528 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 13 Apr 2022 21:07:43 -0400 Subject: enable nullable annotations in the rest of SMAPI core (#837) --- src/SMAPI.Tests/Utilities/KeybindListTests.cs | 10 +- src/SMAPI/Events/ModMessageReceivedEventArgs.cs | 6 +- src/SMAPI/Framework/CommandManager.cs | 34 ++-- src/SMAPI/Framework/Commands/HelpCommand.cs | 8 +- src/SMAPI/Framework/Content/AssetDataForMap.cs | 23 ++- src/SMAPI/Framework/Content/AssetName.cs | 21 +-- src/SMAPI/Framework/Content/ContentCache.cs | 11 +- .../ContentManagers/BaseContentManager.cs | 21 ++- .../Framework/ContentManagers/ModContentManager.cs | 21 +-- src/SMAPI/Framework/DeprecationManager.cs | 25 ++- src/SMAPI/Framework/Input/GamePadStateBuilder.cs | 9 +- src/SMAPI/Framework/Input/SInputState.cs | 6 +- src/SMAPI/Framework/InternalExtensions.cs | 9 +- .../Framework/Logging/InterceptingTextWriter.cs | 24 ++- src/SMAPI/Framework/Logging/LogManager.cs | 36 +++-- src/SMAPI/Framework/ModHelpers/CommandHelper.cs | 4 +- src/SMAPI/Framework/ModLoading/AssemblyLoader.cs | 35 +++-- .../Framework/ModLoading/AssemblyParseResult.cs | 15 +- src/SMAPI/Framework/ModLoading/ModResolver.cs | 75 +++++---- .../ModLoading/Rewriters/FieldReplaceRewriter.cs | 20 ++- src/SMAPI/Framework/Models/SConfig.cs | 78 +++++++--- src/SMAPI/Framework/Networking/ModMessageModel.cs | 21 ++- src/SMAPI/Framework/Networking/MultiplayerPeer.cs | 16 +- .../Framework/Networking/MultiplayerPeerMod.cs | 5 +- .../Framework/Networking/RemoteContextModModel.cs | 30 +++- .../Framework/Networking/RemoteContextModel.cs | 33 +++- src/SMAPI/Framework/Reflection/CacheEntry.cs | 12 +- src/SMAPI/Framework/Reflection/Reflector.cs | 127 +++++++++------ src/SMAPI/Framework/SCore.cs | 172 +++++++++++---------- src/SMAPI/Framework/SMultiplayer.cs | 89 ++++++----- .../Framework/Serialization/KeybindConverter.cs | 4 +- .../FieldWatchers/ComparableWatcher.cs | 5 +- src/SMAPI/Framework/StateTracking/PlayerTracker.cs | 16 +- .../StateTracking/Snapshots/PlayerSnapshot.cs | 11 +- .../Framework/TemporaryHacks/MiniMonoModHotfix.cs | 122 +++++++-------- src/SMAPI/Metadata/CoreAssetPropagator.cs | 47 +++--- src/SMAPI/Translation.cs | 2 +- src/SMAPI/Utilities/KeybindList.cs | 2 +- src/SMAPI/Utilities/PerScreen.cs | 23 ++- 39 files changed, 679 insertions(+), 549 deletions(-) (limited to 'src/SMAPI/Framework/Logging') diff --git a/src/SMAPI.Tests/Utilities/KeybindListTests.cs b/src/SMAPI.Tests/Utilities/KeybindListTests.cs index 060c93ed..c4c086de 100644 --- a/src/SMAPI.Tests/Utilities/KeybindListTests.cs +++ b/src/SMAPI.Tests/Utilities/KeybindListTests.cs @@ -21,12 +21,12 @@ namespace SMAPI.Tests.Utilities public void TryParse_SimpleValue(SButton button) { // act - bool success = KeybindList.TryParse($"{button}", out KeybindList parsed, out string[] errors); + bool success = KeybindList.TryParse($"{button}", out KeybindList? parsed, out string[] errors); // assert Assert.IsTrue(success, "Parsing unexpectedly failed."); Assert.IsNotNull(parsed, "The parsed result should not be null."); - Assert.AreEqual(parsed.ToString(), $"{button}"); + Assert.AreEqual(parsed!.ToString(), $"{button}"); Assert.IsNotNull(errors, message: "The errors should never be null."); Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors."); } @@ -47,14 +47,14 @@ namespace SMAPI.Tests.Utilities public string TryParse_MultiValues(string? input) { // act - bool success = KeybindList.TryParse(input, out KeybindList parsed, out string[] errors); + bool success = KeybindList.TryParse(input, out KeybindList? parsed, out string[] errors); // assert Assert.IsTrue(success, "Parsing unexpectedly failed."); Assert.IsNotNull(parsed, "The parsed result should not be null."); Assert.IsNotNull(errors, message: "The errors should never be null."); Assert.IsEmpty(errors, message: "The input bindings incorrectly reported errors."); - return parsed.ToString(); + return parsed!.ToString(); } /// Assert invalid values are rejected. @@ -67,7 +67,7 @@ namespace SMAPI.Tests.Utilities public void TryParse_InvalidValues(string input, string expectedError) { // act - bool success = KeybindList.TryParse(input, out KeybindList parsed, out string[] errors); + bool success = KeybindList.TryParse(input, out KeybindList? parsed, out string[] errors); // assert Assert.IsFalse(success, "Parsing unexpectedly succeeded."); diff --git a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs index 671bdf38..84a27d18 100644 --- a/src/SMAPI/Events/ModMessageReceivedEventArgs.cs +++ b/src/SMAPI/Events/ModMessageReceivedEventArgs.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewModdingAPI.Framework.Networking; using StardewModdingAPI.Toolkit.Serialization; @@ -47,8 +45,10 @@ namespace StardewModdingAPI.Events /// Read the message data into the given model type. /// The message model type. public TModel ReadAs() + where TModel : notnull { - return this.Message.Data.ToObject(this.JsonHelper.GetSerializer()); + return this.Message.Data.ToObject(this.JsonHelper.GetSerializer()) + ?? throw new InvalidOperationException($"Can't read empty mod message data as a {typeof(TModel).FullName} value."); } } } diff --git a/src/SMAPI/Framework/CommandManager.cs b/src/SMAPI/Framework/CommandManager.cs index 80c08f34..d3b9c8ee 100644 --- a/src/SMAPI/Framework/CommandManager.cs +++ b/src/SMAPI/Framework/CommandManager.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using StardewModdingAPI.Framework.Commands; @@ -39,9 +38,9 @@ namespace StardewModdingAPI.Framework /// The or is null or empty. /// The is not a valid format. /// There's already a command with that name. - public CommandManager Add(IModMetadata mod, string name, string documentation, Action callback) + public CommandManager Add(IModMetadata? mod, string name, string documentation, Action callback) { - name = this.GetNormalizedName(name); + name = this.GetNormalizedName(name)!; // null-checked below // validate format if (string.IsNullOrWhiteSpace(name)) @@ -72,10 +71,13 @@ namespace StardewModdingAPI.Framework /// Get a command by its unique name. /// The command name. /// Returns the matching command, or null if not found. - public Command Get(string name) + public Command? Get(string? name) { - name = this.GetNormalizedName(name); - this.Commands.TryGetValue(name, out Command command); + name = this.GetNormalizedName(name)!; + if (string.IsNullOrWhiteSpace(name)) + return null; + + this.Commands.TryGetValue(name, out Command? command); return command; } @@ -94,7 +96,7 @@ namespace StardewModdingAPI.Framework /// The command which can handle the input. /// The screen ID on which to run the command. /// Returns true if the input was successfully parsed and matched to a command; else false. - public bool TryParse(string input, out string name, out string[] args, out Command command, out int screenId) + public bool TryParse(string? input, [NotNullWhen(true)] out string? name, [NotNullWhen(true)] out string[]? args, [NotNullWhen(true)] out Command? command, out int screenId) { // ignore if blank if (string.IsNullOrWhiteSpace(input)) @@ -108,7 +110,7 @@ namespace StardewModdingAPI.Framework // parse input args = this.ParseArgs(input); - name = this.GetNormalizedName(args[0]); + name = this.GetNormalizedName(args[0])!; args = args.Skip(1).ToArray(); // get screen ID argument @@ -116,7 +118,7 @@ namespace StardewModdingAPI.Framework for (int i = 0; i < args.Length; i++) { // consume arg & set screen ID - if (this.TryParseScreenId(args[i], out int rawScreenId, out string error)) + if (this.TryParseScreenId(args[i], out int rawScreenId, out string? error)) { args = args.Take(i).Concat(args.Skip(i + 1)).ToArray(); screenId = rawScreenId; @@ -140,15 +142,15 @@ namespace StardewModdingAPI.Framework /// The command name. /// The command arguments. /// Returns whether a matching command was triggered. - public bool Trigger(string name, string[] arguments) + public bool Trigger(string? name, string[] arguments) { // get normalized name - name = this.GetNormalizedName(name); - if (name == null) + name = this.GetNormalizedName(name)!; + if (string.IsNullOrWhiteSpace(name)) return false; // get command - if (this.Commands.TryGetValue(name, out Command command)) + if (this.Commands.TryGetValue(name, out Command? command)) { command.Callback.Invoke(name, arguments); return true; @@ -191,7 +193,7 @@ namespace StardewModdingAPI.Framework /// The parsed screen ID, if any. /// The error which indicates an invalid screen ID, if applicable. /// Returns whether the screen ID was parsed successfully. - private bool TryParseScreenId(string arg, out int screen, out string error) + private bool TryParseScreenId(string arg, out int screen, out string? error) { screen = -1; error = null; @@ -220,7 +222,7 @@ namespace StardewModdingAPI.Framework /// Get a normalized command name. /// The command name. - private string GetNormalizedName(string name) + private string? GetNormalizedName(string? name) { name = name?.Trim().ToLower(); return !string.IsNullOrWhiteSpace(name) diff --git a/src/SMAPI/Framework/Commands/HelpCommand.cs b/src/SMAPI/Framework/Commands/HelpCommand.cs index eb6c74f5..65dc3bce 100644 --- a/src/SMAPI/Framework/Commands/HelpCommand.cs +++ b/src/SMAPI/Framework/Commands/HelpCommand.cs @@ -1,5 +1,3 @@ -#nullable disable - using System.Linq; namespace StardewModdingAPI.Framework.Commands @@ -41,7 +39,7 @@ namespace StardewModdingAPI.Framework.Commands { if (args.Any()) { - Command result = this.CommandManager.Get(args[0]); + Command? result = this.CommandManager.Get(args[0]); if (result == null) monitor.Log("There's no command with that name. Type 'help' by itself for more info.", LogLevel.Error); else @@ -63,10 +61,10 @@ namespace StardewModdingAPI.Framework.Commands + "--------------\n" + "The following commands are registered. For more info about a command, type 'help command_name'.\n\n"; - IGrouping[] groups = (from command in this.CommandManager.GetAll() orderby command.Mod?.DisplayName, command.Name group command.Name by command.Mod?.DisplayName).ToArray(); + IGrouping[] groups = (from command in this.CommandManager.GetAll() orderby command.Mod?.DisplayName, command.Name group command.Name by command.Mod?.DisplayName ?? "SMAPI").ToArray(); foreach (var group in groups) { - string modName = group.Key ?? "SMAPI"; + string modName = group.Key; string[] commandNames = group.ToArray(); message += $"{modName}:\n {string.Join("\n ", commandNames)}\n\n"; } diff --git a/src/SMAPI/Framework/Content/AssetDataForMap.cs b/src/SMAPI/Framework/Content/AssetDataForMap.cs index 93148277..133dcc6c 100644 --- a/src/SMAPI/Framework/Content/AssetDataForMap.cs +++ b/src/SMAPI/Framework/Content/AssetDataForMap.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -35,7 +33,7 @@ namespace StardewModdingAPI.Framework.Content /// Normalizes an asset key to match the cache key. /// A callback to invoke when the data is replaced (if any). /// Simplifies access to private code. - public AssetDataForMap(string locale, IAssetName assetName, Map data, Func getNormalizedPath, Action onDataReplaced, Reflector reflection) + public AssetDataForMap(string? locale, IAssetName assetName, Map data, Func getNormalizedPath, Action onDataReplaced, Reflector reflection) : base(locale, assetName, data, getNormalizedPath, onDataReplaced) { this.Reflection = reflection; @@ -126,8 +124,7 @@ namespace StardewModdingAPI.Framework.Content foreach (Layer sourceLayer in source.Layers) { // get layer - Layer targetLayer = sourceToTargetLayers[sourceLayer]; - if (targetLayer == null) + if (!sourceToTargetLayers.TryGetValue(sourceLayer, out Layer? targetLayer)) { target.AddLayer(targetLayer = new Layer(sourceLayer.Id, target, target.Layers[0].LayerSize, Layer.m_tileSize)); sourceToTargetLayers[sourceLayer] = target.GetLayer(sourceLayer.Id); @@ -137,11 +134,13 @@ namespace StardewModdingAPI.Framework.Content targetLayer.Properties.CopyFrom(sourceLayer.Properties); // create new tile - Tile sourceTile = sourceLayer.Tiles[sourcePos.X, sourcePos.Y]; - Tile newTile = sourceTile != null - ? this.CreateTile(sourceTile, targetLayer, tilesheetMap[sourceTile.TileSheet]) - : null; - newTile?.Properties.CopyFrom(sourceTile.Properties); + Tile? sourceTile = sourceLayer.Tiles[sourcePos.X, sourcePos.Y]; + Tile? newTile = null; + if (sourceTile != null) + { + newTile = this.CreateTile(sourceTile, targetLayer, tilesheetMap[sourceTile.TileSheet]); + newTile?.Properties.CopyFrom(sourceTile.Properties); + } // replace tile if (newTile != null || replaceByLayer || replaceAll) @@ -195,7 +194,7 @@ namespace StardewModdingAPI.Framework.Content /// The source tile to copy. /// The target layer. /// The target tilesheet. - private Tile CreateTile(Tile sourceTile, Layer targetLayer, TileSheet targetSheet) + private Tile? CreateTile(Tile sourceTile, Layer targetLayer, TileSheet targetSheet) { switch (sourceTile) { @@ -220,7 +219,7 @@ namespace StardewModdingAPI.Framework.Content } /// Normalize a map tilesheet path for comparison. This value should *not* be used as the actual tilesheet path. /// The path to normalize. - private string NormalizeTilesheetPathForComparison(string path) + private string NormalizeTilesheetPathForComparison(string? path) { if (string.IsNullOrWhiteSpace(path)) return string.Empty; diff --git a/src/SMAPI/Framework/Content/AssetName.cs b/src/SMAPI/Framework/Content/AssetName.cs index 4d583d82..4c691b9a 100644 --- a/src/SMAPI/Framework/Content/AssetName.cs +++ b/src/SMAPI/Framework/Content/AssetName.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using StardewModdingAPI.Toolkit.Utilities; using StardewValley; @@ -26,7 +24,7 @@ namespace StardewModdingAPI.Framework.Content public string BaseName { get; } /// - public string LocaleCode { get; } + public string? LocaleCode { get; } /// public LocalizedContentManager.LanguageCode? LanguageCode { get; } @@ -39,7 +37,7 @@ namespace StardewModdingAPI.Framework.Content /// The base asset name without the locale code. /// The locale code specified in the , if it's a valid code recognized by the game content. /// The language code matching the , if applicable. - public AssetName(string baseName, string localeCode, LocalizedContentManager.LanguageCode? languageCode) + public AssetName(string baseName, string? localeCode, LocalizedContentManager.LanguageCode? languageCode) { // validate if (string.IsNullOrWhiteSpace(baseName)) @@ -69,7 +67,7 @@ namespace StardewModdingAPI.Framework.Content throw new ArgumentException("The asset name can't be null or empty.", nameof(rawName)); string baseName = rawName; - string localeCode = null; + string? localeCode = null; LocalizedContentManager.LanguageCode? languageCode = null; int lastPeriodIndex = rawName.LastIndexOf('.'); @@ -90,7 +88,7 @@ namespace StardewModdingAPI.Framework.Content } /// - public bool IsEquivalentTo(string assetName, bool useBaseName = false) + public bool IsEquivalentTo(string? assetName, bool useBaseName = false) { // empty asset key is never equivalent if (string.IsNullOrWhiteSpace(assetName)) @@ -103,7 +101,7 @@ namespace StardewModdingAPI.Framework.Content } /// - public bool IsEquivalentTo(IAssetName assetName, bool useBaseName = false) + public bool IsEquivalentTo(IAssetName? assetName, bool useBaseName = false) { if (useBaseName) return this.BaseName.Equals(assetName?.BaseName, StringComparison.OrdinalIgnoreCase); @@ -115,7 +113,7 @@ namespace StardewModdingAPI.Framework.Content } /// - public bool StartsWith(string prefix, bool allowPartialWord = true, bool allowSubfolder = true) + public bool StartsWith(string? prefix, bool allowPartialWord = true, bool allowSubfolder = true) { // asset keys never start with null if (prefix is null) @@ -157,8 +155,11 @@ namespace StardewModdingAPI.Framework.Content /// - public bool IsDirectlyUnderPath(string assetFolder) + public bool IsDirectlyUnderPath(string? assetFolder) { + if (assetFolder is null) + return false; + return this.StartsWith(assetFolder + "/", allowPartialWord: false, allowSubfolder: false); } @@ -171,7 +172,7 @@ namespace StardewModdingAPI.Framework.Content } /// - public bool Equals(IAssetName other) + public bool Equals(IAssetName? other) { return other switch { diff --git a/src/SMAPI/Framework/Content/ContentCache.cs b/src/SMAPI/Framework/Content/ContentCache.cs index 4e620d28..d8862eb3 100644 --- a/src/SMAPI/Framework/Content/ContentCache.cs +++ b/src/SMAPI/Framework/Content/ContentCache.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using StardewModdingAPI.Framework.Reflection; @@ -46,7 +45,8 @@ namespace StardewModdingAPI.Framework.Content /// Simplifies access to private game code. public ContentCache(LocalizedContentManager contentManager, Reflector reflection) { - this.Cache = reflection.GetField>(contentManager, "loadedAssets").GetValue(); + this.Cache = reflection.GetField>(contentManager, "loadedAssets").GetValue() + ?? throw new InvalidOperationException("Can't initialize content cache: required field 'loadedAssets' is missing."); } /**** @@ -66,7 +66,8 @@ namespace StardewModdingAPI.Framework.Content /// Normalize path separators in an asset name. /// The file path to normalize. [Pure] - public string NormalizePathSeparators(string path) + [return: NotNullIfNotNull("path")] + public string? NormalizePathSeparators(string? path) { return PathUtilities.NormalizeAssetName(path); } @@ -93,7 +94,7 @@ namespace StardewModdingAPI.Framework.Content public bool Remove(string key, bool dispose) { // get entry - if (!this.Cache.TryGetValue(key, out object value)) + if (!this.Cache.TryGetValue(key, out object? value)) return false; // dispose & remove entry diff --git a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs index f1ccab48..5ae5313d 100644 --- a/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/BaseContentManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -99,11 +97,13 @@ namespace StardewModdingAPI.Framework.ContentManagers this.AggressiveMemoryOptimizations = aggressiveMemoryOptimizations; // get asset data - this.BaseDisposableReferences = reflection.GetField>(this, "disposableAssets").GetValue(); + this.BaseDisposableReferences = reflection.GetField>(this, "disposableAssets").GetValue() + ?? throw new InvalidOperationException("Can't initialize content manager: the required 'disposableAssets' field wasn't found."); } /// public virtual bool DoesAssetExist(IAssetName assetName) + where T : notnull { return this.Cache.ContainsKey(assetName.Name); } @@ -131,6 +131,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// public T LoadLocalized(IAssetName assetName, LanguageCode language, bool useCache) + where T : notnull { // ignore locale in English (or if disabled) if (!this.TryLocalizeKeys || language == LocalizedContentManager.LanguageCode.en) @@ -172,11 +173,12 @@ namespace StardewModdingAPI.Framework.ContentManagers } /// - public abstract T LoadExact(IAssetName assetName, bool useCache); + public abstract T LoadExact(IAssetName assetName, bool useCache) + where T : notnull; /// [SuppressMessage("ReSharper", "ParameterOnlyUsedForPreconditionCheck.Local", Justification = "Parameter is only used for assertion checks by design.")] - public string AssertAndNormalizeAssetName(string assetName) + public string AssertAndNormalizeAssetName(string? assetName) { // NOTE: the game checks for ContentLoadException to handle invalid keys, so avoid // throwing other types like ArgumentException here. @@ -253,7 +255,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // dispose uncached assets foreach (WeakReference reference in this.Disposables) { - if (reference.TryGetTarget(out IDisposable disposable)) + if (reference.TryGetTarget(out IDisposable? disposable)) { try { @@ -285,7 +287,8 @@ namespace StardewModdingAPI.Framework.ContentManagers *********/ /// Apply initial normalization to a raw asset name before it's parsed. /// The asset name to normalize. - private string PrenormalizeRawAssetName(string assetName) + [return: NotNullIfNotNull("assetName")] + private string? PrenormalizeRawAssetName(string? assetName) { // trim assetName = assetName?.Trim(); @@ -301,7 +304,8 @@ namespace StardewModdingAPI.Framework.ContentManagers /// Normalize path separators in a file path. For asset keys, see instead. /// The file path to normalize. [Pure] - protected string NormalizePathSeparators(string path) + [return: NotNullIfNotNull("path")] + protected string? NormalizePathSeparators(string? path) { return this.Cache.NormalizePathSeparators(path); } @@ -323,6 +327,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset value. /// Whether to save the asset to the asset cache. protected virtual void TrackAsset(IAssetName assetName, T value, bool useCache) + where T : notnull { // track asset key if (value is Texture2D texture) diff --git a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs index 8051c296..f0f4bce9 100644 --- a/src/SMAPI/Framework/ContentManagers/ModContentManager.cs +++ b/src/SMAPI/Framework/ContentManagers/ModContentManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Globalization; using System.IO; @@ -92,7 +90,7 @@ namespace StardewModdingAPI.Framework.ContentManagers // resolve managed asset key { - if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string contentManagerID, out IAssetName relativePath)) + if (this.Coordinator.TryParseManagedAssetKey(assetName.Name, out string? contentManagerID, out IAssetName? relativePath)) { if (contentManagerID != this.Name) throw this.GetLoadError(assetName, "can't load a different mod's managed asset key through this mod content manager."); @@ -173,7 +171,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The file to load. private T LoadDataFile(IAssetName assetName, FileInfo file) { - if (!this.JsonHelper.ReadJsonFileIfExists(file.FullName, out T asset)) + if (!this.JsonHelper.ReadJsonFileIfExists(file.FullName, out T? asset)) throw this.GetLoadError(assetName, "the JSON file is invalid."); // should never happen since we check for file existence before calling this method return asset; @@ -249,7 +247,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// The asset name that failed to load. /// The reason the file couldn't be loaded. /// The underlying exception, if applicable. - private SContentLoadException GetLoadError(IAssetName assetName, string reasonPhrase, Exception exception = null) + private SContentLoadException GetLoadError(IAssetName assetName, string reasonPhrase, Exception? exception = null) { return new($"Failed loading asset '{assetName}' from {this.Name}: {reasonPhrase}", exception); } @@ -338,13 +336,16 @@ namespace StardewModdingAPI.Framework.ContentManagers // load best match try { - if (!this.TryGetTilesheetAssetName(relativeMapFolder, imageSource, out IAssetName assetName, out string error)) + if (!this.TryGetTilesheetAssetName(relativeMapFolder, imageSource, out IAssetName? assetName, out string? error)) throw new SContentLoadException($"{errorPrefix} {error}"); - if (!assetName.IsEquivalentTo(tilesheet.ImageSource)) - this.Monitor.VerboseLog($" Mapped tilesheet '{tilesheet.ImageSource}' to '{assetName}'."); + if (assetName is not null) + { + if (!assetName.IsEquivalentTo(tilesheet.ImageSource)) + this.Monitor.VerboseLog($" Mapped tilesheet '{tilesheet.ImageSource}' to '{assetName}'."); - tilesheet.ImageSource = assetName.Name; + tilesheet.ImageSource = assetName.Name; + } } catch (Exception ex) when (ex is not SContentLoadException) { @@ -360,7 +361,7 @@ namespace StardewModdingAPI.Framework.ContentManagers /// A message indicating why the file couldn't be loaded. /// Returns whether the asset name was found. /// See remarks on . - private bool TryGetTilesheetAssetName(string modRelativeMapFolder, string relativePath, out IAssetName assetName, out string error) + private bool TryGetTilesheetAssetName(string modRelativeMapFolder, string relativePath, out IAssetName? assetName, out string? error) { assetName = null; error = null; diff --git a/src/SMAPI/Framework/DeprecationManager.cs b/src/SMAPI/Framework/DeprecationManager.cs index fe1b623f..44b0ba2f 100644 --- a/src/SMAPI/Framework/DeprecationManager.cs +++ b/src/SMAPI/Framework/DeprecationManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -38,14 +36,14 @@ namespace StardewModdingAPI.Framework } /// Get the source name for a mod from its unique ID. - public string GetSourceNameFromStack() + public string? GetSourceNameFromStack() { return this.ModRegistry.GetFromStack()?.DisplayName; } /// Get the source name for a mod from its unique ID. /// The mod's unique ID. - public string GetSourceName(string modId) + public string? GetSourceName(string modId) { return this.ModRegistry.Get(modId)?.DisplayName; } @@ -55,10 +53,12 @@ namespace StardewModdingAPI.Framework /// A noun phrase describing what is deprecated. /// The SMAPI version which deprecated it. /// How deprecated the code is. - public void Warn(string source, string nounPhrase, string version, DeprecationLevel severity) + public void Warn(string? source, string nounPhrase, string version, DeprecationLevel severity) { + source ??= this.GetSourceNameFromStack() ?? ""; + // ignore if already warned - if (!this.MarkWarned(source ?? this.GetSourceNameFromStack() ?? "", nounPhrase, version)) + if (!this.MarkWarned(source, nounPhrase, version)) return; // queue warning @@ -99,17 +99,12 @@ namespace StardewModdingAPI.Framework } // log message - if (warning.ModName != null) - this.Monitor.Log(message, level); + if (level == LogLevel.Trace) + this.Monitor.Log($"{message}\n{warning.StackTrace}", level); else { - if (level == LogLevel.Trace) - this.Monitor.Log($"{message}\n{warning.StackTrace}", level); - else - { - this.Monitor.Log(message, level); - this.Monitor.Log(warning.StackTrace, LogLevel.Debug); - } + this.Monitor.Log(message, level); + this.Monitor.Log(warning.StackTrace, LogLevel.Debug); } } diff --git a/src/SMAPI/Framework/Input/GamePadStateBuilder.cs b/src/SMAPI/Framework/Input/GamePadStateBuilder.cs index 21168b7a..4ac3332c 100644 --- a/src/SMAPI/Framework/Input/GamePadStateBuilder.cs +++ b/src/SMAPI/Framework/Input/GamePadStateBuilder.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; @@ -23,7 +22,7 @@ namespace StardewModdingAPI.Framework.Input private GamePadState? State; /// The current button states. - private readonly IDictionary ButtonStates; + private readonly IDictionary? ButtonStates; /// The left trigger value. private float LeftTrigger; @@ -42,6 +41,7 @@ namespace StardewModdingAPI.Framework.Input ** Accessors *********/ /// Whether the gamepad is currently connected. + [MemberNotNullWhen(true, nameof(GamePadStateBuilder.ButtonStates))] public bool IsConnected { get; } @@ -213,6 +213,9 @@ namespace StardewModdingAPI.Framework.Input /// Get the pressed gamepad buttons. private IEnumerable GetPressedGamePadButtons() { + if (!this.IsConnected) + yield break; + foreach (var pair in this.ButtonStates) { if (pair.Value == ButtonState.Pressed && pair.Key.TryGetController(out Buttons button)) diff --git a/src/SMAPI/Framework/Input/SInputState.cs b/src/SMAPI/Framework/Input/SInputState.cs index 37b3c8ef..fef83af7 100644 --- a/src/SMAPI/Framework/Input/SInputState.cs +++ b/src/SMAPI/Framework/Input/SInputState.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -17,7 +15,7 @@ namespace StardewModdingAPI.Framework.Input ** Accessors *********/ /// The cursor position on the screen adjusted for the zoom level. - private CursorPosition CursorPositionImpl; + private CursorPosition CursorPositionImpl = new(Vector2.Zero, Vector2.Zero, Vector2.Zero, Vector2.Zero); /// The player's last known tile position. private Vector2? LastPlayerTile; @@ -106,7 +104,7 @@ namespace StardewModdingAPI.Framework.Input this.KeyboardState = keyboard.GetState(); this.MouseState = mouse.GetState(); this.ButtonStates = activeButtons; - if (cursorAbsolutePos != this.CursorPositionImpl?.AbsolutePixels || playerTilePos != this.LastPlayerTile) + if (cursorAbsolutePos != this.CursorPositionImpl.AbsolutePixels || playerTilePos != this.LastPlayerTile) { this.LastPlayerTile = playerTilePos; this.CursorPositionImpl = this.GetCursorPosition(this.MouseState, cursorAbsolutePos, zoomMultiplier); diff --git a/src/SMAPI/Framework/InternalExtensions.cs b/src/SMAPI/Framework/InternalExtensions.cs index a1d87487..fd8cc86f 100644 --- a/src/SMAPI/Framework/InternalExtensions.cs +++ b/src/SMAPI/Framework/InternalExtensions.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -43,6 +41,9 @@ namespace StardewModdingAPI.Framework /// The log severity level. public static void LogAsMod(this IModMetadata metadata, string message, LogLevel level = LogLevel.Trace) { + if (metadata.Monitor is null) + throw new InvalidOperationException($"Can't log as mod {metadata.DisplayName}: mod is broken or a content pack. Logged message:\n[{level}] {message}"); + metadata.Monitor.Log(message, level); } @@ -52,7 +53,7 @@ namespace StardewModdingAPI.Framework /// The log severity level. public static void LogAsModOnce(this IModMetadata metadata, string message, LogLevel level = LogLevel.Trace) { - metadata.Monitor.LogOnce(message, level); + metadata.Monitor?.LogOnce(message, level); } /**** @@ -159,7 +160,7 @@ namespace StardewModdingAPI.Framework /// The reflection helper with which to access private fields. public static bool IsOpen(this SpriteBatch spriteBatch, Reflector reflection) { - return reflection.GetField(spriteBatch, "_beginCalled").GetValue(); + return reflection.GetField(spriteBatch, "_beginCalled")!.GetValue(); } } } diff --git a/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs b/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs index a0957b90..9ecc1626 100644 --- a/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs +++ b/src/SMAPI/Framework/Logging/InterceptingTextWriter.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.IO; using System.Text; @@ -9,6 +7,13 @@ namespace StardewModdingAPI.Framework.Logging /// A text writer which allows intercepting output. internal class InterceptingTextWriter : TextWriter { + /********* + ** Fields + *********/ + /// The event raised when a message is written to the console directly. + private readonly Action OnMessageIntercepted; + + /********* ** Accessors *********/ @@ -21,9 +26,6 @@ namespace StardewModdingAPI.Framework.Logging /// public override Encoding Encoding => this.Out.Encoding; - /// The event raised when a message is written to the console directly. - public event Action OnMessageIntercepted; - /// Whether the text writer should ignore the next input if it's a newline. /// This is used when log output is suppressed from the console, since Console.WriteLine writes the trailing newline as a separate call. public bool IgnoreNextIfNewline { get; set; } @@ -34,9 +36,11 @@ namespace StardewModdingAPI.Framework.Logging *********/ /// Construct an instance. /// The underlying output writer. - public InterceptingTextWriter(TextWriter output) + /// The event raised when a message is written to the console directly. + public InterceptingTextWriter(TextWriter output, Action onMessageIntercepted) { this.Out = output; + this.OnMessageIntercepted = onMessageIntercepted; } /// @@ -65,7 +69,7 @@ namespace StardewModdingAPI.Framework.Logging this.Out.Write(buffer, index, count); } else - this.OnMessageIntercepted?.Invoke(new string(buffer, index, count)); + this.OnMessageIntercepted(new string(buffer, index, count)); } /// @@ -74,12 +78,6 @@ namespace StardewModdingAPI.Framework.Logging this.Out.Write(ch); } - /// - protected override void Dispose(bool disposing) - { - this.OnMessageIntercepted = null; - } - /********* ** Private methods diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index dab7f554..a5989673 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -95,6 +93,11 @@ namespace StardewModdingAPI.Framework.Logging /// Get the screen ID that should be logged to distinguish between players in split-screen mode, if any. public LogManager(string logPath, ColorSchemeConfig colorConfig, bool writeToConsole, bool isVerbose, bool isDeveloperMode, Func getScreenIdForLog) { + // init fields + this.LogFile = new LogFileManager(logPath); + this.Monitor = this.GetMonitor("SMAPI"); + this.MonitorForGame = this.GetMonitor("game"); + // init construction logic this.GetMonitorImpl = name => new Monitor(name, LogManager.IgnoreChar, this.LogFile, colorConfig, isVerbose, getScreenIdForLog) { @@ -103,15 +106,13 @@ namespace StardewModdingAPI.Framework.Logging ShowFullStampInConsole = isDeveloperMode }; - // init fields - this.LogFile = new LogFileManager(logPath); - this.Monitor = this.GetMonitor("SMAPI"); - this.MonitorForGame = this.GetMonitor("game"); - // redirect direct console output - this.ConsoleInterceptor = new InterceptingTextWriter(Console.Out); - if (writeToConsole) - this.ConsoleInterceptor.OnMessageIntercepted += message => this.HandleConsoleMessage(this.MonitorForGame, message); + this.ConsoleInterceptor = new InterceptingTextWriter( + output: Console.Out, + onMessageIntercepted: writeToConsole + ? message => this.HandleConsoleMessage(this.MonitorForGame, message) + : _ => { } + ); Console.SetOut(this.ConsoleInterceptor); // enable Unicode handling on Windows @@ -156,7 +157,7 @@ namespace StardewModdingAPI.Framework.Logging while (true) { // get input - string input = Console.ReadLine(); + string? input = Console.ReadLine(); if (string.IsNullOrWhiteSpace(input)) continue; @@ -222,7 +223,7 @@ namespace StardewModdingAPI.Framework.Logging if (File.Exists(Constants.UpdateMarker)) { string[] rawUpdateFound = File.ReadAllText(Constants.UpdateMarker).Split(new[] { '|' }, 2); - if (SemanticVersion.TryParse(rawUpdateFound[0], out ISemanticVersion updateFound)) + if (SemanticVersion.TryParse(rawUpdateFound[0], out ISemanticVersion? updateFound)) { if (Constants.ApiVersion.IsPrerelease() && updateFound.IsNewerThan(Constants.ApiVersion)) { @@ -264,7 +265,7 @@ namespace StardewModdingAPI.Framework.Logging /// Log the initial header with general SMAPI and system details. /// The path from which mods will be loaded. /// The custom SMAPI settings. - public void LogIntro(string modsPath, IDictionary customSettings) + public void LogIntro(string modsPath, IDictionary customSettings) { // log platform this.Monitor.Log($"SMAPI {Constants.ApiVersion} with Stardew Valley {Constants.GameVersion} (build {Constants.GetBuildVersionLabel()}) on {EnvironmentUtility.GetFriendlyPlatformName(Constants.Platform)}", LogLevel.Info); @@ -326,7 +327,7 @@ namespace StardewModdingAPI.Framework.Logging // log loaded content packs if (loadedContentPacks.Any()) { - string GetModDisplayName(string id) => loadedMods.FirstOrDefault(p => p.HasID(id))?.DisplayName; + string? GetModDisplayName(string id) => loadedMods.FirstOrDefault(p => p.HasID(id))?.DisplayName; this.Monitor.Log($"Loaded {loadedContentPacks.Length} content packs:", LogLevel.Info); foreach (IModMetadata metadata in loadedContentPacks.OrderBy(p => p.DisplayName)) @@ -335,7 +336,7 @@ namespace StardewModdingAPI.Framework.Logging this.Monitor.Log( $" {metadata.DisplayName} {manifest.Version}" + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "") - + $" | for {GetModDisplayName(metadata.Manifest.ContentPackFor.UniqueID)}" + + $" | for {GetModDisplayName(metadata.Manifest.ContentPackFor!.UniqueID)}" + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""), LogLevel.Info ); @@ -398,6 +399,7 @@ namespace StardewModdingAPI.Framework.Logging /// The loaded mods. /// The mods which could not be loaded. /// Whether to log issues for mods which directly use potentially sensitive .NET APIs like file or shell access. + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "Manifests aren't guaranteed non-null at this point in the loading process.")] private void LogModWarnings(IEnumerable mods, IModMetadata[] skippedMods, bool logParanoidWarnings) { // get mods with warnings @@ -431,7 +433,7 @@ namespace StardewModdingAPI.Framework.Logging // duplicate mod: log first one only, don't show redundant version if (mod.FailReason == ModFailReason.Duplicate && mod.HasManifest()) { - if (loggedDuplicateIds.Add(mod.Manifest.UniqueID)) + if (loggedDuplicateIds.Add(mod.Manifest!.UniqueID)) continue; // already logged message = $" - {mod.DisplayName} because {mod.Error}"; @@ -610,7 +612,7 @@ namespace StardewModdingAPI.Framework.Logging /// A brief heading label for the group. /// A detailed explanation of the warning, split into lines. /// Formats the mod label, or null to use the . - private void LogModWarningGroup(IModMetadata[] mods, Func match, LogLevel level, string heading, string[] blurb, Func modLabel = null) + private void LogModWarningGroup(IModMetadata[] mods, Func match, LogLevel level, string heading, string[] blurb, Func? modLabel = null) { // get matching mods string[] modLabels = mods diff --git a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs index c2b5092e..7d25979c 100644 --- a/src/SMAPI/Framework/ModHelpers/CommandHelper.cs +++ b/src/SMAPI/Framework/ModHelpers/CommandHelper.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; namespace StardewModdingAPI.Framework.ModHelpers @@ -24,7 +22,7 @@ namespace StardewModdingAPI.Framework.ModHelpers /// The mod using this instance. /// Manages console commands. public CommandHelper(IModMetadata mod, CommandManager commandManager) - : base(mod?.Manifest?.UniqueID ?? "SMAPI") + : base(mod.Manifest.UniqueID) { this.Mod = mod; this.CommandManager = commandManager; diff --git a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs index 070ee803..72b547b1 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyLoader.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -96,7 +94,12 @@ namespace StardewModdingAPI.Framework.ModLoading // get referenced local assemblies AssemblyParseResult[] assemblies; { - HashSet visitedAssemblyNames = new HashSet(AppDomain.CurrentDomain.GetAssemblies().Select(p => p.GetName().Name)); // don't try loading assemblies that are already loaded + HashSet visitedAssemblyNames = new HashSet( // don't try loading assemblies that are already loaded + from assembly in AppDomain.CurrentDomain.GetAssemblies() + let name = assembly.GetName().Name + where name != null + select name + ); assemblies = this.GetReferencedLocalAssemblies(new FileInfo(assemblyPath), visitedAssemblyNames, this.AssemblyDefinitionResolver).ToArray(); } @@ -113,11 +116,11 @@ namespace StardewModdingAPI.Framework.ModLoading // rewrite & load assemblies in leaf-to-root order bool oneAssembly = assemblies.Length == 1; - Assembly lastAssembly = null; + Assembly? lastAssembly = null; HashSet loggedMessages = new HashSet(); foreach (AssemblyParseResult assembly in assemblies) { - if (assembly.Status == AssemblyLoadStatus.AlreadyLoaded) + if (!assembly.HasDefinition) continue; // rewrite assembly @@ -165,7 +168,7 @@ namespace StardewModdingAPI.Framework.ModLoading throw new IncompatibleInstructionException(); // last assembly loaded is the root - return lastAssembly; + return lastAssembly!; } /// Get whether an assembly is loaded. @@ -174,7 +177,8 @@ namespace StardewModdingAPI.Framework.ModLoading { try { - return this.AssemblyDefinitionResolver.Resolve(reference) != null; + _ = this.AssemblyDefinitionResolver.Resolve(reference); + return true; } catch (AssemblyResolutionException) { @@ -190,7 +194,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// assemblies (especially with Mono). Since this is meant to be called on , /// the implicit assumption is that loading the exact assembly failed. /// - public static Assembly ResolveAssembly(string name) + public static Assembly? ResolveAssembly(string name) { string shortName = name.Split(new[] { ',' }, 2).First(); // get simple name (without version and culture) return AppDomain.CurrentDomain @@ -212,7 +216,8 @@ namespace StardewModdingAPI.Framework.ModLoading /// Track an object for disposal as part of the assembly loader. /// The instance type. /// The disposable instance. - private T TrackForDisposal(T instance) where T : IDisposable + private T TrackForDisposal(T instance) + where T : IDisposable { this.Disposables.Add(instance); return instance; @@ -321,9 +326,9 @@ namespace StardewModdingAPI.Framework.ModLoading // rewrite types using custom attributes foreach (TypeDefinition type in module.GetTypes()) { - foreach (var attr in type.CustomAttributes) + foreach (CustomAttribute attr in type.CustomAttributes) { - foreach (var conField in attr.ConstructorArguments) + foreach (CustomAttributeArgument conField in attr.ConstructorArguments) { if (conField.Value is TypeReference typeRef) this.ChangeTypeScope(typeRef); @@ -382,7 +387,7 @@ namespace StardewModdingAPI.Framework.ModLoading { // get message template // ($phrase is replaced with the noun phrase or messages) - string template = null; + string? template = null; switch (result) { case InstructionHandleResult.Rewritten: @@ -441,20 +446,20 @@ namespace StardewModdingAPI.Framework.ModLoading // format messages string phrase = handler.Phrases.Any() ? string.Join(", ", handler.Phrases) - : handler.DefaultPhrase ?? handler.GetType().Name; + : handler.DefaultPhrase; this.Monitor.LogOnce(loggedMessages, template.Replace("$phrase", phrase)); } /// Get the correct reference to use for compatibility with the current platform. /// The type reference to rewrite. - private void ChangeTypeScope(TypeReference type) + private void ChangeTypeScope(TypeReference? type) { // check skip conditions if (type == null || type.FullName.StartsWith("System.")) return; // get assembly - if (!this.TypeAssemblies.TryGetValue(type.FullName, out Assembly assembly)) + if (!this.TypeAssemblies.TryGetValue(type.FullName, out Assembly? assembly)) return; // replace scope diff --git a/src/SMAPI/Framework/ModLoading/AssemblyParseResult.cs b/src/SMAPI/Framework/ModLoading/AssemblyParseResult.cs index 56bd5a8b..b133f8d6 100644 --- a/src/SMAPI/Framework/ModLoading/AssemblyParseResult.cs +++ b/src/SMAPI/Framework/ModLoading/AssemblyParseResult.cs @@ -1,5 +1,5 @@ -#nullable disable - +using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using Mono.Cecil; @@ -15,11 +15,15 @@ namespace StardewModdingAPI.Framework.ModLoading public readonly FileInfo File; /// The assembly definition. - public readonly AssemblyDefinition Definition; + public readonly AssemblyDefinition? Definition; /// The result of the assembly load. public AssemblyLoadStatus Status; + /// Whether the is loaded and ready (i.e. the is not or ). + [MemberNotNullWhen(true, nameof(AssemblyParseResult.Definition))] + public bool HasDefinition => this.Status == AssemblyLoadStatus.Okay; + /********* ** Public methods @@ -28,11 +32,14 @@ namespace StardewModdingAPI.Framework.ModLoading /// The original assembly file. /// The assembly definition. /// The result of the assembly load. - public AssemblyParseResult(FileInfo file, AssemblyDefinition assembly, AssemblyLoadStatus status) + public AssemblyParseResult(FileInfo file, AssemblyDefinition? assembly, AssemblyLoadStatus status) { this.File = file; this.Definition = assembly; this.Status = status; + + if (status == AssemblyLoadStatus.Okay && assembly == null) + throw new InvalidOperationException($"Invalid assembly parse result: load status {status} with a null assembly."); } } } diff --git a/src/SMAPI/Framework/ModLoading/ModResolver.cs b/src/SMAPI/Framework/ModLoading/ModResolver.cs index 4fdeefbc..afb388d0 100644 --- a/src/SMAPI/Framework/ModLoading/ModResolver.cs +++ b/src/SMAPI/Framework/ModLoading/ModResolver.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using StardewModdingAPI.Toolkit; @@ -28,10 +27,10 @@ namespace StardewModdingAPI.Framework.ModLoading { foreach (ModFolder folder in toolkit.GetModFolders(rootPath)) { - Manifest manifest = folder.Manifest; + Manifest? manifest = folder.Manifest; // parse internal data record (if any) - ModDataRecordVersionedFields dataRecord = modDatabase.Get(manifest?.UniqueID)?.GetVersionedFields(manifest); + ModDataRecordVersionedFields? dataRecord = modDatabase.Get(manifest?.UniqueID)?.GetVersionedFields(manifest); // apply defaults if (manifest != null && dataRecord?.UpdateKey is not null) @@ -43,7 +42,7 @@ namespace StardewModdingAPI.Framework.ModLoading ? ModMetadataStatus.Found : ModMetadataStatus.Failed; - var metadata = new ModMetadata(folder.DisplayName, folder.Directory.FullName, rootPath, manifest, dataRecord, isIgnored: shouldIgnore); + IModMetadata metadata = new ModMetadata(folder.DisplayName, folder.Directory.FullName, rootPath, manifest, dataRecord, isIgnored: shouldIgnore); if (shouldIgnore) metadata.SetStatus(status, ModFailReason.DisabledByDotConvention, "disabled by dot convention"); else @@ -57,7 +56,9 @@ namespace StardewModdingAPI.Framework.ModLoading /// The mod manifests to validate. /// The current SMAPI version. /// Get an update URL for an update key (if valid). - public void ValidateManifests(IEnumerable mods, ISemanticVersion apiVersion, Func getUpdateUrl) + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "Manifest values may be null before they're validated.")] + [SuppressMessage("ReSharper", "ConditionIsAlwaysTrueOrFalse", Justification = "Manifest values may be null before they're validated.")] + public void ValidateManifests(IEnumerable mods, ISemanticVersion apiVersion, Func getUpdateUrl) { mods = mods.ToArray(); @@ -84,7 +85,7 @@ namespace StardewModdingAPI.Framework.ModLoading List updateUrls = new List(); foreach (UpdateKey key in mod.GetUpdateKeys(validOnly: true)) { - string url = getUpdateUrl(key.ToString()); + string? url = getUpdateUrl(key.ToString()); if (url != null) updateUrls.Add(url); } @@ -94,7 +95,7 @@ namespace StardewModdingAPI.Framework.ModLoading // build error string error = $"{reasonPhrase}. Please check for a "; - if (mod.DataRecord.StatusUpperVersion == null || mod.Manifest.Version.Equals(mod.DataRecord.StatusUpperVersion)) + if (mod.DataRecord.StatusUpperVersion == null || mod.Manifest.Version?.Equals(mod.DataRecord.StatusUpperVersion) == true) error += "newer version"; else error += $"version newer than {mod.DataRecord.StatusUpperVersion}"; @@ -133,21 +134,21 @@ namespace StardewModdingAPI.Framework.ModLoading if (hasDll) { // invalid filename format - if (mod.Manifest.EntryDll.Intersect(Path.GetInvalidFileNameChars()).Any()) + if (mod.Manifest.EntryDll!.Intersect(Path.GetInvalidFileNameChars()).Any()) { mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its manifest has invalid filename '{mod.Manifest.EntryDll}' for the EntryDLL field."); continue; } // invalid path - if (!File.Exists(Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll))) + if (!File.Exists(Path.Combine(mod.DirectoryPath, mod.Manifest.EntryDll!))) { mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its DLL '{mod.Manifest.EntryDll}' doesn't exist."); continue; } // invalid capitalization - string actualFilename = new DirectoryInfo(mod.DirectoryPath).GetFiles(mod.Manifest.EntryDll).FirstOrDefault()?.Name; + string? actualFilename = new DirectoryInfo(mod.DirectoryPath).GetFiles(mod.Manifest.EntryDll!).FirstOrDefault()?.Name; if (actualFilename != mod.Manifest.EntryDll) { mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its {nameof(IManifest.EntryDll)} value '{mod.Manifest.EntryDll}' doesn't match the actual file capitalization '{actualFilename}'. The capitalization must match for crossplatform compatibility."); @@ -159,7 +160,7 @@ namespace StardewModdingAPI.Framework.ModLoading else { // invalid content pack ID - if (string.IsNullOrWhiteSpace(mod.Manifest.ContentPackFor.UniqueID)) + if (string.IsNullOrWhiteSpace(mod.Manifest.ContentPackFor!.UniqueID)) { mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, $"its manifest declares {nameof(IManifest.ContentPackFor)} without its required {nameof(IManifestContentPackFor.UniqueID)} field."); continue; @@ -190,7 +191,7 @@ namespace StardewModdingAPI.Framework.ModLoading mod.SetStatus(ModMetadataStatus.Failed, ModFailReason.InvalidManifest, "its manifest specifies an invalid ID (IDs must only contain letters, numbers, underscores, periods, or hyphens)."); // validate dependencies - foreach (var dependency in mod.Manifest.Dependencies) + foreach (IManifestDependency? dependency in mod.Manifest.Dependencies) { // null dependency if (dependency == null) @@ -328,8 +329,11 @@ namespace StardewModdingAPI.Framework.ModLoading string[] failedLabels = ( from entry in dependencies - where entry.Mod != null && entry.MinVersion != null && entry.MinVersion.IsNewerThan(entry.Mod.Manifest.Version) - select $"{entry.Mod.DisplayName} (needs {entry.MinVersion} or later)" + where + entry.Mod != null + && entry.MinVersion != null + && entry.MinVersion.IsNewerThan(entry.Mod.Manifest.Version) + select $"{entry.Mod!.DisplayName} (needs {entry.MinVersion} or later)" ) .ToArray(); if (failedLabels.Any()) @@ -345,16 +349,14 @@ namespace StardewModdingAPI.Framework.ModLoading states[mod] = ModDependencyStatus.Checking; // recursively sort dependencies - foreach (var dependency in dependencies) + foreach (ModDependency dependency in dependencies) { - IModMetadata requiredMod = dependency.Mod; - var subchain = new List(currentChain) { mod }; - - // ignore missing optional dependency - if (!dependency.IsRequired && requiredMod == null) - continue; + IModMetadata? requiredMod = dependency.Mod; + if (requiredMod == null) + continue; // missing dependencies are handled earlier // detect dependency loop + var subchain = new List(currentChain) { mod }; if (states[requiredMod] == ModDependencyStatus.Checking) { sortedMods.Push(mod); @@ -363,8 +365,8 @@ namespace StardewModdingAPI.Framework.ModLoading } // recursively process each dependency - var substatus = this.ProcessDependencies(mods, modDatabase, requiredMod, states, sortedMods, subchain); - switch (substatus) + var subStatus = this.ProcessDependencies(mods, modDatabase, requiredMod, states, sortedMods, subchain); + switch (subStatus) { // sorted successfully case ModDependencyStatus.Sorted: @@ -380,7 +382,7 @@ namespace StardewModdingAPI.Framework.ModLoading // unexpected status case ModDependencyStatus.Queued: case ModDependencyStatus.Checking: - throw new InvalidModStateException($"Something went wrong sorting dependencies: mod '{requiredMod.DisplayName}' unexpectedly stayed in the '{substatus}' status."); + throw new InvalidModStateException($"Something went wrong sorting dependencies: mod '{requiredMod.DisplayName}' unexpectedly stayed in the '{subStatus}' status."); // sanity check default: @@ -399,14 +401,11 @@ namespace StardewModdingAPI.Framework.ModLoading /// The loaded mods. private IEnumerable GetDependenciesFrom(IManifest manifest, IModMetadata[] loadedMods) { - IModMetadata FindMod(string id) => loadedMods.FirstOrDefault(m => m.HasID(id)); + IModMetadata? FindMod(string id) => loadedMods.FirstOrDefault(m => m.HasID(id)); // yield dependencies - if (manifest.Dependencies != null) - { - foreach (var entry in manifest.Dependencies) - yield return new ModDependency(entry.UniqueID, entry.MinimumVersion, FindMod(entry.UniqueID), entry.IsRequired); - } + foreach (IManifestDependency entry in manifest.Dependencies) + yield return new ModDependency(entry.UniqueID, entry.MinimumVersion, FindMod(entry.UniqueID), entry.IsRequired); // yield content pack parent if (manifest.ContentPackFor != null) @@ -415,10 +414,10 @@ namespace StardewModdingAPI.Framework.ModLoading /// Get a technical message indicating why a mod's compatibility status was overridden, if applicable. /// The mod metadata. - private string GetTechnicalReasonForStatusOverride(IModMetadata mod) + private string? GetTechnicalReasonForStatusOverride(IModMetadata mod) { // get compatibility list record - var data = mod.DataRecord; + ModDataRecordVersionedFields? data = mod.DataRecord; if (data == null) return null; @@ -432,14 +431,14 @@ namespace StardewModdingAPI.Framework.ModLoading }; // get reason - string[] reasons = new[] { mod.DataRecord.StatusReasonPhrase, mod.DataRecord.StatusReasonDetails } + string?[] reasons = new[] { data.StatusReasonPhrase, data.StatusReasonDetails } .Where(p => !string.IsNullOrWhiteSpace(p)) .ToArray(); // build message return $"marked {statusLabel} in SMAPI's internal compatibility list for " - + (mod.DataRecord.StatusUpperVersion != null ? $"versions up to {mod.DataRecord.StatusUpperVersion}" : "all versions") + + (data.StatusUpperVersion != null ? $"versions up to {data.StatusUpperVersion}" : "all versions") + ": " + (reasons.Any() ? string.Join(": ", reasons) : "no reason given") + "."; @@ -459,13 +458,13 @@ namespace StardewModdingAPI.Framework.ModLoading public string ID { get; } /// The minimum required version (if any). - public ISemanticVersion MinVersion { get; } + public ISemanticVersion? MinVersion { get; } /// Whether the mod shouldn't be loaded if the dependency isn't available. public bool IsRequired { get; } /// The loaded mod that fulfills the dependency (if available). - public IModMetadata Mod { get; } + public IModMetadata? Mod { get; } /********* @@ -476,7 +475,7 @@ namespace StardewModdingAPI.Framework.ModLoading /// The minimum required version (if any). /// The loaded mod that fulfills the dependency (if available). /// Whether the mod shouldn't be loaded if the dependency isn't available. - public ModDependency(string id, ISemanticVersion minVersion, IModMetadata mod, bool isRequired) + public ModDependency(string id, ISemanticVersion? minVersion, IModMetadata? mod, bool isRequired) { this.ID = id; this.MinVersion = minVersion; diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs index 806fca62..d5f4cf4a 100644 --- a/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs +++ b/src/SMAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Reflection; @@ -33,13 +31,19 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// The new field name to reference. public FieldReplaceRewriter AddField(Type fromType, string fromFieldName, Type toType, string toFieldName) { + // validate parameters + if (fromType == null) + throw new InvalidOperationException("Can't replace a field on a null source type."); + if (toType == null) + throw new InvalidOperationException("Can't replace a field on a null target type."); + // get full type name - string fromTypeName = fromType?.FullName; + string? fromTypeName = fromType.FullName; if (fromTypeName == null) throw new InvalidOperationException($"Can't replace field for invalid type reference {toType}."); // get target field - FieldInfo toField = toType.GetField(toFieldName); + FieldInfo? toField = toType.GetField(toFieldName); if (toField == null) throw new InvalidOperationException($"The {toType.FullName} class doesn't have a {toFieldName} field."); @@ -54,15 +58,15 @@ namespace StardewModdingAPI.Framework.ModLoading.Rewriters /// public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction) { - FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction); - string declaringType = fieldRef?.DeclaringType?.FullName; + FieldReference? fieldRef = RewriteHelper.AsFieldReference(instruction); + string? declaringType = fieldRef?.DeclaringType?.FullName; // get mapped field - if (declaringType == null || !this.FieldMaps.TryGetValue(declaringType, out var fieldMap) || !fieldMap.TryGetValue(fieldRef.Name, out FieldInfo toField)) + if (declaringType == null || !this.FieldMaps.TryGetValue(declaringType, out var fieldMap) || !fieldMap.TryGetValue(fieldRef!.Name, out FieldInfo? toField)) return false; // replace with new field - this.Phrases.Add($"{fieldRef.DeclaringType.Name}.{fieldRef.Name} field"); + this.Phrases.Add($"{fieldRef.DeclaringType!.Name}.{fieldRef.Name} field"); instruction.Operand = module.ImportReference(toField); return this.MarkRewritten(); } diff --git a/src/SMAPI/Framework/Models/SConfig.cs b/src/SMAPI/Framework/Models/SConfig.cs index e74d73b5..d626ab4d 100644 --- a/src/SMAPI/Framework/Models/SConfig.cs +++ b/src/SMAPI/Framework/Models/SConfig.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -40,60 +38,96 @@ namespace StardewModdingAPI.Framework.Models ** Accessors ********/ /// Whether to enable development features. - public bool DeveloperMode { get; set; } + public bool DeveloperMode { get; private set; } /// Whether to check for newer versions of SMAPI and mods on startup. - public bool CheckForUpdates { get; set; } + public bool CheckForUpdates { get; } /// Whether to add a section to the 'mod issues' list for mods which which directly use potentially sensitive .NET APIs like file or shell access. - public bool ParanoidWarnings { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.ParanoidWarnings)]; + public bool ParanoidWarnings { get; } /// Whether to show beta versions as valid updates. - public bool UseBetaChannel { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.UseBetaChannel)]; + public bool UseBetaChannel { get; } /// SMAPI's GitHub project name, used to perform update checks. - public string GitHubProjectName { get; set; } + public string GitHubProjectName { get; } /// The base URL for SMAPI's web API, used to perform update checks. - public string WebApiBaseUrl { get; set; } + public string WebApiBaseUrl { get; } /// Whether SMAPI should log more information about the game context. - public bool VerboseLogging { get; set; } + public bool VerboseLogging { get; } /// Whether SMAPI should rewrite mods for compatibility. - public bool RewriteMods { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.RewriteMods)]; + public bool RewriteMods { get; } /// Whether to enable more aggressive memory optimizations. - public bool AggressiveMemoryOptimizations { get; set; } = (bool)SConfig.DefaultValues[nameof(SConfig.AggressiveMemoryOptimizations)]; + public bool AggressiveMemoryOptimizations { get; } /// Whether SMAPI should log network traffic. Best combined with , which includes network metadata. - public bool LogNetworkTraffic { get; set; } + public bool LogNetworkTraffic { get; } /// The colors to use for text written to the SMAPI console. - public ColorSchemeConfig ConsoleColors { get; set; } + public ColorSchemeConfig ConsoleColors { get; } /// The mod IDs SMAPI should ignore when performing update checks or validating update keys. - public string[] SuppressUpdateChecks { get; set; } + public string[] SuppressUpdateChecks { get; } /******** ** Public methods ********/ + /// Construct an instance. + /// Whether to enable development features. + /// Whether to check for newer versions of SMAPI and mods on startup. + /// Whether to add a section to the 'mod issues' list for mods which which directly use potentially sensitive .NET APIs like file or shell access. + /// Whether to show beta versions as valid updates. + /// SMAPI's GitHub project name, used to perform update checks. + /// The base URL for SMAPI's web API, used to perform update checks. + /// Whether SMAPI should log more information about the game context. + /// Whether SMAPI should rewrite mods for compatibility. + /// Whether to enable more aggressive memory optimizations. + /// Whether SMAPI should log network traffic. + /// The colors to use for text written to the SMAPI console. + /// The mod IDs SMAPI should ignore when performing update checks or validating update keys. + public SConfig(bool developerMode, bool checkForUpdates, bool? paranoidWarnings, bool? useBetaChannel, string gitHubProjectName, string webApiBaseUrl, bool verboseLogging, bool? rewriteMods, bool? aggressiveMemoryOptimizations, bool logNetworkTraffic, ColorSchemeConfig consoleColors, string[]? suppressUpdateChecks) + { + this.DeveloperMode = developerMode; + this.CheckForUpdates = checkForUpdates; + this.ParanoidWarnings = paranoidWarnings ?? (bool)SConfig.DefaultValues[nameof(SConfig.ParanoidWarnings)]; + this.UseBetaChannel = useBetaChannel ?? (bool)SConfig.DefaultValues[nameof(SConfig.UseBetaChannel)]; + this.GitHubProjectName = gitHubProjectName; + this.WebApiBaseUrl = webApiBaseUrl; + this.VerboseLogging = verboseLogging; + this.RewriteMods = rewriteMods ?? (bool)SConfig.DefaultValues[nameof(SConfig.RewriteMods)]; + this.AggressiveMemoryOptimizations = aggressiveMemoryOptimizations ?? (bool)SConfig.DefaultValues[nameof(SConfig.AggressiveMemoryOptimizations)]; + this.LogNetworkTraffic = logNetworkTraffic; + this.ConsoleColors = consoleColors; + this.SuppressUpdateChecks = suppressUpdateChecks ?? Array.Empty(); + } + + /// Override the value of . + /// The value to set. + public void OverrideDeveloperMode(bool value) + { + this.DeveloperMode = value; + } + /// Get the settings which have been customized by the player. - public IDictionary GetCustomSettings() + public IDictionary GetCustomSettings() { - IDictionary custom = new Dictionary(); + Dictionary custom = new(); - foreach (var pair in SConfig.DefaultValues) + foreach ((string? name, object defaultValue) in SConfig.DefaultValues) { - object value = typeof(SConfig).GetProperty(pair.Key)?.GetValue(this); - if (!pair.Value.Equals(value)) - custom[pair.Key] = value; + object? value = typeof(SConfig).GetProperty(name)?.GetValue(this); + if (!defaultValue.Equals(value)) + custom[name] = value; } - HashSet curSuppressUpdateChecks = new HashSet(this.SuppressUpdateChecks ?? Array.Empty(), StringComparer.OrdinalIgnoreCase); + HashSet curSuppressUpdateChecks = new(this.SuppressUpdateChecks, StringComparer.OrdinalIgnoreCase); if (SConfig.DefaultSuppressUpdateChecks.Count != curSuppressUpdateChecks.Count || SConfig.DefaultSuppressUpdateChecks.Any(p => !curSuppressUpdateChecks.Contains(p))) - custom[nameof(this.SuppressUpdateChecks)] = "[" + string.Join(", ", this.SuppressUpdateChecks ?? Array.Empty()) + "]"; + custom[nameof(this.SuppressUpdateChecks)] = "[" + string.Join(", ", this.SuppressUpdateChecks) + "]"; return custom; } diff --git a/src/SMAPI/Framework/Networking/ModMessageModel.cs b/src/SMAPI/Framework/Networking/ModMessageModel.cs index 4e7d01eb..01672714 100644 --- a/src/SMAPI/Framework/Networking/ModMessageModel.cs +++ b/src/SMAPI/Framework/Networking/ModMessageModel.cs @@ -1,6 +1,5 @@ -#nullable disable - using System.Linq; +using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace StardewModdingAPI.Framework.Networking @@ -15,33 +14,30 @@ namespace StardewModdingAPI.Framework.Networking ** Origin ****/ /// The unique ID of the player who broadcast the message. - public long FromPlayerID { get; set; } + public long FromPlayerID { get; } /// The unique ID of the mod which broadcast the message. - public string FromModID { get; set; } + public string FromModID { get; } /**** ** Destination ****/ /// The players who should receive the message. - public long[] ToPlayerIDs { get; set; } + public long[]? ToPlayerIDs { get; init; } /// The mods which should receive the message, or null for all mods. - public string[] ToModIDs { get; set; } + public string[]? ToModIDs { get; } /// A message type which receiving mods can use to decide whether it's the one they want to handle, like SetPlayerLocation. This doesn't need to be globally unique, since mods should check the originating mod ID. - public string Type { get; set; } + public string Type { get; } /// The custom mod data being broadcast. - public JToken Data { get; set; } + public JToken Data { get; } /********* ** Public methods *********/ - /// Construct an instance. - public ModMessageModel() { } - /// Construct an instance. /// The unique ID of the player who broadcast the message. /// The unique ID of the mod which broadcast the message. @@ -49,7 +45,8 @@ namespace StardewModdingAPI.Framework.Networking /// The mods which should receive the message, or null for all mods. /// A message type which receiving mods can use to decide whether it's the one they want to handle, like SetPlayerLocation. This doesn't need to be globally unique, since mods should check the originating mod ID. /// The custom mod data being broadcast. - public ModMessageModel(long fromPlayerID, string fromModID, long[] toPlayerIDs, string[] toModIDs, string type, JToken data) + [JsonConstructor] + public ModMessageModel(long fromPlayerID, string fromModID, long[]? toPlayerIDs, string[]? toModIDs, string type, JToken data) { this.FromPlayerID = fromPlayerID; this.FromModID = fromModID; diff --git a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs index 8ee5c309..b37c1e89 100644 --- a/src/SMAPI/Framework/Networking/MultiplayerPeer.cs +++ b/src/SMAPI/Framework/Networking/MultiplayerPeer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -39,10 +37,10 @@ namespace StardewModdingAPI.Framework.Networking public GamePlatform? Platform { get; } /// - public ISemanticVersion GameVersion { get; } + public ISemanticVersion? GameVersion { get; } /// - public ISemanticVersion ApiVersion { get; } + public ISemanticVersion? ApiVersion { get; } /// public IEnumerable Mods { get; } @@ -57,11 +55,12 @@ namespace StardewModdingAPI.Framework.Networking /// The metadata to copy. /// A method which sends a message to the peer. /// Whether this is a connection to the host player. - public MultiplayerPeer(long playerID, int? screenID, RemoteContextModel model, Action sendMessage, bool isHost) + public MultiplayerPeer(long playerID, int? screenID, RemoteContextModel? model, Action sendMessage, bool isHost) { this.PlayerID = playerID; this.ScreenID = screenID; this.IsHost = isHost; + if (model != null) { this.Platform = model.Platform; @@ -69,13 +68,16 @@ namespace StardewModdingAPI.Framework.Networking this.ApiVersion = model.ApiVersion; this.Mods = model.Mods.Select(mod => new MultiplayerPeerMod(mod)).ToArray(); } + else + this.Mods = Array.Empty(); + this.SendMessageImpl = sendMessage; } /// - public IMultiplayerPeerMod GetMod(string id) + public IMultiplayerPeerMod? GetMod(string? id) { - if (string.IsNullOrWhiteSpace(id) || this.Mods == null || !this.Mods.Any()) + if (string.IsNullOrWhiteSpace(id) || !this.Mods.Any()) return null; id = id.Trim(); diff --git a/src/SMAPI/Framework/Networking/MultiplayerPeerMod.cs b/src/SMAPI/Framework/Networking/MultiplayerPeerMod.cs index 6fdb9e54..1e150508 100644 --- a/src/SMAPI/Framework/Networking/MultiplayerPeerMod.cs +++ b/src/SMAPI/Framework/Networking/MultiplayerPeerMod.cs @@ -1,4 +1,4 @@ -#nullable disable +using System.Diagnostics.CodeAnalysis; namespace StardewModdingAPI.Framework.Networking { @@ -22,10 +22,11 @@ namespace StardewModdingAPI.Framework.Networking *********/ /// Construct an instance. /// The mod metadata. + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "The ID shouldn't be null, but we should handle it to avoid an error just in case.")] public MultiplayerPeerMod(RemoteContextModModel mod) { this.Name = mod.Name; - this.ID = mod.ID?.Trim(); + this.ID = mod.ID?.Trim() ?? string.Empty; this.Version = mod.Version; } } diff --git a/src/SMAPI/Framework/Networking/RemoteContextModModel.cs b/src/SMAPI/Framework/Networking/RemoteContextModModel.cs index 0383576c..7571acba 100644 --- a/src/SMAPI/Framework/Networking/RemoteContextModModel.cs +++ b/src/SMAPI/Framework/Networking/RemoteContextModModel.cs @@ -1,17 +1,33 @@ -#nullable disable - namespace StardewModdingAPI.Framework.Networking { /// Metadata about an installed mod exchanged with connected computers. public class RemoteContextModModel { - /// The mod's display name. - public string Name { get; set; } - + /********* + ** Accessors + *********/ /// The unique mod ID. - public string ID { get; set; } + public string ID { get; } + + /// The mod's display name. + public string Name { get; } /// The mod version. - public ISemanticVersion Version { get; set; } + public ISemanticVersion Version { get; } + + + /********* + ** Accessors + *********/ + /// Construct an instance. + /// The unique mod ID. + /// The mod's display name. + /// The mod version. + public RemoteContextModModel(string id, string name, ISemanticVersion version) + { + this.ID = id; + this.Name = name; + this.Version = version; + } } } diff --git a/src/SMAPI/Framework/Networking/RemoteContextModel.cs b/src/SMAPI/Framework/Networking/RemoteContextModel.cs index 37fafa67..7d53e732 100644 --- a/src/SMAPI/Framework/Networking/RemoteContextModel.cs +++ b/src/SMAPI/Framework/Networking/RemoteContextModel.cs @@ -1,4 +1,4 @@ -#nullable disable +using System; namespace StardewModdingAPI.Framework.Networking { @@ -9,18 +9,37 @@ namespace StardewModdingAPI.Framework.Networking ** Accessors *********/ /// Whether this player is the host player. - public bool IsHost { get; set; } + public bool IsHost { get; } - /// The game's platform version. - public GamePlatform Platform { get; set; } + /// The game's platform. + public GamePlatform Platform { get; } /// The installed version of Stardew Valley. - public ISemanticVersion GameVersion { get; set; } + public ISemanticVersion? GameVersion { get; } /// The installed version of SMAPI. - public ISemanticVersion ApiVersion { get; set; } + public ISemanticVersion? ApiVersion { get; } /// The installed mods. - public RemoteContextModModel[] Mods { get; set; } + public RemoteContextModModel[] Mods { get; } + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// Whether this player is the host player. + /// The game's platform. + /// The installed version of Stardew Valley. + /// The installed version of SMAPI. + /// The installed mods. + public RemoteContextModel(bool isHost, GamePlatform platform, ISemanticVersion gameVersion, ISemanticVersion apiVersion, RemoteContextModModel[]? mods) + { + this.IsHost = isHost; + this.Platform = platform; + this.GameVersion = gameVersion; + this.ApiVersion = apiVersion; + this.Mods = mods ?? Array.Empty(); + } } } diff --git a/src/SMAPI/Framework/Reflection/CacheEntry.cs b/src/SMAPI/Framework/Reflection/CacheEntry.cs index 6b18d204..27f48a1f 100644 --- a/src/SMAPI/Framework/Reflection/CacheEntry.cs +++ b/src/SMAPI/Framework/Reflection/CacheEntry.cs @@ -1,5 +1,4 @@ -#nullable disable - +using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace StardewModdingAPI.Framework.Reflection @@ -11,21 +10,20 @@ namespace StardewModdingAPI.Framework.Reflection ** Accessors *********/ /// Whether the lookup found a valid match. - public bool IsValid { get; } + [MemberNotNullWhen(true, nameof(CacheEntry.MemberInfo))] + public bool IsValid => this.MemberInfo != null; /// The reflection data for this member (or null if invalid). - public MemberInfo MemberInfo { get; } + public MemberInfo? MemberInfo { get; } /********* ** Public methods *********/ /// Construct an instance. - /// Whether the lookup found a valid match. /// The reflection data for this member (or null if invalid). - public CacheEntry(bool isValid, MemberInfo memberInfo) + public CacheEntry(MemberInfo? memberInfo) { - this.IsValid = isValid; this.MemberInfo = memberInfo; } } diff --git a/src/SMAPI/Framework/Reflection/Reflector.cs b/src/SMAPI/Framework/Reflection/Reflector.cs index c6fc2c79..3490ee97 100644 --- a/src/SMAPI/Framework/Reflection/Reflector.cs +++ b/src/SMAPI/Framework/Reflection/Reflector.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Reflection; using System.Runtime.Caching; @@ -14,7 +12,7 @@ namespace StardewModdingAPI.Framework.Reflection ** Fields *********/ /// The cached fields and methods found via reflection. - private readonly MemoryCache Cache = new(typeof(Reflector).FullName); + private readonly MemoryCache Cache = new(typeof(Reflector).FullName!); /// The sliding cache expiration time. private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5); @@ -30,8 +28,9 @@ namespace StardewModdingAPI.Framework.Reflection /// The field type. /// The object which has the field. /// The field name. - /// Whether to throw an exception if the field is not found. - /// Returns the field wrapper, or null if the field doesn't exist and is false. + /// Whether to throw an exception if the field isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the field wrapper, or null if is false and the field doesn't exist. + /// The target field doesn't exist, and is true. public IReflectedField GetField(object obj, string name, bool required = true) { // validate @@ -39,24 +38,26 @@ namespace StardewModdingAPI.Framework.Reflection throw new ArgumentNullException(nameof(obj), "Can't get a instance field from a null object."); // get field from hierarchy - IReflectedField field = this.GetFieldFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + IReflectedField? field = this.GetFieldFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (required && field == null) throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a '{name}' instance field."); - return field; + return field!; } /// Get a static field. /// The field type. /// The type which has the field. /// The field name. - /// Whether to throw an exception if the field is not found. + /// Whether to throw an exception if the field isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the field wrapper, or null if is false and the field doesn't exist. + /// The target field doesn't exist, and is true. public IReflectedField GetField(Type type, string name, bool required = true) { // get field from hierarchy - IReflectedField field = this.GetFieldFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public); + IReflectedField? field = this.GetFieldFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Public); if (required && field == null) throw new InvalidOperationException($"The {type.FullName} object doesn't have a '{name}' static field."); - return field; + return field!; } /**** @@ -66,7 +67,9 @@ namespace StardewModdingAPI.Framework.Reflection /// The property type. /// The object which has the property. /// The property name. - /// Whether to throw an exception if the property is not found. + /// Whether to throw an exception if the property isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the property wrapper, or null if is false and the property doesn't exist. + /// The target property doesn't exist, and is true. public IReflectedProperty GetProperty(object obj, string name, bool required = true) { // validate @@ -74,24 +77,26 @@ namespace StardewModdingAPI.Framework.Reflection throw new ArgumentNullException(nameof(obj), "Can't get a instance property from a null object."); // get property from hierarchy - IReflectedProperty property = this.GetPropertyFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + IReflectedProperty? property = this.GetPropertyFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (required && property == null) throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a '{name}' instance property."); - return property; + return property!; } /// Get a static property. /// The property type. /// The type which has the property. /// The property name. - /// Whether to throw an exception if the property is not found. + /// Whether to throw an exception if the property isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the property wrapper, or null if is false and the property doesn't exist. + /// The target property doesn't exist, and is true. public IReflectedProperty GetProperty(Type type, string name, bool required = true) { // get field from hierarchy - IReflectedProperty property = this.GetPropertyFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + IReflectedProperty? property = this.GetPropertyFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (required && property == null) throw new InvalidOperationException($"The {type.FullName} object doesn't have a '{name}' static property."); - return property; + return property!; } /**** @@ -99,8 +104,10 @@ namespace StardewModdingAPI.Framework.Reflection ****/ /// Get a instance method. /// The object which has the method. - /// The field name. - /// Whether to throw an exception if the field is not found. + /// The method name. + /// Whether to throw an exception if the method isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the method wrapper, or null if is false and the method doesn't exist. + /// The target method doesn't exist, and is true. public IReflectedMethod GetMethod(object obj, string name, bool required = true) { // validate @@ -108,23 +115,25 @@ namespace StardewModdingAPI.Framework.Reflection throw new ArgumentNullException(nameof(obj), "Can't get a instance method from a null object."); // get method from hierarchy - IReflectedMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + IReflectedMethod? method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (required && method == null) throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a '{name}' instance method."); - return method; + return method!; } /// Get a static method. /// The type which has the method. - /// The field name. - /// Whether to throw an exception if the field is not found. + /// The method name. + /// Whether to throw an exception if the method isn't found. Due to limitations with nullable reference types, setting this to false will still mark the value non-nullable. + /// Returns the method wrapper, or null if is false and the method doesn't exist. + /// The target method doesn't exist, and is true. public IReflectedMethod GetMethod(Type type, string name, bool required = true) { // get method from hierarchy - IReflectedMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + IReflectedMethod? method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); if (required && method == null) throw new InvalidOperationException($"The {type.FullName} object doesn't have a '{name}' static method."); - return method; + return method!; } @@ -134,18 +143,25 @@ namespace StardewModdingAPI.Framework.Reflection /// Get a field from the type hierarchy. /// The expected field type. /// The type which has the field. - /// The object which has the field. + /// The object which has the field, or null for a static field. /// The field name. /// The reflection binding which flags which indicates what type of field to find. - private IReflectedField GetFieldFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags) + private IReflectedField? GetFieldFromHierarchy(Type type, object? obj, string name, BindingFlags bindingFlags) { bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); - FieldInfo field = this.GetCached($"field::{isStatic}::{type.FullName}::{name}", () => + FieldInfo? field = this.GetCached($"field::{isStatic}::{type.FullName}::{name}", () => { - FieldInfo fieldInfo = null; - for (; type != null && fieldInfo == null; type = type.BaseType) - fieldInfo = type.GetField(name, bindingFlags); - return fieldInfo; + for (Type? curType = type; curType != null; curType = curType.BaseType) + { + FieldInfo? fieldInfo = type.GetField(name, bindingFlags); + if (fieldInfo != null) + { + type = curType; + return fieldInfo; + } + } + + return null; }); return field != null @@ -156,18 +172,25 @@ namespace StardewModdingAPI.Framework.Reflection /// Get a property from the type hierarchy. /// The expected property type. /// The type which has the property. - /// The object which has the property. + /// The object which has the property, or null for a static property. /// The property name. /// The reflection binding which flags which indicates what type of property to find. - private IReflectedProperty GetPropertyFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags) + private IReflectedProperty? GetPropertyFromHierarchy(Type type, object? obj, string name, BindingFlags bindingFlags) { bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); - PropertyInfo property = this.GetCached($"property::{isStatic}::{type.FullName}::{name}", () => + PropertyInfo? property = this.GetCached($"property::{isStatic}::{type.FullName}::{name}", () => { - PropertyInfo propertyInfo = null; - for (; type != null && propertyInfo == null; type = type.BaseType) - propertyInfo = type.GetProperty(name, bindingFlags); - return propertyInfo; + for (Type? curType = type; curType != null; curType = curType.BaseType) + { + PropertyInfo? propertyInfo = type.GetProperty(name, bindingFlags); + if (propertyInfo != null) + { + type = curType; + return propertyInfo; + } + } + + return null; }); return property != null @@ -177,18 +200,25 @@ namespace StardewModdingAPI.Framework.Reflection /// Get a method from the type hierarchy. /// The type which has the method. - /// The object which has the method. + /// The object which has the method, or null for a static method. /// The method name. /// The reflection binding which flags which indicates what type of method to find. - private IReflectedMethod GetMethodFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags) + private IReflectedMethod? GetMethodFromHierarchy(Type type, object? obj, string name, BindingFlags bindingFlags) { bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); - MethodInfo method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}", () => + MethodInfo? method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}", () => { - MethodInfo methodInfo = null; - for (; type != null && methodInfo == null; type = type.BaseType) - methodInfo = type.GetMethod(name, bindingFlags); - return methodInfo; + for (Type? curType = type; curType != null; curType = curType.BaseType) + { + MethodInfo? methodInfo = type.GetMethod(name, bindingFlags); + if (methodInfo != null) + { + type = curType; + return methodInfo; + } + } + + return null; }); return method != null @@ -200,7 +230,8 @@ namespace StardewModdingAPI.Framework.Reflection /// The expected type. /// The cache key. /// Fetches a new value to cache. - private TMemberInfo GetCached(string key, Func fetch) where TMemberInfo : MemberInfo + private TMemberInfo? GetCached(string key, Func fetch) + where TMemberInfo : MemberInfo { // get from cache if (this.Cache.Contains(key)) @@ -212,8 +243,8 @@ namespace StardewModdingAPI.Framework.Reflection } // fetch & cache new value - TMemberInfo result = fetch(); - CacheEntry cacheEntry = new(result != null, result); + TMemberInfo? result = fetch(); + CacheEntry cacheEntry = new(result); this.Cache.Add(key, cacheEntry, new CacheItemPolicy { SlidingExpiration = this.SlidingCacheExpiry }); return result; } diff --git a/src/SMAPI/Framework/SCore.cs b/src/SMAPI/Framework/SCore.cs index 364a7632..bce7cffa 100644 --- a/src/SMAPI/Framework/SCore.cs +++ b/src/SMAPI/Framework/SCore.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Concurrent; using System.Collections.Generic; @@ -92,13 +90,13 @@ namespace StardewModdingAPI.Framework private readonly CommandManager CommandManager; /// The underlying game instance. - private SGameRunner Game; + private SGameRunner Game = null!; // initialized very early /// SMAPI's content manager. - private ContentCoordinator ContentCore; + private ContentCoordinator ContentCore = null!; // initialized very early /// The game's core multiplayer utility for the main player. - private SMultiplayer Multiplayer; + private SMultiplayer Multiplayer = null!; // initialized very early /// Tracks the installed mods. /// This is initialized after the game starts. @@ -146,19 +144,18 @@ namespace StardewModdingAPI.Framework private readonly ConcurrentQueue RawCommandQueue = new(); /// A list of commands to execute on each screen. - private readonly PerScreen>> ScreenCommandQueue = new(() => new List>()); - + private readonly PerScreen> ScreenCommandQueue = new(() => new List()); /********* ** Accessors *********/ /// Manages deprecation warnings. /// This is initialized after the game starts. This is accessed directly because it's not part of the normal class model. - internal static DeprecationManager DeprecationManager { get; private set; } + internal static DeprecationManager DeprecationManager { get; private set; } = null!; // initialized in constructor, which happens before other code can access it /// The singleton instance. /// This is only intended for use by external code like the Error Handler mod. - internal static SCore Instance { get; private set; } + internal static SCore Instance { get; private set; } = null!; // initialized in constructor, which happens before other code can access it /// The number of game update ticks which have already executed. This is similar to , but incremented more consistently for every tick. internal static uint TicksElapsed { get; private set; } @@ -191,7 +188,8 @@ namespace StardewModdingAPI.Framework this.Settings = JsonConvert.DeserializeObject(File.ReadAllText(Constants.ApiConfigPath)); if (File.Exists(Constants.ApiUserConfigPath)) JsonConvert.PopulateObject(File.ReadAllText(Constants.ApiUserConfigPath), this.Settings); - this.Settings.DeveloperMode = developerMode ?? this.Settings.DeveloperMode; + if (developerMode.HasValue) + this.Settings.OverrideDeveloperMode(developerMode.Value); this.LogManager = new LogManager(logPath: logPath, colorConfig: this.Settings.ConsoleColors, writeToConsole: writeToConsole, isVerbose: this.Settings.VerboseLogging, isDeveloperMode: this.Settings.DeveloperMode, getScreenIdForLog: this.GetScreenIdForLog); this.CommandManager = new CommandManager(this.Monitor); @@ -331,6 +329,7 @@ namespace StardewModdingAPI.Framework } /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + [SuppressMessage("ReSharper", "ConstantConditionalAccessQualifier", Justification = "May be disposed before SMAPI is fully initialized.")] public void Dispose() { // skip if already disposed @@ -355,9 +354,9 @@ namespace StardewModdingAPI.Framework // dispose core components this.IsGameRunning = false; this.ContentCore?.Dispose(); - this.CancellationToken?.Dispose(); + this.CancellationToken.Dispose(); this.Game?.Dispose(); - this.LogManager?.Dispose(); // dispose last to allow for any last-second log messages + this.LogManager.Dispose(); // dispose last to allow for any last-second log messages // end game (moved from Game1.OnExiting to let us clean up first) Process.GetCurrentProcess().Kill(); @@ -517,12 +516,12 @@ namespace StardewModdingAPI.Framework /********* ** Parse commands *********/ - while (this.RawCommandQueue.TryDequeue(out string rawInput)) + while (this.RawCommandQueue.TryDequeue(out string? rawInput)) { // parse command - string name; - string[] args; - Command command; + string? name; + string[]? args; + Command? command; int screenId; try { @@ -539,7 +538,7 @@ namespace StardewModdingAPI.Framework } // queue command for screen - this.ScreenCommandQueue.GetValueForScreen(screenId).Add(Tuple.Create(command, name, args)); + this.ScreenCommandQueue.GetValueForScreen(screenId).Add(new(command, name, args)); } @@ -556,7 +555,7 @@ namespace StardewModdingAPI.Framework catch (Exception ex) { // log error - this.Monitor.Log($"An error occured in the overridden update loop: {ex.GetLogSummary()}", LogLevel.Error); + this.Monitor.Log($"An error occurred in the overridden update loop: {ex.GetLogSummary()}", LogLevel.Error); // exit if irrecoverable if (!this.UpdateCrashTimer.Decrement()) @@ -575,7 +574,7 @@ namespace StardewModdingAPI.Framework /// Invoke the game's update logic. private void OnPlayerInstanceUpdating(SGame instance, GameTime gameTime, Action runUpdate) { - var events = this.EventManager; + EventManager events = this.EventManager; try { @@ -595,12 +594,8 @@ namespace StardewModdingAPI.Framework *********/ { var commandQueue = this.ScreenCommandQueue.Value; - foreach (var entry in commandQueue) + foreach ((Command? command, string? name, string[]? args) in commandQueue) { - Command command = entry.Item1; - string name = entry.Item2; - string[] args = entry.Item3; - try { command.Callback.Invoke(name, args); @@ -637,6 +632,7 @@ namespace StardewModdingAPI.Framework { this.Monitor.Log("Game loader synchronizing..."); this.Reflection.GetMethod(Game1.game1, "UpdateTitleScreen").Invoke(Game1.currentGameTime); // run game logic to change music on load, etc + // ReSharper disable once ConstantConditionalAccessQualifier -- may become null within the loop while (Game1.currentLoader?.MoveNext() == true) { SCore.ProcessTicksElapsed++; @@ -825,7 +821,7 @@ namespace StardewModdingAPI.Framework // raise cursor moved event if (state.Cursor.IsChanged) - events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old, state.Cursor.New)); + events.CursorMoved.Raise(new CursorMovedEventArgs(state.Cursor.Old!, state.Cursor.New!)); // raise mouse wheel scrolled if (state.MouseWheelScroll.IsChanged) @@ -956,7 +952,7 @@ namespace StardewModdingAPI.Framework // raise player events if (raiseWorldEvents) { - PlayerSnapshot playerState = state.CurrentPlayer; + PlayerSnapshot playerState = state.CurrentPlayer!; // not null at this point Farmer player = playerState.Player; // raise current location changed @@ -965,25 +961,25 @@ namespace StardewModdingAPI.Framework if (this.Monitor.IsVerbose) this.Monitor.Log($"Context: set location to {playerState.Location.New}."); - events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old, playerState.Location.New)); + events.Warped.Raise(new WarpedEventArgs(player, playerState.Location.Old!, playerState.Location.New!)); } // raise player leveled up a skill - foreach (var pair in playerState.Skills) + foreach ((SkillType skill, var value) in playerState.Skills) { - if (!pair.Value.IsChanged) + if (!value.IsChanged) continue; if (this.Monitor.IsVerbose) - this.Monitor.Log($"Events: player skill '{pair.Key}' changed from {pair.Value.Old} to {pair.Value.New}."); + this.Monitor.Log($"Events: player skill '{skill}' changed from {value.Old} to {value.New}."); - events.LevelChanged.Raise(new LevelChangedEventArgs(player, pair.Key, pair.Value.Old, pair.Value.New)); + events.LevelChanged.Raise(new LevelChangedEventArgs(player, skill, value.Old, value.New)); } // raise player inventory changed if (playerState.Inventory.IsChanged) { - var inventory = playerState.Inventory; + SnapshotItemListDiff inventory = playerState.Inventory; if (this.Monitor.IsVerbose) this.Monitor.Log("Events: player inventory changed."); @@ -1070,7 +1066,8 @@ namespace StardewModdingAPI.Framework // update mod translation helpers foreach (IModMetadata mod in this.ModRegistry.GetAll()) { - mod.Translations.SetLocale(locale, languageCode); + TranslationHelper translations = mod.Translations!; // not null at this point + translations.SetLocale(locale, languageCode); foreach (ContentPack contentPack in mod.GetFakeContentPacks()) contentPack.TranslationImpl.SetLocale(locale, languageCode); @@ -1117,7 +1114,7 @@ namespace StardewModdingAPI.Framework break; case LoadStage.Loaded: - // override chatbox + // override chat box Game1.onScreenMenus.Remove(Game1.chatBox); Game1.onScreenMenus.Add(Game1.chatBox = new SChatBox(this.LogManager.MonitorForGame)); break; @@ -1182,7 +1179,7 @@ namespace StardewModdingAPI.Framework /// The content pack ID. /// The verb phrase indicating what action will be performed, like 'load assets' or 'edit assets'. /// Returns the content pack metadata if valid, else null. - private IModMetadata GetOnBehalfOfContentPack(IModMetadata mod, string id, string verb) + private IModMetadata? GetOnBehalfOfContentPack(IModMetadata mod, string? id, string verb) { if (id == null) return null; @@ -1190,7 +1187,7 @@ namespace StardewModdingAPI.Framework string errorPrefix = $"Can't {verb} on behalf of content pack ID '{id}'"; // get target mod - IModMetadata onBehalfOf = this.ModRegistry.Get(id); + IModMetadata? onBehalfOf = this.ModRegistry.Get(id); if (onBehalfOf == null) { mod.LogAsModOnce($"{errorPrefix}: there's no content pack installed with that ID.", LogLevel.Warn); @@ -1198,7 +1195,7 @@ namespace StardewModdingAPI.Framework } // make sure it's a content pack for the requesting mod - if (!onBehalfOf.IsContentPack || !string.Equals(onBehalfOf.Manifest?.ContentPackFor?.UniqueID, mod.Manifest.UniqueID)) + if (!onBehalfOf.IsContentPack || !string.Equals(onBehalfOf.Manifest.ContentPackFor?.UniqueID, mod.Manifest.UniqueID)) { mod.LogAsModOnce($"{errorPrefix}: that isn't a content pack for this mod.", LogLevel.Warn); return null; @@ -1232,7 +1229,7 @@ namespace StardewModdingAPI.Framework modIDs.Remove(message.FromModID); // don't send a broadcast back to the sender // raise events - this.EventManager.ModMessageReceived.Raise(new ModMessageReceivedEventArgs(message, this.Toolkit.JsonHelper), mod => mod != null && modIDs.Contains(mod.Manifest.UniqueID)); + this.EventManager.ModMessageReceived.Raise(new ModMessageReceivedEventArgs(message, this.Toolkit.JsonHelper), mod => modIDs.Contains(mod.Manifest.UniqueID)); } /// Constructor a content manager to read game content files. @@ -1241,6 +1238,7 @@ namespace StardewModdingAPI.Framework private LocalizedContentManager CreateContentManager(IServiceProvider serviceProvider, string rootDirectory) { // Game1._temporaryContent initializing from SGame constructor + // ReSharper disable once ConditionIsAlwaysTrueOrFalse -- this is the method that initializes it if (this.ContentCore == null) { this.ContentCore = new ContentCoordinator( @@ -1293,21 +1291,21 @@ namespace StardewModdingAPI.Framework // detect issues bool hasObjectIssues = false; void LogIssue(int id, string issue) => this.Monitor.Log($@"Detected issue: item #{id} in Content\Data\ObjectInformation.xnb is invalid ({issue})."); - foreach (KeyValuePair entry in Game1.objectInformation) + foreach ((int id, string? fieldsStr) in Game1.objectInformation) { // must not be empty - if (string.IsNullOrWhiteSpace(entry.Value)) + if (string.IsNullOrWhiteSpace(fieldsStr)) { - LogIssue(entry.Key, "entry is empty"); + LogIssue(id, "entry is empty"); hasObjectIssues = true; continue; } // require core fields - string[] fields = entry.Value.Split('/'); + string[] fields = fieldsStr.Split('/'); if (fields.Length < SObject.objectInfoDescriptionIndex + 1) { - LogIssue(entry.Key, "too few fields for an object"); + LogIssue(id, "too few fields for an object"); hasObjectIssues = true; continue; } @@ -1318,7 +1316,7 @@ namespace StardewModdingAPI.Framework case "Cooking": if (fields.Length < SObject.objectInfoBuffDurationIndex + 1) { - LogIssue(entry.Key, "too few fields for a cooking item"); + LogIssue(id, "too few fields for a cooking item"); hasObjectIssues = true; } break; @@ -1366,7 +1364,7 @@ namespace StardewModdingAPI.Framework string[] installedNames = registryKeys .SelectMany(registryKey => { - using RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey); + using RegistryKey? key = Registry.LocalMachine.OpenSubKey(registryKey); if (key == null) return Array.Empty(); @@ -1374,9 +1372,9 @@ namespace StardewModdingAPI.Framework .GetSubKeyNames() .Select(subkeyName => { - using RegistryKey subkey = key.OpenSubKey(subkeyName); - string displayName = (string)subkey?.GetValue("DisplayName"); - string displayVersion = (string)subkey?.GetValue("DisplayVersion"); + using RegistryKey? subkey = key.OpenSubKey(subkeyName); + string? displayName = (string?)subkey?.GetValue("DisplayName"); + string? displayVersion = (string?)subkey?.GetValue("DisplayVersion"); if (displayName != null && displayVersion != null && displayName.EndsWith($" {displayVersion}")) displayName = displayName.Substring(0, displayName.Length - displayVersion.Length - 1); @@ -1386,6 +1384,7 @@ namespace StardewModdingAPI.Framework .ToArray(); }) .Where(name => name != null && (name.Contains("MSI Afterburner") || name.Contains("RivaTuner"))) + .Select(name => name!) .Distinct() .OrderBy(name => name) .ToArray(); @@ -1418,14 +1417,14 @@ namespace StardewModdingAPI.Framework // check SMAPI version { - ISemanticVersion updateFound = null; - string updateUrl = null; + ISemanticVersion? updateFound = null; + string? updateUrl = null; try { // fetch update check ModEntryModel response = client.GetModInfo(new[] { new ModSearchEntryModel("Pathoschild.SMAPI", Constants.ApiVersion, new[] { $"GitHub:{this.Settings.GitHubProjectName}" }) }, apiVersion: Constants.ApiVersion, gameVersion: Constants.GameVersion, platform: Constants.Platform).Single().Value; updateFound = response.SuggestedUpdate?.Version; - updateUrl = response.SuggestedUpdate?.Url ?? Constants.HomePageUrl; + updateUrl = response.SuggestedUpdate?.Url; // log message if (updateFound != null) @@ -1451,7 +1450,7 @@ namespace StardewModdingAPI.Framework // show update message on next launch if (updateFound != null) - this.LogManager.WriteUpdateMarker(updateFound.ToString(), updateUrl); + this.LogManager.WriteUpdateMarker(updateFound.ToString(), updateUrl ?? Constants.HomePageUrl); } // check mod versions @@ -1485,12 +1484,12 @@ namespace StardewModdingAPI.Framework foreach (IModMetadata mod in mods.OrderBy(p => p.DisplayName)) { // link to update-check data - if (!mod.HasID() || !results.TryGetValue(mod.Manifest.UniqueID, out ModEntryModel result)) + if (!mod.HasID() || !results.TryGetValue(mod.Manifest.UniqueID, out ModEntryModel? result)) continue; mod.SetUpdateData(result); // handle errors - if (result.Errors != null && result.Errors.Any()) + if (result.Errors.Any()) { errors.AppendLine(result.Errors.Length == 1 ? $" {mod.DisplayName}: {result.Errors[0]}" @@ -1512,13 +1511,8 @@ namespace StardewModdingAPI.Framework { this.Monitor.Newline(); this.Monitor.Log($"You can update {updates.Count} mod{(updates.Count != 1 ? "s" : "")}:", LogLevel.Alert); - foreach (var entry in updates) - { - IModMetadata mod = entry.Item1; - ISemanticVersion newVersion = entry.Item2; - string newUrl = entry.Item3; + foreach ((IModMetadata mod, ISemanticVersion newVersion, string newUrl) in updates) this.Monitor.Log($" {mod.DisplayName} {newVersion}: {newUrl}", LogLevel.Alert); - } } else this.Monitor.Log(" All mods up to date."); @@ -1571,9 +1565,8 @@ namespace StardewModdingAPI.Framework // load mods foreach (IModMetadata mod in mods) { - if (!this.TryLoadMod(mod, mods, modAssemblyLoader, proxyFactory, jsonHelper, contentCore, modDatabase, suppressUpdateChecks, out ModFailReason? failReason, out string errorPhrase, out string errorDetails)) + if (!this.TryLoadMod(mod, mods, modAssemblyLoader, proxyFactory, jsonHelper, contentCore, modDatabase, suppressUpdateChecks, out ModFailReason? failReason, out string? errorPhrase, out string? errorDetails)) { - failReason ??= ModFailReason.LoadFailed; mod.SetStatus(ModMetadataStatus.Failed, failReason.Value, errorPhrase, errorDetails); skippedMods.Add(mod); } @@ -1599,7 +1592,7 @@ namespace StardewModdingAPI.Framework foreach (IModMetadata metadata in loadedMods) { // add interceptors - if (metadata.Mod.Helper is ModHelper helper) + if (metadata.Mod?.Helper is ModHelper helper) { // ReSharper disable SuspiciousTypeConversion.Global if (metadata.Mod is IAssetEditor editor) @@ -1636,8 +1629,8 @@ namespace StardewModdingAPI.Framework // call entry method try { - IMod mod = metadata.Mod; - mod.Entry(mod.Helper); + IMod mod = metadata.Mod!; + mod.Entry(mod.Helper!); } catch (Exception ex) { @@ -1647,7 +1640,7 @@ namespace StardewModdingAPI.Framework // get mod API try { - object api = metadata.Mod.GetApi(); + object? api = metadata.Mod!.GetApi(); if (api != null && !api.GetType().IsPublic) { api = null; @@ -1676,7 +1669,8 @@ namespace StardewModdingAPI.Framework /// The interceptors that were added. /// The interceptors that were removed. /// A list of interceptors to update for the change. - private void OnAssetInterceptorsChanged(IModMetadata mod, IEnumerable added, IEnumerable removed, IList> list) + private void OnAssetInterceptorsChanged(IModMetadata mod, IEnumerable? added, IEnumerable? removed, IList> list) + where T : notnull { foreach (T interceptor in added ?? Array.Empty()) { @@ -1705,7 +1699,7 @@ namespace StardewModdingAPI.Framework /// The user-facing reason phrase explaining why the mod couldn't be loaded (if applicable). /// More detailed details about the error intended for developers (if any). /// Returns whether the mod was successfully loaded. - private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader assemblyLoader, InterfaceProxyFactory proxyFactory, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase, HashSet suppressUpdateChecks, out ModFailReason? failReason, out string errorReasonPhrase, out string errorDetails) + private bool TryLoadMod(IModMetadata mod, IModMetadata[] mods, AssemblyLoader assemblyLoader, InterfaceProxyFactory proxyFactory, JsonHelper jsonHelper, ContentCoordinator contentCore, ModDatabase modDatabase, HashSet suppressUpdateChecks, [NotNullWhen(false)] out ModFailReason? failReason, out string? errorReasonPhrase, out string? errorDetails) { errorDetails = null; @@ -1714,6 +1708,7 @@ namespace StardewModdingAPI.Framework string relativePath = mod.GetRelativePathWithRoot(); if (mod.IsContentPack) this.Monitor.Log($" {mod.DisplayName} (from {relativePath}) [content pack]..."); + // ReSharper disable once ConstantConditionalAccessQualifier -- mod may be invalid at this point else if (mod.Manifest?.EntryDll != null) this.Monitor.Log($" {mod.DisplayName} (from {relativePath}{Path.DirectorySeparatorChar}{mod.Manifest.EntryDll})..."); // don't use Path.Combine here, since EntryDLL might not be valid else @@ -1721,21 +1716,22 @@ namespace StardewModdingAPI.Framework } // add warning for missing update key - if (mod.HasID() && !suppressUpdateChecks.Contains(mod.Manifest.UniqueID) && !mod.HasValidUpdateKeys()) + if (mod.HasID() && !suppressUpdateChecks.Contains(mod.Manifest!.UniqueID) && !mod.HasValidUpdateKeys()) mod.SetWarning(ModWarning.NoUpdateKeys); // validate status if (mod.Status == ModMetadataStatus.Failed) { this.Monitor.Log($" Failed: {mod.ErrorDetails ?? mod.Error}"); - failReason = mod.FailReason; + failReason = mod.FailReason ?? ModFailReason.LoadFailed; errorReasonPhrase = mod.Error; return false; } + IManifest manifest = mod.Manifest!; // validate dependencies // Although dependencies are validated before mods are loaded, a dependency may have failed to load. - foreach (IManifestDependency dependency in mod.Manifest.Dependencies.Where(p => p.IsRequired)) + foreach (IManifestDependency dependency in manifest.Dependencies.Where(p => p.IsRequired)) { if (this.ModRegistry.Get(dependency.UniqueID) == null) { @@ -1751,7 +1747,6 @@ namespace StardewModdingAPI.Framework // load as content pack if (mod.IsContentPack) { - IManifest manifest = mod.Manifest; IMonitor monitor = this.LogManager.GetMonitor(mod.DisplayName); CaseInsensitivePathCache relativePathCache = this.ContentCore.GetCaseInsensitivePathCache(mod.DirectoryPath); GameContentHelper gameContentHelper = new(this.ContentCore, manifest.UniqueID, mod.DisplayName, monitor, this.Reflection); @@ -1770,8 +1765,7 @@ namespace StardewModdingAPI.Framework else { // get mod info - IManifest manifest = mod.Manifest; - string assemblyPath = Path.Combine(mod.DirectoryPath, manifest.EntryDll); + string assemblyPath = Path.Combine(mod.DirectoryPath, manifest.EntryDll!); // load mod Assembly modAssembly; @@ -1782,7 +1776,7 @@ namespace StardewModdingAPI.Framework } catch (IncompatibleInstructionException) // details already in trace logs { - string[] updateUrls = new[] { modDatabase.GetModPageUrlFor(manifest.UniqueID), "https://smapi.io/mods" }.Where(p => p != null).ToArray(); + string[] updateUrls = new[] { modDatabase.GetModPageUrlFor(manifest.UniqueID), "https://smapi.io/mods" }.Where(p => p != null).ToArray()!; errorReasonPhrase = $"it's no longer compatible. Please check for a new version at {string.Join(" or ", updateUrls)}"; failReason = ModFailReason.Incompatible; return false; @@ -1808,7 +1802,7 @@ namespace StardewModdingAPI.Framework try { // get mod instance - if (!this.TryLoadModEntry(modAssembly, out Mod modEntry, out errorReasonPhrase)) + if (!this.TryLoadModEntry(modAssembly, out Mod? modEntry, out errorReasonPhrase)) { failReason = ModFailReason.LoadFailed; return false; @@ -1822,8 +1816,8 @@ namespace StardewModdingAPI.Framework return this.ModRegistry .GetAll(assemblyMods: false) - .Where(p => p.IsContentPack && mod.HasID(p.Manifest.ContentPackFor.UniqueID)) - .Select(p => p.ContentPack) + .Where(p => p.IsContentPack && mod.HasID(p.Manifest.ContentPackFor!.UniqueID)) + .Select(p => p.ContentPack!) .ToArray(); } @@ -1890,7 +1884,7 @@ namespace StardewModdingAPI.Framework /// The loaded instance. /// The error indicating why loading failed (if applicable). /// Returns whether the mod entry class was successfully loaded. - private bool TryLoadModEntry(Assembly modAssembly, out Mod mod, out string error) + private bool TryLoadModEntry(Assembly modAssembly, [NotNullWhen(true)] out Mod? mod, [NotNullWhen(false)] out string? error) { mod = null; @@ -1908,7 +1902,7 @@ namespace StardewModdingAPI.Framework } // get implementation - mod = (Mod)modAssembly.CreateInstance(modEntries[0].ToString()); + mod = (Mod?)modAssembly.CreateInstance(modEntries[0].ToString()); if (mod == null) { error = "its entry class couldn't be instantiated."; @@ -1954,7 +1948,7 @@ namespace StardewModdingAPI.Framework metadata.LogAsMod($" - {error}", LogLevel.Warn); } - metadata.Translations.SetTranslations(translations); + metadata.Translations!.SetTranslations(translations); } // fake content packs @@ -1997,7 +1991,7 @@ namespace StardewModdingAPI.Framework string locale = Path.GetFileNameWithoutExtension(file.Name.ToLower().Trim()); try { - if (!jsonHelper.ReadJsonFileIfExists(file.FullName, out IDictionary data) || data == null) + if (!jsonHelper.ReadJsonFileIfExists(file.FullName, out IDictionary? data)) { errors.Add($"{file.Name} file couldn't be read"); // mainly happens when the file is corrupted or empty continue; @@ -2016,8 +2010,8 @@ namespace StardewModdingAPI.Framework foreach (string locale in translations.Keys.ToArray()) { // handle duplicates - HashSet keys = new HashSet(StringComparer.OrdinalIgnoreCase); - HashSet duplicateKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + HashSet keys = new(StringComparer.OrdinalIgnoreCase); + HashSet duplicateKeys = new(StringComparer.OrdinalIgnoreCase); foreach (string key in translations[locale].Keys.ToArray()) { if (!keys.Add(key)) @@ -2107,5 +2101,15 @@ namespace StardewModdingAPI.Framework return null; } + + + /********* + ** Private types + *********/ + /// A queued console command to run during the update loop. + /// The command which can handle the input. + /// The parsed command name. + /// The parsed command arguments. + private readonly record struct QueuedCommand(Command Command, string Name, string[] Args); } } diff --git a/src/SMAPI/Framework/SMultiplayer.cs b/src/SMAPI/Framework/SMultiplayer.cs index de3c25a5..c0e8ee81 100644 --- a/src/SMAPI/Framework/SMultiplayer.cs +++ b/src/SMAPI/Framework/SMultiplayer.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.IO; @@ -61,7 +59,7 @@ namespace StardewModdingAPI.Framework private readonly PerScreen> PeersImpl = new(() => new Dictionary()); /// The backing field for . - private readonly PerScreen HostPeerImpl = new(); + private readonly PerScreen HostPeerImpl = new(); /********* @@ -71,7 +69,7 @@ namespace StardewModdingAPI.Framework public IDictionary Peers => this.PeersImpl.Value; /// The metadata for the host player, if the current player is a farmhand. - public MultiplayerPeer HostPeer + public MultiplayerPeer? HostPeer { get => this.HostPeerImpl.Value; private set => this.HostPeerImpl.Value = value; @@ -115,13 +113,13 @@ namespace StardewModdingAPI.Framework { case LidgrenClient: { - string address = this.Reflection.GetField(client, "address").GetValue(); + string address = this.Reflection.GetField(client, "address").GetValue() ?? throw new InvalidOperationException("Can't initialize base networking client: no valid address found."); return new SLidgrenClient(address, this.OnClientProcessingMessage, this.OnClientSendingMessage); } case GalaxyNetClient: { - GalaxyID address = this.Reflection.GetField(client, "lobbyId").GetValue(); + GalaxyID address = this.Reflection.GetField(client, "lobbyId").GetValue() ?? throw new InvalidOperationException("Can't initialize GOG networking client: no valid address found."); return new SGalaxyNetClient(address, this.OnClientProcessingMessage, this.OnClientSendingMessage); } @@ -139,13 +137,13 @@ namespace StardewModdingAPI.Framework { case LidgrenServer: { - IGameServer gameServer = this.Reflection.GetField(server, "gameServer").GetValue(); + IGameServer gameServer = this.Reflection.GetField(server, "gameServer").GetValue() ?? throw new InvalidOperationException("Can't initialize base networking client: the required 'gameServer' field wasn't found."); return new SLidgrenServer(gameServer, this, this.OnServerProcessingMessage); } case GalaxyNetServer: { - IGameServer gameServer = this.Reflection.GetField(server, "gameServer").GetValue(); + IGameServer gameServer = this.Reflection.GetField(server, "gameServer").GetValue() ?? throw new InvalidOperationException("Can't initialize GOG networking client: the required 'gameServer' field wasn't found."); return new SGalaxyNetServer(gameServer, this, this.OnServerProcessingMessage); } @@ -194,7 +192,7 @@ namespace StardewModdingAPI.Framework case (byte)MessageType.ModContext: { // parse message - RemoteContextModel model = this.ReadContext(message.Reader); + RemoteContextModel? model = this.ReadContext(message.Reader); this.Monitor.Log($"Received context for farmhand {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}."); // store peer @@ -290,7 +288,7 @@ namespace StardewModdingAPI.Framework case (byte)MessageType.ModContext: { // parse message - RemoteContextModel model = this.ReadContext(message.Reader); + RemoteContextModel? model = this.ReadContext(message.Reader); this.Monitor.Log($"Received context for {(model?.IsHost == true ? "host" : "farmhand")} {message.FarmerID} running {(model != null ? $"SMAPI {model.ApiVersion} with {model.Mods.Length} mods" : "vanilla")}."); // store peer @@ -334,7 +332,7 @@ namespace StardewModdingAPI.Framework case (byte)MessageType.PlayerIntroduction: { // store peer - if (!this.Peers.TryGetValue(message.FarmerID, out MultiplayerPeer peer)) + if (!this.Peers.TryGetValue(message.FarmerID, out MultiplayerPeer? peer)) { peer = new MultiplayerPeer( playerID: message.FarmerID, @@ -367,7 +365,7 @@ namespace StardewModdingAPI.Framework { foreach (long playerID in this.disconnectingFarmers) { - if (this.Peers.TryGetValue(playerID, out MultiplayerPeer peer)) + if (this.Peers.TryGetValue(playerID, out MultiplayerPeer? peer)) { this.Monitor.Log($"Player quit: {playerID}"); this.Peers.Remove(playerID); @@ -384,7 +382,7 @@ namespace StardewModdingAPI.Framework /// The unique ID of the mod sending the message. /// The mod IDs which should receive the message on the destination computers, or null for all mods. Specifying mod IDs is recommended to improve performance, unless it's a general-purpose broadcast. /// The values for the players who should receive the message, or null for all players. If you don't need to broadcast to all players, specifying player IDs is recommended to reduce latency. - public void BroadcastModMessage(TMessage message, string messageType, string fromModID, string[] toModIDs, long[] toPlayerIDs) + public void BroadcastModMessage(TMessage message, string messageType, string fromModID, string[]? toModIDs, long[]? toPlayerIDs) { // validate input if (message == null) @@ -488,13 +486,13 @@ namespace StardewModdingAPI.Framework /// Read the metadata context for a player. /// The stream reader. - private RemoteContextModel ReadContext(BinaryReader reader) + private RemoteContextModel? ReadContext(BinaryReader reader) { string data = reader.ReadString(); RemoteContextModel model = this.JsonHelper.Deserialize(data); return model.ApiVersion != null ? model - : null; // no data available for unmodded players + : null; // no data available for vanilla players } /// Receive a mod message sent from another player's mods. @@ -515,12 +513,15 @@ namespace StardewModdingAPI.Framework // forward to other players if (Context.IsMainPlayer && playerIDs.Any(p => p != Game1.player.UniqueMultiplayerID)) { - ModMessageModel newModel = new(model); foreach (long playerID in playerIDs) { - if (playerID != Game1.player.UniqueMultiplayerID && playerID != model.FromPlayerID && this.Peers.TryGetValue(playerID, out MultiplayerPeer peer)) + if (playerID != Game1.player.UniqueMultiplayerID && playerID != model.FromPlayerID && this.Peers.TryGetValue(playerID, out MultiplayerPeer? peer)) { - newModel.ToPlayerIDs = new[] { peer.PlayerID }; + ModMessageModel newModel = new(model) + { + ToPlayerIDs = new[] { peer.PlayerID } + }; + this.Monitor.VerboseLog($" Forwarding message to player {peer.PlayerID}."); peer.SendMessage(new OutgoingMessage((byte)MessageType.ModMessage, peer.PlayerID, this.JsonHelper.Serialize(newModel, Formatting.None))); } @@ -546,22 +547,20 @@ namespace StardewModdingAPI.Framework /// Get the fields to include in a context sync message sent to other players. private object[] GetContextSyncMessageFields() { - RemoteContextModel model = new() - { - IsHost = Context.IsWorldReady && Context.IsMainPlayer, - Platform = Constants.TargetPlatform, - ApiVersion = Constants.ApiVersion, - GameVersion = Constants.GameVersion, - Mods = this.ModRegistry + RemoteContextModel model = new( + isHost: Context.IsWorldReady && Context.IsMainPlayer, + platform: Constants.TargetPlatform, + apiVersion: Constants.ApiVersion, + gameVersion: Constants.GameVersion, + mods: this.ModRegistry .GetAll() - .Select(mod => new RemoteContextModModel - { - ID = mod.Manifest.UniqueID, - Name = mod.Manifest.Name, - Version = mod.Manifest.Version - }) + .Select(mod => new RemoteContextModModel( + id: mod.Manifest.UniqueID, + name: mod.Manifest.Name, + version: mod.Manifest.Version + )) .ToArray() - }; + ); return new object[] { this.JsonHelper.Serialize(model, Formatting.None) }; } @@ -573,21 +572,19 @@ namespace StardewModdingAPI.Framework if (!peer.HasSmapi) return new object[] { "{}" }; - RemoteContextModel model = new() - { - IsHost = peer.IsHost, - Platform = peer.Platform.Value, - ApiVersion = peer.ApiVersion, - GameVersion = peer.GameVersion, - Mods = peer.Mods - .Select(mod => new RemoteContextModModel - { - ID = mod.ID, - Name = mod.Name, - Version = mod.Version - }) + RemoteContextModel model = new( + isHost: peer.IsHost, + platform: peer.Platform.Value, + apiVersion: peer.ApiVersion, + gameVersion: peer.GameVersion, + mods: peer.Mods + .Select(mod => new RemoteContextModModel( + id: mod.ID, + name: mod.Name, + version: mod.Version + )) .ToArray() - }; + ); return new object[] { this.JsonHelper.Serialize(model, Formatting.None) }; } diff --git a/src/SMAPI/Framework/Serialization/KeybindConverter.cs b/src/SMAPI/Framework/Serialization/KeybindConverter.cs index f3bab20d..539f1291 100644 --- a/src/SMAPI/Framework/Serialization/KeybindConverter.cs +++ b/src/SMAPI/Framework/Serialization/KeybindConverter.cs @@ -53,13 +53,13 @@ namespace StardewModdingAPI.Framework.Serialization if (objectType == typeof(Keybind)) { - return Keybind.TryParse(str, out Keybind parsed, out string[] errors) + return Keybind.TryParse(str, out Keybind? parsed, out string[] errors) ? parsed : throw new SParseException($"Can't parse {nameof(Keybind)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}"); } else { - return KeybindList.TryParse(str, out KeybindList parsed, out string[] errors) + return KeybindList.TryParse(str, out KeybindList? parsed, out string[] errors) ? parsed : throw new SParseException($"Can't parse {nameof(KeybindList)} from invalid value '{str}' (path: {path}).\n{string.Join("\n", errors)}"); } diff --git a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableWatcher.cs b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableWatcher.cs index 4f94294c..5f76fe0a 100644 --- a/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableWatcher.cs +++ b/src/SMAPI/Framework/StateTracking/FieldWatchers/ComparableWatcher.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; @@ -42,7 +40,8 @@ namespace StardewModdingAPI.Framework.StateTracking.FieldWatchers { this.GetValue = getValue; this.Comparer = comparer; - this.PreviousValue = getValue(); + this.CurrentValue = getValue(); + this.PreviousValue = this.CurrentValue; } /// Update the current value if needed. diff --git a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs index 367eafea..5433ac8e 100644 --- a/src/SMAPI/Framework/StateTracking/PlayerTracker.cs +++ b/src/SMAPI/Framework/StateTracking/PlayerTracker.cs @@ -1,7 +1,6 @@ -#nullable disable - using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using StardewModdingAPI.Enums; using StardewModdingAPI.Framework.StateTracking.Comparers; @@ -23,7 +22,7 @@ namespace StardewModdingAPI.Framework.StateTracking private IDictionary CurrentInventory; /// The player's last valid location. - private GameLocation LastValidLocation; + private GameLocation? LastValidLocation; /// The underlying watchers. private readonly List Watchers = new(); @@ -36,7 +35,7 @@ namespace StardewModdingAPI.Framework.StateTracking public Farmer Player { get; } /// The player's current location. - public IValueWatcher LocationWatcher { get; } + public IValueWatcher LocationWatcher { get; } /// Tracks changes to the player's skill levels. public IDictionary> SkillWatchers { get; } @@ -51,7 +50,8 @@ namespace StardewModdingAPI.Framework.StateTracking { // init player data this.Player = player; - this.PreviousInventory = this.GetInventory(); + this.CurrentInventory = this.GetInventory(); + this.PreviousInventory = new Dictionary(this.CurrentInventory); // init trackers this.LocationWatcher = WatcherFactory.ForReference(this.GetCurrentLocation); @@ -95,7 +95,7 @@ namespace StardewModdingAPI.Framework.StateTracking /// Get the player's current location, ignoring temporary null values. /// The game will set to null in some cases, e.g. when they're a secondary player in multiplayer and transition to a location that hasn't been synced yet. While that's happening, this returns the player's last valid location instead. - public GameLocation GetCurrentLocation() + public GameLocation? GetCurrentLocation() { return this.Player.currentLocation ?? this.LastValidLocation; } @@ -103,7 +103,7 @@ namespace StardewModdingAPI.Framework.StateTracking /// Get the inventory changes since the last update, if anything changed. /// The inventory changes, or null if nothing changed. /// Returns whether anything changed. - public bool TryGetInventoryChanges(out SnapshotItemListDiff changes) + public bool TryGetInventoryChanges([NotNullWhen(true)] out SnapshotItemListDiff? changes) { IDictionary current = this.GetInventory(); @@ -124,7 +124,7 @@ namespace StardewModdingAPI.Framework.StateTracking public void Dispose() { this.PreviousInventory.Clear(); - this.CurrentInventory?.Clear(); + this.CurrentInventory.Clear(); foreach (IWatcher watcher in this.Watchers) watcher.Dispose(); diff --git a/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs index bf81a35e..6a24ec30 100644 --- a/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs +++ b/src/SMAPI/Framework/StateTracking/Snapshots/PlayerSnapshot.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; @@ -47,17 +45,18 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots public PlayerSnapshot(Farmer player) { this.Player = player; + this.Inventory = this.EmptyItemListDiff; } /// Update the tracked values. /// The player watcher to snapshot. public void Update(PlayerTracker watcher) { - this.Location.Update(watcher.LocationWatcher); - foreach (var pair in this.Skills) - pair.Value.Update(watcher.SkillWatchers[pair.Key]); + this.Location.Update(watcher.LocationWatcher!); + foreach ((SkillType skill, var value) in this.Skills) + value.Update(watcher.SkillWatchers[skill]); - this.Inventory = watcher.TryGetInventoryChanges(out SnapshotItemListDiff itemChanges) + this.Inventory = watcher.TryGetInventoryChanges(out SnapshotItemListDiff? itemChanges) ? itemChanges : this.EmptyItemListDiff; } diff --git a/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs b/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs index 5f0ecfa0..b5fc1f57 100644 --- a/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs +++ b/src/SMAPI/Framework/TemporaryHacks/MiniMonoModHotfix.cs @@ -1,5 +1,3 @@ -#nullable disable - // This temporary utility fixes an esoteric issue in XNA Framework where deserialization depends on // the order of fields returned by Type.GetFields, but that order changes after Harmony/MonoMod use // reflection to access the fields due to an issue in .NET Framework. @@ -7,15 +5,15 @@ // // This will be removed when Harmony/MonoMod are updated to incorporate the fix. // -// Special thanks to 0x0ade for submitting this worokaround! Copy/pasted and adapted from MonoMod. +// Special thanks to 0x0ade for submitting this workaround! Copy/pasted and adapted from MonoMod. using System; -using System.Reflection; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Reflection.Emit; using System.Runtime.CompilerServices; using HarmonyLib; -using System.Reflection.Emit; // ReSharper disable once CheckNamespace -- Temporary hotfix submitted by the MonoMod author. namespace MonoMod.Utils @@ -26,33 +24,33 @@ namespace MonoMod.Utils { // .NET Framework can break member ordering if using Module.Resolve* on certain members. - private static object[] _NoArgs = Array.Empty(); - private static object[] _CacheGetterArgs = { /* MemberListType.All */ 0, /* name apparently always null? */ null }; + private static readonly object[] _NoArgs = Array.Empty(); + private static readonly object?[] _CacheGetterArgs = { /* MemberListType.All */ 0, /* name apparently always null? */ null }; - private static Type t_RuntimeModule = + private static readonly Type? t_RuntimeModule = typeof(Module).Assembly .GetType("System.Reflection.RuntimeModule"); - private static PropertyInfo p_RuntimeModule_RuntimeType = + private static readonly PropertyInfo? p_RuntimeModule_RuntimeType = typeof(Module).Assembly .GetType("System.Reflection.RuntimeModule") ?.GetProperty("RuntimeType", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - private static Type t_RuntimeType = + private static readonly Type? t_RuntimeType = typeof(Type).Assembly .GetType("System.RuntimeType"); - private static PropertyInfo p_RuntimeType_Cache = + private static readonly PropertyInfo? p_RuntimeType_Cache = typeof(Type).Assembly .GetType("System.RuntimeType") ?.GetProperty("Cache", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - private static MethodInfo m_RuntimeTypeCache_GetFieldList = + private static readonly MethodInfo? m_RuntimeTypeCache_GetFieldList = typeof(Type).Assembly .GetType("System.RuntimeType+RuntimeTypeCache") ?.GetMethod("GetFieldList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); - private static MethodInfo m_RuntimeTypeCache_GetPropertyList = + private static readonly MethodInfo? m_RuntimeTypeCache_GetPropertyList = typeof(Type).Assembly .GetType("System.RuntimeType+RuntimeTypeCache") ?.GetMethod("GetPropertyList", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); @@ -65,37 +63,37 @@ namespace MonoMod.Utils harmony.Patch( original: typeof(Harmony).Assembly - .GetType("HarmonyLib.MethodBodyReader") + .GetType("HarmonyLib.MethodBodyReader", throwOnError: true)! .GetMethod("ReadOperand", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance), transpiler: new HarmonyMethod(typeof(MiniMonoModHotfix), nameof(ResolveTokenFix)) ); harmony.Patch( original: typeof(MonoMod.Utils.ReflectionHelper).Assembly - .GetType("MonoMod.Utils.DynamicMethodDefinition+<>c__DisplayClass3_0") + .GetType("MonoMod.Utils.DynamicMethodDefinition+<>c__DisplayClass3_0", throwOnError: true)! .GetMethod("<_CopyMethodToDefinition>g__ResolveTokenAs|1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance), transpiler: new HarmonyMethod(typeof(MiniMonoModHotfix), nameof(ResolveTokenFix)) ); } - private static IEnumerable ResolveTokenFix(IEnumerable instrs) + private static IEnumerable ResolveTokenFix(IEnumerable instructions) { - MethodInfo getdecl = typeof(MiniMonoModHotfix).GetMethod(nameof(GetRealDeclaringType)); - MethodInfo fixup = typeof(MiniMonoModHotfix).GetMethod(nameof(FixReflectionCache)); + MethodInfo getRealDeclaringType = typeof(MiniMonoModHotfix).GetMethod(nameof(MiniMonoModHotfix.GetRealDeclaringType)) ?? throw new InvalidOperationException($"Can't get required method {nameof(MiniMonoModHotfix)}.{nameof(GetRealDeclaringType)}"); + MethodInfo fixReflectionCache = typeof(MiniMonoModHotfix).GetMethod(nameof(MiniMonoModHotfix.FixReflectionCache)) ?? throw new InvalidOperationException($"Can't get required method {nameof(MiniMonoModHotfix)}.{nameof(FixReflectionCache)}"); - foreach (CodeInstruction instr in instrs) + foreach (CodeInstruction instruction in instructions) { - yield return instr; + yield return instruction; - if (instr.operand is MethodInfo called) + if (instruction.operand is MethodInfo called) { switch (called.Name) { case "ResolveType": // type.FixReflectionCache(); yield return new CodeInstruction(OpCodes.Dup); - yield return new CodeInstruction(OpCodes.Call, fixup); + yield return new CodeInstruction(OpCodes.Call, fixReflectionCache); break; case "ResolveMember": @@ -103,15 +101,15 @@ namespace MonoMod.Utils case "ResolveField": // member.GetRealDeclaringType().FixReflectionCache(); yield return new CodeInstruction(OpCodes.Dup); - yield return new CodeInstruction(OpCodes.Call, getdecl); - yield return new CodeInstruction(OpCodes.Call, fixup); + yield return new CodeInstruction(OpCodes.Call, getRealDeclaringType); + yield return new CodeInstruction(OpCodes.Call, fixReflectionCache); break; } } } } - public static Type GetModuleType(this Module module) + public static Type? GetModuleType(this Module? module) { // Sadly we can't blindly resolve type 0x02000001 as the runtime throws ArgumentException. @@ -120,22 +118,21 @@ namespace MonoMod.Utils // .NET if (p_RuntimeModule_RuntimeType != null) - return (Type)p_RuntimeModule_RuntimeType.GetValue(module, _NoArgs); + return (Type?)p_RuntimeModule_RuntimeType.GetValue(module, _NoArgs); // The hotfix doesn't apply to Mono anyway, thus that's not copied over. return null; } - public static Type GetRealDeclaringType(this MemberInfo member) - => member.DeclaringType ?? member.Module.GetModuleType(); + public static Type? GetRealDeclaringType(this MemberInfo member) + { + return member.DeclaringType ?? member.Module.GetModuleType(); + } - public static void FixReflectionCache(this Type type) + public static void FixReflectionCache(this Type? type) { - if (t_RuntimeType == null || - p_RuntimeType_Cache == null || - m_RuntimeTypeCache_GetFieldList == null || - m_RuntimeTypeCache_GetPropertyList == null) + if (t_RuntimeType == null || p_RuntimeType_Cache == null || m_RuntimeTypeCache_GetFieldList == null || m_RuntimeTypeCache_GetPropertyList == null) return; for (; type != null; type = type.DeclaringType) @@ -145,21 +142,17 @@ namespace MonoMod.Utils if (!t_RuntimeType.IsInstanceOfType(type)) continue; - CacheFixEntry entry = _CacheFixed.GetValue(type, rt => { - CacheFixEntry entryNew = new(); - object cache; - Array properties, fields; - + CacheFixEntry entry = _CacheFixed.GetValue(type, rt => + { // All RuntimeTypes MUST have a cache, the getter is non-virtual, it creates on demand and asserts non-null. - entryNew.Cache = cache = p_RuntimeType_Cache.GetValue(rt, _NoArgs); - entryNew.Properties = properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList); - entryNew.Fields = fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList); + object cache = MiniMonoModHotfix.p_RuntimeType_Cache.GetValue(rt, MiniMonoModHotfix._NoArgs)!; + Array properties = MiniMonoModHotfix._GetArray(cache, MiniMonoModHotfix.m_RuntimeTypeCache_GetPropertyList); + Array fields = MiniMonoModHotfix._GetArray(cache, MiniMonoModHotfix.m_RuntimeTypeCache_GetFieldList); _FixReflectionCacheOrder(properties); _FixReflectionCacheOrder(fields); - entryNew.NeedsVerify = false; - return entryNew; + return new CacheFixEntry(cache, properties, fields, needsVerify: false); }); if (entry.NeedsVerify && !_Verify(entry, type)) @@ -177,44 +170,43 @@ namespace MonoMod.Utils private static bool _Verify(CacheFixEntry entry, Type type) { - object cache; - Array properties, fields; - // The cache can sometimes be invalidated. // TODO: Figure out if only the arrays get replaced or if the entire cache object gets replaced! - if (entry.Cache != (cache = p_RuntimeType_Cache.GetValue(type, _NoArgs))) + object cache = p_RuntimeType_Cache!.GetValue(type, _NoArgs)!; + if (entry.Cache != cache) { entry.Cache = cache; - entry.Properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList); - entry.Fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList); + entry.Properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList!); + entry.Fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList!); return false; } - else if (entry.Properties != (properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList))) + + Array properties = _GetArray(cache, m_RuntimeTypeCache_GetPropertyList!); + if (entry.Properties != properties) { entry.Properties = properties; - entry.Fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList); + entry.Fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList!); return false; - } - else if (entry.Fields != (fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList))) + + Array fields = _GetArray(cache, m_RuntimeTypeCache_GetFieldList!); + if (entry.Fields != fields) { entry.Fields = fields; return false; } - else - { - // Cache should still be the same, no re-fix necessary. - return true; - } + + // Cache should still be the same, no re-fix necessary. + return true; } private static Array _GetArray(object cache, MethodInfo getter) { // Get and discard once, otherwise we might not be getting the actual backing array. getter.Invoke(cache, _CacheGetterArgs); - return (Array)getter.Invoke(cache, _CacheGetterArgs); + return (Array)getter.Invoke(cache, _CacheGetterArgs)!; } private static void _FixReflectionCacheOrder(Array orig) where T : MemberInfo @@ -222,7 +214,7 @@ namespace MonoMod.Utils // Sort using a short-lived list. List list = new List(orig.Length); for (int i = 0; i < orig.Length; i++) - list.Add((T)orig.GetValue(i)); + list.Add((T)orig.GetValue(i)!); list.Sort((a, b) => a.MetadataToken - b.MetadataToken); @@ -232,10 +224,18 @@ namespace MonoMod.Utils private class CacheFixEntry { - public object Cache; + public object? Cache; public Array Properties; public Array Fields; public bool NeedsVerify; + + public CacheFixEntry(object? cache, Array properties, Array fields, bool needsVerify) + { + this.Cache = cache; + this.Properties = properties; + this.Fields = fields; + this.NeedsVerify = needsVerify; + } } } } diff --git a/src/SMAPI/Metadata/CoreAssetPropagator.cs b/src/SMAPI/Metadata/CoreAssetPropagator.cs index b7cec72c..f1b9af9a 100644 --- a/src/SMAPI/Metadata/CoreAssetPropagator.cs +++ b/src/SMAPI/Metadata/CoreAssetPropagator.cs @@ -1,5 +1,3 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; @@ -712,7 +710,7 @@ namespace StardewModdingAPI.Metadata bool isPaintMask = assetName.BaseName.EndsWith(paintMaskSuffix, StringComparison.OrdinalIgnoreCase); // get building type - string type = Path.GetFileName(assetName.BaseName)!; + string type = Path.GetFileName(assetName.BaseName); if (isPaintMask) type = type.Substring(0, type.Length - paintMaskSuffix.Length); @@ -749,7 +747,7 @@ namespace StardewModdingAPI.Metadata if (!ignoreWorld) { - foreach (var location in this.GetLocations()) + foreach (GameLocation location in this.GetLocations()) { foreach (MapSeat seat in location.mapSeats.Where(p => p != null)) { @@ -783,7 +781,7 @@ namespace StardewModdingAPI.Metadata // update sprites Texture2D texture = content.Load(assetName.BaseName); - foreach (var entry in critters) + foreach (Critter entry in critters) entry.sprite.spriteTexture = texture; return critters.Length; @@ -799,16 +797,16 @@ namespace StardewModdingAPI.Metadata foreach (GameLocation location in this.GetLocations()) { - IEnumerable doors = location.interiorDoors?.Doors; + IEnumerable? doors = location.interiorDoors?.Doors; if (doors == null) continue; - foreach (InteriorDoor door in doors) + foreach (InteriorDoor? door in doors) { if (door?.Sprite == null) continue; - string curKey = this.Reflection.GetField(door.Sprite, "textureName").GetValue(); + string? curKey = this.Reflection.GetField(door.Sprite, "textureName").GetValue(); if (this.IsSameBaseName(assetName, curKey)) door.Sprite.texture = texture.Value; } @@ -933,7 +931,7 @@ namespace StardewModdingAPI.Metadata // warping onto the wrong tile (or even off-screen) if a patch changes the farmhouse // map on location change. if (playerPos.HasValue) - Game1.player.Position = playerPos.Value; + Game1.player!.Position = playerPos.Value; } /// Reload the disposition data for matching NPCs. @@ -1003,7 +1001,11 @@ namespace StardewModdingAPI.Metadata { GameLocation adventureGuild = Game1.getLocationFromName("AdventureGuild"); if (adventureGuild != null) - characters.Add(new { Npc = this.Reflection.GetField(adventureGuild, "Gil").GetValue(), AssetName = gilKey }); + { + NPC? gil = this.Reflection.GetField(adventureGuild, "Gil").GetValue(); + if (gil != null) + characters.Add(new { Npc = gil, AssetName = gilKey }); + } } } @@ -1029,7 +1031,7 @@ namespace StardewModdingAPI.Metadata foreach (Farmer player in players) { - this.Reflection.GetField>>>(typeof(FarmerRenderer), "_recolorOffsets").GetValue().Remove(player.getTexture()); + this.Reflection.GetField>>>(typeof(FarmerRenderer), "_recolorOffsets").GetValue()?.Remove(player.getTexture()); player.FarmerRenderer.MarkSpriteDirty(); } @@ -1048,11 +1050,12 @@ namespace StardewModdingAPI.Metadata { // get suspension bridges field var field = this.Reflection.GetField>(location, nameof(IslandNorth.suspensionBridges), required: false); + // ReSharper disable once ConditionIsAlwaysTrueOrFalse -- field is nullable when required: false if (field == null || !typeof(IEnumerable).IsAssignableFrom(field.FieldInfo.FieldType)) continue; // update textures - foreach (SuspensionBridge bridge in field.GetValue()) + foreach (SuspensionBridge bridge in field.GetValue()!) this.Reflection.GetField(bridge, "_texture").SetValue(texture.Value); } @@ -1158,7 +1161,7 @@ namespace StardewModdingAPI.Metadata Game1.samBandName = content.LoadString("Strings/StringsFromCSFiles:Game1.cs.2156"); Game1.elliottBookName = content.LoadString("Strings/StringsFromCSFiles:Game1.cs.2157"); - string[] dayNames = this.Reflection.GetField(typeof(Game1), "_shortDayDisplayName").GetValue(); + string[] dayNames = this.Reflection.GetField(typeof(Game1), "_shortDayDisplayName").GetValue()!; dayNames[0] = content.LoadString("Strings/StringsFromCSFiles:Game1.cs.3042"); dayNames[1] = content.LoadString("Strings/StringsFromCSFiles:Game1.cs.3043"); dayNames[2] = content.LoadString("Strings/StringsFromCSFiles:Game1.cs.3044"); @@ -1227,7 +1230,7 @@ namespace StardewModdingAPI.Metadata { foreach (Building building in buildableLocation.buildings) { - GameLocation indoors = building.indoors.Value; + GameLocation? indoors = building.indoors.Value; if (indoors != null) yield return new LocationInfo(indoors, building); } @@ -1238,19 +1241,19 @@ namespace StardewModdingAPI.Metadata /// Get whether two asset names are equivalent if you ignore the locale code. /// The first value to compare. /// The second value to compare. - private bool IsSameBaseName(IAssetName left, string right) + private bool IsSameBaseName(IAssetName? left, string? right) { if (left is null || right is null) return false; - IAssetName parsedB = this.ParseAssetNameOrNull(right); + IAssetName? parsedB = this.ParseAssetNameOrNull(right); return this.IsSameBaseName(left, parsedB); } /// Get whether two asset names are equivalent if you ignore the locale code. /// The first value to compare. /// The second value to compare. - private bool IsSameBaseName(IAssetName left, IAssetName right) + private bool IsSameBaseName(IAssetName? left, IAssetName? right) { if (left is null || right is null) return false; @@ -1260,7 +1263,7 @@ namespace StardewModdingAPI.Metadata /// Normalize an asset key to match the cache key and assert that it's valid, but don't raise an error for null or empty values. /// The asset key to normalize. - private IAssetName ParseAssetNameOrNull(string path) + private IAssetName? ParseAssetNameOrNull(string? path) { if (string.IsNullOrWhiteSpace(path)) return null; @@ -1270,7 +1273,7 @@ namespace StardewModdingAPI.Metadata /// Get the segments in a path (e.g. 'a/b' is 'a' and 'b'). /// The path to check. - private string[] GetSegments(string path) + private string[] GetSegments(string? path) { return path != null ? PathUtilities.GetSegments(path) @@ -1280,7 +1283,7 @@ namespace StardewModdingAPI.Metadata /// Load a texture, and dispose the old one if is enabled and it's different from the new instance. /// The previous texture to dispose. /// The asset key to load. - private Texture2D LoadAndDisposeIfNeeded(Texture2D oldTexture, string key) + private Texture2D LoadAndDisposeIfNeeded(Texture2D? oldTexture, string key) { // if aggressive memory optimizations are enabled, load the asset from the disposable // content manager and dispose the old instance if needed. @@ -1322,7 +1325,7 @@ namespace StardewModdingAPI.Metadata public GameLocation Location { get; } /// The building which contains the location, if any. - public Building ParentBuilding { get; } + public Building? ParentBuilding { get; } /********* @@ -1331,7 +1334,7 @@ namespace StardewModdingAPI.Metadata /// Construct an instance. /// The location instance. /// The building which contains the location, if any. - public LocationInfo(GameLocation location, Building parentBuilding) + public LocationInfo(GameLocation location, Building? parentBuilding) { this.Location = location; this.ParentBuilding = parentBuilding; diff --git a/src/SMAPI/Translation.cs b/src/SMAPI/Translation.cs index 2a0d2ce8..eb608f15 100644 --- a/src/SMAPI/Translation.cs +++ b/src/SMAPI/Translation.cs @@ -96,7 +96,7 @@ namespace StardewModdingAPI { string key = match.Groups[1].Value.Trim(); return tokenLookup.TryGetValue(key, out string? value) - ? value + ? (value ?? "") : match.Value; }); return new Translation(this.Locale, this.Key, text); diff --git a/src/SMAPI/Utilities/KeybindList.cs b/src/SMAPI/Utilities/KeybindList.cs index 18eeb9fd..aa12a37a 100644 --- a/src/SMAPI/Utilities/KeybindList.cs +++ b/src/SMAPI/Utilities/KeybindList.cs @@ -50,7 +50,7 @@ namespace StardewModdingAPI.Utilities /// The keybind string. See remarks on for format details. /// The parsed keybind list, if valid. /// The errors that occurred while parsing the input, if any. - public static bool TryParse(string input, [NotNullWhen(true)] out KeybindList? parsed, out string[] errors) + public static bool TryParse(string? input, [NotNullWhen(true)] out KeybindList? parsed, out string[] errors) { // empty input if (string.IsNullOrWhiteSpace(input)) diff --git a/src/SMAPI/Utilities/PerScreen.cs b/src/SMAPI/Utilities/PerScreen.cs index afe3ba91..799ff63b 100644 --- a/src/SMAPI/Utilities/PerScreen.cs +++ b/src/SMAPI/Utilities/PerScreen.cs @@ -1,8 +1,7 @@ -#nullable disable - using System; using System.Collections.Generic; using System.Linq; +using StardewModdingAPI.Framework; namespace StardewModdingAPI.Utilities { @@ -39,14 +38,28 @@ namespace StardewModdingAPI.Utilities ** Public methods *********/ /// Construct an instance. + /// Limitation with nullable reference types: when the underlying type is nullable, this sets the default value to null regardless of whether you marked the type parameter nullable. To avoid that, set the default value with the 'createNewState' argument instead. public PerScreen() - : this(null) { } + : this(null!) { } /// Construct an instance. /// Create the initial state for a screen. public PerScreen(Func createNewState) { - this.CreateNewState = createNewState ?? (() => default); + // ReSharper disable once ConditionIsAlwaysTrueOrFalse -- required for backwards compatibility + if (createNewState is null) + { + SCore.DeprecationManager.Warn( + SCore.DeprecationManager.GetSourceNameFromStack(), + $"calling the {nameof(PerScreen)} constructor with null", + "3.14.0", + DeprecationLevel.Notice + ); + + createNewState = (() => default!); + } + + this.CreateNewState = createNewState; } /// Get all active values by screen ID. This doesn't initialize the value for a screen ID if it's not created yet. @@ -61,7 +74,7 @@ namespace StardewModdingAPI.Utilities public T GetValueForScreen(int screenId) { this.RemoveDeadScreens(); - return this.States.TryGetValue(screenId, out T state) + return this.States.TryGetValue(screenId, out T? state) ? state : this.States[screenId] = this.CreateNewState(); } -- cgit From 3078ae2a8e10294c86f8702769e15da16511ecde Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 13 Apr 2022 22:17:26 -0400 Subject: fix typos in recent changes (#837) --- src/SMAPI/Framework/Logging/LogManager.cs | 8 ++++---- src/SMAPI/Framework/Reflection/Reflector.cs | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) (limited to 'src/SMAPI/Framework/Logging') diff --git a/src/SMAPI/Framework/Logging/LogManager.cs b/src/SMAPI/Framework/Logging/LogManager.cs index a5989673..b94807b5 100644 --- a/src/SMAPI/Framework/Logging/LogManager.cs +++ b/src/SMAPI/Framework/Logging/LogManager.cs @@ -93,18 +93,18 @@ namespace StardewModdingAPI.Framework.Logging /// Get the screen ID that should be logged to distinguish between players in split-screen mode, if any. public LogManager(string logPath, ColorSchemeConfig colorConfig, bool writeToConsole, bool isVerbose, bool isDeveloperMode, Func getScreenIdForLog) { - // init fields + // init log file this.LogFile = new LogFileManager(logPath); - this.Monitor = this.GetMonitor("SMAPI"); - this.MonitorForGame = this.GetMonitor("game"); - // init construction logic + // init monitor this.GetMonitorImpl = name => new Monitor(name, LogManager.IgnoreChar, this.LogFile, colorConfig, isVerbose, getScreenIdForLog) { WriteToConsole = writeToConsole, ShowTraceInConsole = isDeveloperMode, ShowFullStampInConsole = isDeveloperMode }; + this.Monitor = this.GetMonitor("SMAPI"); + this.MonitorForGame = this.GetMonitor("game"); // redirect direct console output this.ConsoleInterceptor = new InterceptingTextWriter( diff --git a/src/SMAPI/Framework/Reflection/Reflector.cs b/src/SMAPI/Framework/Reflection/Reflector.cs index 3490ee97..79575c26 100644 --- a/src/SMAPI/Framework/Reflection/Reflector.cs +++ b/src/SMAPI/Framework/Reflection/Reflector.cs @@ -153,7 +153,7 @@ namespace StardewModdingAPI.Framework.Reflection { for (Type? curType = type; curType != null; curType = curType.BaseType) { - FieldInfo? fieldInfo = type.GetField(name, bindingFlags); + FieldInfo? fieldInfo = curType.GetField(name, bindingFlags); if (fieldInfo != null) { type = curType; @@ -182,7 +182,7 @@ namespace StardewModdingAPI.Framework.Reflection { for (Type? curType = type; curType != null; curType = curType.BaseType) { - PropertyInfo? propertyInfo = type.GetProperty(name, bindingFlags); + PropertyInfo? propertyInfo = curType.GetProperty(name, bindingFlags); if (propertyInfo != null) { type = curType; @@ -210,7 +210,7 @@ namespace StardewModdingAPI.Framework.Reflection { for (Type? curType = type; curType != null; curType = curType.BaseType) { - MethodInfo? methodInfo = type.GetMethod(name, bindingFlags); + MethodInfo? methodInfo = curType.GetMethod(name, bindingFlags); if (methodInfo != null) { type = curType; -- cgit