using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Guilds; using HarmonyLib; using ItemManager; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using TameGuildWars.Compatibility; using UnityEngine; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("TameGuildWars")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("TameGuildWars")] [assembly: AssemblyCopyright("Copyright © 2022")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("1327040b-77e8-48df-918a-542534b5ec0f")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyCompany("WackyMole")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<54445620-f45c-49a6-9f02-d5bbf8177ed1>Embedded] internal sealed class <54445620-f45c-49a6-9f02-d5bbf8177ed1>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [CompilerGenerated] [<54445620-f45c-49a6-9f02-d5bbf8177ed1>Embedded] internal sealed class <01a73d35-473a-4adb-86fb-c7fd269b4cb1>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <01a73d35-473a-4adb-86fb-c7fd269b4cb1>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <01a73d35-473a-4adb-86fb-c7fd269b4cb1>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<54445620-f45c-49a6-9f02-d5bbf8177ed1>Embedded] [CompilerGenerated] internal sealed class <3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContextAttribute : Attribute { public readonly byte Flag; public <3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace TameGuildWars { [BepInPlugin("WackyMole.TameGuildWars", "TameGuildWars", "1.0.0")] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class TameGuildWarsPlugin : BaseUnityPlugin { [HarmonyPatch(typeof(ZNet), "Awake")] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] private static class ZNetAwakePatch { [HarmonyPostfix] private static void Postfix() { Instance?.TryRegisterAllyRpc(); } } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] public enum Toggle { On = 1, Off = 0 } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(2)] [UsedImplicitly] public string Category; [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action CustomDrawer; } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] private class AcceptableShortcuts : AcceptableValueBase { public AcceptableShortcuts() : base(typeof(KeyboardShortcut)) { } public override object Clamp(object value) { return value; } public override bool IsValid(object value) { return true; } public override string ToDescriptionString() { return "# Acceptable values: " + string.Join(", ", UnityInput.Current.SupportedKeyCodes); } } private static string _pendingAllyRequesterGuild = string.Empty; private static string _pendingAllyRequestedTarget = string.Empty; private static bool _showAllyRequestPopup; private static GUIStyle _allyPopupTitleStyle; private static GUIStyle _allyPopupLabelStyle; private bool _allyRpcRegistered; private bool _allyRpcRegistrationStarted; internal static TameGuildWarsPlugin Instance; internal const string ModName = "TameGuildWars"; internal const string ModVersion = "1.0.0"; internal const string Author = "WackyMole"; private const string ModGUID = "WackyMole.TameGuildWars"; private static string ConfigFileName = "WackyMole.TameGuildWars.cfg"; private static string ConfigFileFullPath; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("WackyMole.TameGuildWars"); public static readonly ManualLogSource TameGuildWarsLogger; private static readonly ConfigSync ConfigSync; public static ConfigEntry ConfigObedienceDecayRate; public static ConfigEntry ConfigNonGuildMemberDecayMultiplier; public static ConfigEntry ConfigNoGuildDecayMultiplier; public static ConfigEntry ConfigHostileToNeutrals; public static ConfigEntry ConfigConfusionDurationSeconds; public static ConfigEntry ConfigCommandHornRadius; public static ConfigEntry ConfigCommandHornSound; public static ConfigEntry ConfigConfusionResistanceMinHealth; public static ConfigEntry ConfigConfusionResistanceMaxHealth; public static ConfigEntry ConfigConfusionResistanceMaxValue; public static ConfigEntry ConfigConfusionResistanceLowHealthMultiplier; public static ConfigEntry ConfigConfusionBomb1Min; public static ConfigEntry ConfigConfusionBomb1Max; public static ConfigEntry ConfigConfusionBomb2Min; public static ConfigEntry ConfigConfusionBomb2Max; public static ConfigEntry ConfigConfusionBomb3Min; public static ConfigEntry ConfigConfusionBomb3Max; public static ConfigEntry ConfigAllowBossConfusion; public static ConfigEntry ConfigDeathNotifications; public static ConfigEntry ConfigShowGuildIcon; public static ConfigEntry ConfigGuildIconOffsetX; public static ConfigEntry ConfigGuildIconOffsetY; public static ConfigEntry ConfigAlarmDurationSeconds; public static ConfigEntry ConfigAlarmLeashDistance; public static ConfigEntry ConfigAllyAddCooldownSeconds; public static ConfigEntry ConfigGuardLeashDistance; public static ConfigEntry ConfigSwarmRadius; public static ConfigEntry ConfigSwarmCheckInterval; public static ConfigEntry ConfigMobActionLogging; public static readonly CustomSyncedValue SyncedAllies; private static ConfigEntry _serverConfigLocked; private const string SharedChatInputRpc = "TGW_SendSharedChatInput"; private static readonly FieldInfo ChatInputField; private void OnGUI() { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (_showAllyRequestPopup && !string.IsNullOrEmpty(_pendingAllyRequesterGuild) && !string.IsNullOrEmpty(_pendingAllyRequestedTarget) && !((Object)(object)Player.m_localPlayer == (Object)null)) { EnsureAllyPopupStyles(); Rect val = default(Rect); ((Rect)(ref val))..ctor(((float)Screen.width - 520f) * 0.5f, ((float)Screen.height - 200f) * 0.5f, 520f, 200f); GUI.ModalWindow(938412, val, new WindowFunction(DrawAllyRequestPopupWindow), "Guild Ally Request"); } } private static void EnsureAllyPopupStyles() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown if (_allyPopupTitleStyle == null) { _allyPopupTitleStyle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)4, fontSize = 18, fontStyle = (FontStyle)1, wordWrap = true }; } if (_allyPopupLabelStyle == null) { _allyPopupLabelStyle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)4, fontSize = 14, wordWrap = true }; } } private static void DrawAllyRequestPopupWindow(int windowId) { GUILayout.BeginVertical(Array.Empty()); GUILayout.Space(12f); GUILayout.Label("Guild '" + _pendingAllyRequesterGuild + "' is requesting an alliance with '" + _pendingAllyRequestedTarget + "'.", _allyPopupTitleStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(54f) }); GUILayout.Space(10f); GUILayout.Label("Accepting will make both sides allied. Denying will reject the request.", _allyPopupLabelStyle, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(36f) }); GUILayout.Space(14f); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.FlexibleSpace(); GUI.enabled = ZRoutedRpc.instance != null; if (GUILayout.Button("Accept", (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(170f), GUILayout.Height(40f) })) { RespondToPendingAllyRequest(accept: true); } GUILayout.Space(16f); if (GUILayout.Button("Deny", (GUILayoutOption[])(object)new GUILayoutOption[2] { GUILayout.Width(170f), GUILayout.Height(40f) })) { RespondToPendingAllyRequest(accept: false); } GUI.enabled = true; GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(8f); GUILayout.EndVertical(); GUI.DragWindow(); } private static void RespondToPendingAllyRequest(bool accept) { if (string.IsNullOrEmpty(_pendingAllyRequesterGuild) || string.IsNullOrEmpty(_pendingAllyRequestedTarget)) { _showAllyRequestPopup = false; return; } if (ZRoutedRpc.instance == null) { Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)2, "Unable to respond right now (network not ready).", 0, (Sprite)null); } return; } string pendingAllyRequesterGuild = _pendingAllyRequesterGuild; string pendingAllyRequestedTarget = _pendingAllyRequestedTarget; TameGuildWarsLogger.LogInfo((object)("Popup ally response: action='" + (accept ? "accept" : "deny") + "', requester='" + pendingAllyRequesterGuild + "', target='" + pendingAllyRequestedTarget + "'.")); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_RespondAllyRequest", new object[3] { pendingAllyRequesterGuild, pendingAllyRequestedTarget, accept }); _showAllyRequestPopup = false; _pendingAllyRequesterGuild = string.Empty; _pendingAllyRequestedTarget = string.Empty; } private static void ShowAllyRequestPopup(string requesterGuild, string requestedTarget) { _pendingAllyRequesterGuild = requesterGuild ?? string.Empty; _pendingAllyRequestedTarget = requestedTarget ?? string.Empty; _showAllyRequestPopup = !string.IsNullOrEmpty(_pendingAllyRequesterGuild) && !string.IsNullOrEmpty(_pendingAllyRequestedTarget); } private void TryRegisterAllyRpc() { if (!_allyRpcRegistered && ZRoutedRpc.instance != null) { ZRoutedRpc.instance.Register("TGW_SetAlly", (Action)RPC_TGW_SetAlly); ZRoutedRpc.instance.Register("TGW_RequestAlly", (Action)RPC_TGW_RequestAlly); ZRoutedRpc.instance.Register("TGW_NotifyAllyRequest", (Action)RPC_TGW_NotifyAllyRequest); ZRoutedRpc.instance.Register("TGW_RespondAllyRequest", (Action)RPC_TGW_RespondAllyRequest); ZRoutedRpc.instance.Register("TGW_NotifyAllyResponse", (Action)RPC_TGW_NotifyAllyResponse); ZRoutedRpc.instance.Register("TGW_BroadcastAllyRemoved", (Action)RPC_TGW_BroadcastAllyRemoved); ZRoutedRpc.instance.Register("TGW_NotifyAllyRemoved", (Action)RPC_TGW_NotifyAllyRemoved); ZRoutedRpc.instance.Register("TGW_SendSharedChatInput", (Action)RPC_TGW_SendSharedChatInput); _allyRpcRegistered = true; ((MonoBehaviour)this).CancelInvoke("TryRegisterAllyRpc"); } } private static void RPC_TGW_SetAlly(long sender, string myGuild, string targetNameOrGuild, bool ally) { if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { TameGuildWarsLogger.LogInfo((object)string.Format("Received TGW_SetAlly RPC from sender {0}: guild='{1}', target='{2}', action='{3}'.", sender, myGuild, targetNameOrGuild, ally ? "add" : "remove")); if (!GuildUtils.TryGetSenderGuild(sender, out var guildName) || string.IsNullOrEmpty(guildName)) { TameGuildWarsLogger.LogWarning((object)$"Unable to resolve guild for ally update sender {sender}; accepting claimed guild '{myGuild}'."); } else if (!string.Equals(guildName, myGuild, StringComparison.Ordinal)) { TameGuildWarsLogger.LogWarning((object)$"Rejected ally update from sender {sender}: claimed guild '{myGuild}' but actual guild was '{guildName}'."); return; } if (GuildUtils.SetAlly(myGuild, targetNameOrGuild, ally)) { TameGuildWarsLogger.LogInfo((object)("Guild '" + myGuild + "' " + (ally ? "added" : "removed") + " ally '" + targetNameOrGuild + "'.")); } else { TameGuildWarsLogger.LogWarning((object)("Guild '" + myGuild + "' failed to " + (ally ? "add" : "remove") + " ally '" + targetNameOrGuild + "' (cooldown or invalid state).")); } } } private static void RPC_TGW_RequestAlly(long sender, string requesterGuild, string requestedTarget) { if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer()) { TameGuildWarsLogger.LogInfo((object)$"Received TGW_RequestAlly RPC from sender {sender}: requester='{requesterGuild}', target='{requestedTarget}'."); if (string.IsNullOrWhiteSpace(requesterGuild) || string.IsNullOrWhiteSpace(requestedTarget)) { TameGuildWarsLogger.LogWarning((object)"Rejected TGW_RequestAlly because requester guild or target was blank."); return; } if (GuildUtils.TryGetSenderGuild(sender, out var guildName) && !string.IsNullOrEmpty(guildName) && !string.Equals(guildName, requesterGuild, StringComparison.Ordinal)) { TameGuildWarsLogger.LogWarning((object)$"Rejected TGW_RequestAlly from sender {sender}: claimed guild '{requesterGuild}' but actual guild was '{guildName}'."); return; } GuildUtils.CreatePendingAllyRequest(requesterGuild, requestedTarget, sender); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "TGW_NotifyAllyRequest", new object[2] { requesterGuild, requestedTarget }); } } private static void RPC_TGW_NotifyAllyRequest(long sender, string requesterGuild, string requestedTarget) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } foreach (string localPlayerAllyRequestTarget in GuildUtils.GetLocalPlayerAllyRequestTargets(localPlayer)) { if (string.Equals(localPlayerAllyRequestTarget, requestedTarget, StringComparison.OrdinalIgnoreCase)) { GuildUtils.CreatePendingAllyRequest(requesterGuild, requestedTarget, sender); TameGuildWarsLogger.LogInfo((object)("Received ally request prompt for local target '" + requestedTarget + "' from guild '" + requesterGuild + "'.")); ((Character)localPlayer).Message((MessageType)2, "Ally request from " + requesterGuild + ". Use guild_ally accept " + requesterGuild + " " + requestedTarget + " or guild_ally deny " + requesterGuild + " " + requestedTarget, 0, (Sprite)null); ShowAllyRequestPopup(requesterGuild, requestedTarget); break; } } } private static void RPC_TGW_RespondAllyRequest(long sender, string requesterGuild, string requestedTarget, bool accepted) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } TameGuildWarsLogger.LogInfo((object)$"Received TGW_RespondAllyRequest RPC from sender {sender}: requester='{requesterGuild}', target='{requestedTarget}', accepted={accepted}."); if (!GuildUtils.TryGetPendingAllyRequest(requesterGuild, requestedTarget, out var _)) { TameGuildWarsLogger.LogWarning((object)("No pending ally request found for requester='" + requesterGuild + "', target='" + requestedTarget + "'.")); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "TGW_NotifyAllyResponse", new object[3] { requesterGuild, requestedTarget, false }); return; } GuildUtils.RemovePendingAllyRequest(requesterGuild, requestedTarget); if (accepted) { bool flag = GuildUtils.SetAlly(requesterGuild, requestedTarget, ally: true); bool flag2 = GuildUtils.SetAlly(requestedTarget, requesterGuild, ally: true); string text = BuildAllianceFormedMessage(requesterGuild, requestedTarget); TameGuildWarsLogger.LogInfo((object)((flag && flag2) ? text : ("Alliance acceptance partially failed between " + requesterGuild + " and " + requestedTarget + "."))); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "TGW_NotifyAllyResponse", new object[3] { requesterGuild, requestedTarget, flag && flag2 }); if (flag && flag2) { SendSharedChatInput(sender, "/s " + text); } } else { string text2 = "Alliance request from " + requesterGuild + " to " + requestedTarget + " was denied."; TameGuildWarsLogger.LogInfo((object)text2); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "TGW_NotifyAllyResponse", new object[3] { requesterGuild, requestedTarget, false }); } } private static void RPC_TGW_NotifyAllyResponse(long sender, string requesterGuild, string requestedTarget, bool accepted) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { bool num = GuildUtils.GetLocalPlayerAllyRequestTargets(localPlayer).Any([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string target) => string.Equals(target, requestedTarget, StringComparison.OrdinalIgnoreCase) || string.Equals(target, requesterGuild, StringComparison.OrdinalIgnoreCase)); string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (num || string.Equals(playerGuildName, requesterGuild, StringComparison.OrdinalIgnoreCase)) { string text = (accepted ? ("Alliance formed between " + requesterGuild + " and " + requestedTarget + ".") : ("Alliance request between " + requesterGuild + " and " + requestedTarget + " was denied or failed.")); TameGuildWarsLogger.LogInfo((object)$"Ally response notification: requester='{requesterGuild}', target='{requestedTarget}', accepted={accepted}. Message='{text}'"); ((Character)localPlayer).Message((MessageType)(accepted ? 1 : 2), text, 0, (Sprite)null); } } } private static void RPC_TGW_BroadcastAllyRemoved(long sender, string removerGuild, string removedTarget) { if (!((Object)(object)ZNet.instance == (Object)null) && ZNet.instance.IsServer() && !string.IsNullOrWhiteSpace(removerGuild) && !string.IsNullOrWhiteSpace(removedTarget)) { if (GuildUtils.TryGetSenderGuild(sender, out var guildName) && !string.IsNullOrEmpty(guildName) && !string.Equals(guildName, removerGuild, StringComparison.Ordinal)) { TameGuildWarsLogger.LogWarning((object)$"Rejected TGW_BroadcastAllyRemoved from sender {sender}: claimed guild '{removerGuild}' but actual guild was '{guildName}'."); return; } ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "TGW_NotifyAllyRemoved", new object[2] { removerGuild, removedTarget }); SendSharedChatInput(sender, "/s " + BuildAllianceRemovedMessage(removerGuild, removedTarget)); } } private static void RPC_TGW_NotifyAllyRemoved(long sender, string removerGuild, string removedTarget) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (string.Equals(playerGuildName, removerGuild, StringComparison.OrdinalIgnoreCase) || string.Equals(playerGuildName, removedTarget, StringComparison.OrdinalIgnoreCase) || string.Equals(localPlayer.GetPlayerName(), removedTarget, StringComparison.OrdinalIgnoreCase)) { string text = BuildAllianceRemovedMessage(removerGuild, removedTarget); ((Character)localPlayer).Message((MessageType)2, text, 0, (Sprite)null); TameGuildWarsLogger.LogInfo((object)("Ally removal notification: remover='" + removerGuild + "', target='" + removedTarget + "'.")); } } } private static string BuildAllianceFormedMessage(string requesterGuild, string requestedTarget) { return "Alliance formed between " + requesterGuild + " and " + requestedTarget + "."; } private static string BuildAllianceRemovedMessage(string removerGuild, string removedTarget) { return "Alliance between " + removerGuild + " and " + removedTarget + " has been removed."; } public void Awake() { Instance = this; ConfigObedienceDecayRate = config("1 - General", "Obedience Decay Rate", 0.1f, "Base Obedience Loss per update tick"); ConfigNonGuildMemberDecayMultiplier = config("1 - General", "Non-Guild Member Decay Multiplier", 3f, "Multiplier applied to obedience decay when near non-guild members"); ConfigNoGuildDecayMultiplier = config("1 - General", "No Guild Decay Multiplier", 5f, "Multiplier applied to obedience decay when the owner has no guild"); ConfigConfusionDurationSeconds = config("1 - General", "Confusion Duration", 120f, "Duration in seconds for maximum (100) confusion to wear off."); ConfigCommandHornRadius = config("1 - General", "Command Horn Radius", 30f, "Radius in meters for tamed guild mobs affected by the command horn."); ConfigCommandHornSound = config("1 - General", "Command Horn Sound", "sfx_viking-horn", "Sound effect played when using the command horn."); ConfigDeathNotifications = config("1 - General", "Death Notifications", Toggle.On, "If On, global notifications will be sent when high-value guild mobs (2+ stars) are killed by a player from another guild."); ConfigShowGuildIcon = config("1 - General", "Show Guild Icon", Toggle.On, "If On, shows the guild's icon image next to the mob's name plate."); ConfigGuildIconOffsetX = config("1 - General", "Guild Icon Offset X", -85f, "Horizontal offset for the guild icon relative to the mob nameplate."); ConfigGuildIconOffsetY = config("1 - General", "Guild Icon Offset Y", 0f, "Vertical offset for the guild icon relative to the mob nameplate."); ConfigHostileToNeutrals = config("3 - Combat", "Hostile To Neutral Players", Toggle.On, "If On, guild mobs will attack players who are not in any guild."); ConfigAlarmDurationSeconds = config("3 - Combat", "Alarm Duration", 30f, "How long a mob remembers the last hostile player before calming down."); ConfigAlarmLeashDistance = config("3 - Combat", "Alarm Leash Distance", 75f, "How far the alarmed player can get from the mob before the alarm is cleared."); ConfigAllyAddCooldownSeconds = config("3 - Combat", "Ally Add Cooldown Seconds", 10f, "Cooldown before adding the same ally target again with guild_ally add."); ConfigGuardLeashDistance = config("3 - Combat", "Guard Leash Distance", 125f, "Maximum distance a mob in Guard stance can move from its stance anchor before returning."); ConfigSwarmRadius = config("3 - Combat", "Swarm Radius", 50f, "Radius in meters for nearby same-guild mobs to join a swarm response."); ConfigSwarmCheckInterval = config("3 - Combat", "Swarm Check Interval", 2f, "How often idle guild mobs scan nearby same-guild mobs for a swarm target. Lower is more responsive; higher is cheaper."); ConfigMobActionLogging = config("4 - Debug", "Mob Action Logging", Toggle.Off, "If On, logs major guild mob actions such as stance changes, alarms, and target swaps.", synchronizedSetting: false); ConfigConfusionResistanceMinHealth = config("2 - Confusion", "Resistance Min Health", 25f, "Max health value where confusion resistance starts scaling."); ConfigConfusionResistanceMaxHealth = config("2 - Confusion", "Resistance Max Health", 1600f, "Max health value where confusion resistance reaches full configured strength (before multiplayer scaling)."); ConfigConfusionResistanceMaxValue = config("2 - Confusion", "Resistance Max Value", 0.9f, "Maximum confusion resistance at or above Resistance Max Health. 0 = none, 1 = full immunity."); ConfigConfusionResistanceLowHealthMultiplier = config("2 - Confusion", "Resistance At 0% Health Multiplier", 0.7f, "How much of baseline resistance remains when the mob is near 0 health. 0 = no resistance when low, 1 = full baseline."); ConfigConfusionBomb1Min = config("2 - Confusion", "Bomb Tier 1 Min", 12f, "Minimum confusion added by tgw_confusionbomb1 before resistance."); ConfigConfusionBomb1Max = config("2 - Confusion", "Bomb Tier 1 Max", 32f, "Maximum confusion added by tgw_confusionbomb1 before resistance."); ConfigConfusionBomb2Min = config("2 - Confusion", "Bomb Tier 2 Min", 24f, "Minimum confusion added by tgw_confusionbomb2 before resistance."); ConfigConfusionBomb2Max = config("2 - Confusion", "Bomb Tier 2 Max", 55f, "Maximum confusion added by tgw_confusionbomb2 before resistance."); ConfigConfusionBomb3Min = config("2 - Confusion", "Bomb Tier 3 Min", 40f, "Minimum confusion added by tgw_confusionbomb3 before resistance."); ConfigConfusionBomb3Max = config("2 - Confusion", "Bomb Tier 3 Max", 85f, "Maximum confusion added by tgw_confusionbomb3 before resistance."); ConfigAllowBossConfusion = config("2 - Confusion", "Allow Boss Confusion", Toggle.Off, "If On, boss-class enemies can be affected by Confusion Bombs. Default: Off (bosses immune). [Synced with Server]"); Item item = new Item("tamebundle", "tgw_confusionbomb1"); item.Name.English("Confusion Bomb I"); item.Description.English("Applies a low confusion amount to tamed mobs in an area."); item.RequiredItems.Add("Resin", 8); item.RequiredItems.Add("Coal", 4); item.RequiredItems.Add("LeatherScraps", 3); item.RequiredItems.Add("Ooze", 2); item.Crafting.Add(CraftingTable.Workbench, 2); item.Configurable = Configurability.Recipe | Configurability.Drop | Configurability.Trader; Item item2 = new Item("tamebundle", "tgw_confusionbomb2"); item2.Name.English("Confusion Bomb II"); item2.Description.English("Applies a medium confusion amount to tamed mobs in an area."); item2.RequiredItems.Add("Resin", 10); item2.RequiredItems.Add("Ooze", 4); item2.RequiredItems.Add("Obsidian", 3); item2.RequiredItems.Add("Crystal", 6); item2.Crafting.Add(CraftingTable.Workbench, 5); item2.Configurable = Configurability.Recipe | Configurability.Drop | Configurability.Trader; Item item3 = new Item("tamebundle", "tgw_confusionbomb3"); item3.Name.English("Confusion Bomb III"); item3.Description.English("Applies a high confusion amount to tamed mobs in an area."); item3.RequiredItems.Add("Resin", 12); item3.RequiredItems.Add("Ooze", 6); item3.RequiredItems.Add("Bilebag", 2); item3.RequiredItems.Add("BlackCore", 1); item3.Crafting.Add(CraftingTable.MageTable, 1); item3.Configurable = Configurability.Recipe | Configurability.Drop | Configurability.Trader; Item item4 = new Item("tamebundle", "tgw_command"); item4.Name.English("Command Horn"); item4.Description.English("Blow to cycle nearby guild tamed mob orders."); item4.RequiredItems.Add("FineWood", 10); item4.RequiredItems.Add("LeatherScraps", 4); item4.RequiredItems.Add("Bronze", 2); item4.Crafting.Add(CraftingTable.Workbench, 3); PrefabManager.RegisterPrefab("tamebundle", "sfx_viking-horn"); item4.Configurable = Configurability.Recipe | Configurability.Drop | Configurability.Trader; Assembly executingAssembly = Assembly.GetExecutingAssembly(); _harmony.PatchAll(executingAssembly); PortablePalsPatches.TryPatch(_harmony); SetupWatcher(); } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); } private void SetupWatcher() { TryRegisterAllyRpc(); if (!_allyRpcRegistered && !_allyRpcRegistrationStarted) { ((MonoBehaviour)this).InvokeRepeating("TryRegisterAllyRpc", 1f, 1f); _allyRpcRegistrationStarted = true; } FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; FileSystemWatcher fileSystemWatcher2 = new FileSystemWatcher(Paths.ConfigPath, "TameGuildWarsAllies.txt"); fileSystemWatcher2.Changed += ReadAlliesValues; fileSystemWatcher2.Created += ReadAlliesValues; fileSystemWatcher2.Renamed += ReadAlliesValues; fileSystemWatcher2.IncludeSubdirectories = true; fileSystemWatcher2.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher2.EnableRaisingEvents = true; ReadAlliesValues(null, null); } private void ReadAlliesValues(object sender, FileSystemEventArgs e) { string path = Path.Combine(Paths.ConfigPath, "TameGuildWarsAllies.txt"); if (!File.Exists(path)) { File.WriteAllText(path, ""); } try { TameGuildWarsLogger.LogDebug((object)"ReadAlliesValues called"); string value = File.ReadAllText(path); SyncedAllies.Value = value; } catch (Exception arg) { TameGuildWarsLogger.LogError((object)$"There was an issue loading your TameGuildWarsAllies.txt\n{arg}"); } } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { TameGuildWarsLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { TameGuildWarsLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); TameGuildWarsLogger.LogError((object)"Please check your config entries for spelling and format!"); } } private ConfigEntry config<[<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(group, name, value, val); ConfigSync.AddConfigEntry(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry config<[<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } internal static void SendGuildChatInput(string message) { SendChatInput("/g", message); } internal static void SendShoutChatInput(string message) { SendChatInput("/s", message); } private static void SendSharedChatInput(long targetPeerId, string inputText) { if (!string.IsNullOrWhiteSpace(inputText) && ZRoutedRpc.instance != null) { long serverPeerID = ZRoutedRpc.instance.GetServerPeerID(); if (targetPeerId == serverPeerID && (Object)(object)Player.m_localPlayer != (Object)null) { SendRawChatInput(inputText); return; } ZRoutedRpc.instance.InvokeRoutedRPC(targetPeerId, "TGW_SendSharedChatInput", new object[1] { inputText }); } } private static void RPC_TGW_SendSharedChatInput(long sender, string inputText) { SendRawChatInput(inputText); } private static void SendChatInput(string command, string message) { if (!string.IsNullOrWhiteSpace(command) && !string.IsNullOrWhiteSpace(message)) { SendRawChatInput(command + " " + NormalizeChatMessage(message)); } } private static void SendRawChatInput(string inputText) { if ((Object)(object)Chat.instance == (Object)null || string.IsNullOrWhiteSpace(inputText)) { return; } object obj = ChatInputField?.GetValue(Chat.instance); PropertyInfo propertyInfo = obj?.GetType().GetProperty("text", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); string value = (propertyInfo?.GetValue(obj, null) as string) ?? string.Empty; try { if (obj == null || propertyInfo == null || !propertyInfo.CanWrite) { TameGuildWarsLogger.LogWarning((object)"Failed to send shared chat input: Chat.m_input.text was not available."); return; } propertyInfo.SetValue(obj, NormalizeChatMessage(inputText), null); ((Terminal)Chat.instance).InputText(); } catch (Exception ex) { TameGuildWarsLogger.LogWarning((object)("Failed to send shared chat input '" + inputText + "': " + ex.Message)); } finally { if (obj != null && propertyInfo != null && propertyInfo.CanWrite && !string.IsNullOrEmpty(value)) { propertyInfo.SetValue(obj, value, null); } } } private static string NormalizeChatMessage(string message) { return message.Replace('\r', ' ').Replace('\n', ' ').Trim(); } static TameGuildWarsPlugin() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; TameGuildWarsLogger = Logger.CreateLogSource("TameGuildWars"); ConfigSync = new ConfigSync("WackyMole.TameGuildWars") { DisplayName = "TameGuildWars", CurrentVersion = "1.0.0", MinimumRequiredVersion = "1.0.0" }; ConfigObedienceDecayRate = null; ConfigNonGuildMemberDecayMultiplier = null; ConfigNoGuildDecayMultiplier = null; ConfigHostileToNeutrals = null; ConfigConfusionDurationSeconds = null; ConfigCommandHornRadius = null; ConfigCommandHornSound = null; ConfigConfusionResistanceMinHealth = null; ConfigConfusionResistanceMaxHealth = null; ConfigConfusionResistanceMaxValue = null; ConfigConfusionResistanceLowHealthMultiplier = null; ConfigConfusionBomb1Min = null; ConfigConfusionBomb1Max = null; ConfigConfusionBomb2Min = null; ConfigConfusionBomb2Max = null; ConfigConfusionBomb3Min = null; ConfigConfusionBomb3Max = null; ConfigAllowBossConfusion = null; ConfigDeathNotifications = null; ConfigShowGuildIcon = null; ConfigGuildIconOffsetX = null; ConfigGuildIconOffsetY = null; ConfigAlarmDurationSeconds = null; ConfigAlarmLeashDistance = null; ConfigAllyAddCooldownSeconds = null; ConfigGuardLeashDistance = null; ConfigSwarmRadius = null; ConfigSwarmCheckInterval = null; ConfigMobActionLogging = null; SyncedAllies = new CustomSyncedValue(ConfigSync, "TameGuildWarsAllies", ""); _serverConfigLocked = null; ChatInputField = typeof(Chat).GetField("m_input", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] public static class GuildUtils { [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] private struct CachedGuildName { [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(1)] public string GuildName; public long CachedAtTicks; } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] public struct PendingAllyRequest { public string RequesterGuild; public string RequestedTarget; public long SenderPeerId; public long ExpiresAtTicks; } private const double PlayerGuildCacheSeconds = 1.0; private const double AllianceBreakGraceSeconds = 10.0; private const double AllyRequestLifetimeSeconds = 60.0; private static readonly Dictionary AllianceGraceUntilTicks = new Dictionary(); private static readonly Dictionary AllyAddCooldownUntilTicks = new Dictionary(); private static readonly Dictionary PendingIncomingAllyRequests = new Dictionary(); private static readonly Dictionary PlayerGuildCache = new Dictionary(); public static string GetPlayerGuildName(Player player) { if ((Object)(object)player == (Object)null) { return string.Empty; } long playerID = player.GetPlayerID(); long ticks = DateTime.UtcNow.Ticks; if (playerID != 0L && PlayerGuildCache.TryGetValue(playerID, out var value) && new TimeSpan(ticks - value.CachedAtTicks).TotalSeconds <= 1.0) { return value.GuildName ?? string.Empty; } string text = string.Empty; if (API.IsLoaded()) { Guild playerGuild = API.GetPlayerGuild(player); if (playerGuild != null) { text = playerGuild.Name; } } if (playerID != 0L) { PlayerGuildCache[playerID] = new CachedGuildName { GuildName = text, CachedAtTicks = ticks }; } return text ?? string.Empty; } public static void InvalidatePlayerGuildCache(long playerId = 0L) { if (playerId == 0L) { PlayerGuildCache.Clear(); } else { PlayerGuildCache.Remove(playerId); } } public static bool IsAlly(string myGuild, string targetNameOrGuild) { if (string.IsNullOrEmpty(myGuild) || string.IsNullOrEmpty(targetNameOrGuild)) { return false; } string key = BuildAllyKey(myGuild, targetNameOrGuild); if (TameGuildWarsPlugin.SyncedAllies.Value == null) { return false; } return TameGuildWarsPlugin.SyncedAllies.Value.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Any([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string ally) => string.Equals(ally.Trim(), key, StringComparison.OrdinalIgnoreCase)); } public static bool IsAllianceBreakGraceActive(string myGuild, string targetNameOrGuild) { if (string.IsNullOrEmpty(myGuild) || string.IsNullOrEmpty(targetNameOrGuild)) { return false; } string key = BuildAllyKey(myGuild, targetNameOrGuild); if (!AllianceGraceUntilTicks.TryGetValue(key, out var value)) { return false; } if (DateTime.UtcNow.Ticks <= value) { return true; } AllianceGraceUntilTicks.Remove(key); return false; } public static string BuildPendingAllyRequestKey(string requesterGuild, string requestedTarget) { return requesterGuild.Trim().ToLowerInvariant() + "::" + requestedTarget.Trim().ToLowerInvariant(); } public static PendingAllyRequest CreatePendingAllyRequest(string requesterGuild, string requestedTarget, long senderPeerId) { PendingAllyRequest pendingAllyRequest = new PendingAllyRequest { RequesterGuild = requesterGuild.Trim(), RequestedTarget = requestedTarget.Trim(), SenderPeerId = senderPeerId, ExpiresAtTicks = DateTime.UtcNow.AddSeconds(60.0).Ticks }; PendingIncomingAllyRequests[BuildPendingAllyRequestKey(pendingAllyRequest.RequesterGuild, pendingAllyRequest.RequestedTarget)] = pendingAllyRequest; TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"Stored pending ally request: requester='{pendingAllyRequest.RequesterGuild}', target='{pendingAllyRequest.RequestedTarget}', sender={pendingAllyRequest.SenderPeerId}."); return pendingAllyRequest; } public static bool TryGetPendingAllyRequest(string requesterGuild, string requestedTarget, out PendingAllyRequest request) { string key = BuildPendingAllyRequestKey(requesterGuild, requestedTarget); if (!PendingIncomingAllyRequests.TryGetValue(key, out request)) { return false; } if (DateTime.UtcNow.Ticks <= request.ExpiresAtTicks) { return true; } PendingIncomingAllyRequests.Remove(key); request = default(PendingAllyRequest); return false; } public static bool RemovePendingAllyRequest(string requesterGuild, string requestedTarget) { string key = BuildPendingAllyRequestKey(requesterGuild, requestedTarget); bool flag = PendingIncomingAllyRequests.Remove(key); if (flag) { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("Removed pending ally request: requester='" + requesterGuild + "', target='" + requestedTarget + "'.")); } return flag; } public static string BuildAllyKey(string myGuild, string targetNameOrGuild) { return ("TGW_Ally_" + myGuild.Trim() + "_" + targetNameOrGuild.Trim()).ToLowerInvariant(); } public static bool TryGetAllyAddCooldownRemaining(string myGuild, string targetNameOrGuild, out double remainingSeconds) { remainingSeconds = 0.0; if (string.IsNullOrEmpty(myGuild) || string.IsNullOrEmpty(targetNameOrGuild)) { return false; } string key = BuildAllyKey(myGuild, targetNameOrGuild); if (!AllyAddCooldownUntilTicks.TryGetValue(key, out var value)) { return false; } remainingSeconds = new TimeSpan(value - DateTime.UtcNow.Ticks).TotalSeconds; if (remainingSeconds > 0.0) { return true; } AllyAddCooldownUntilTicks.Remove(key); remainingSeconds = 0.0; return false; } public static bool SetAlly(string myGuild, string targetNameOrGuild, bool ally) { if (string.IsNullOrEmpty(myGuild) || string.IsNullOrEmpty(targetNameOrGuild)) { return false; } string text = BuildAllyKey(myGuild, targetNameOrGuild); if (ally && TryGetAllyAddCooldownRemaining(myGuild, targetNameOrGuild, out var remainingSeconds)) { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"Rejected ally add for '{text}' due to cooldown ({remainingSeconds:0.0}s remaining)."); return false; } if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer()) { if (ZRoutedRpc.instance == null) { TameGuildWarsPlugin.TameGuildWarsLogger.LogWarning((object)("Unable to " + (ally ? "add" : "remove") + " ally '" + targetNameOrGuild + "' for guild '" + myGuild + "': ZRoutedRpc is not ready.")); return false; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("Dispatching ally " + (ally ? "add" : "remove") + " RPC: guild='" + myGuild + "', target='" + targetNameOrGuild + "', key='" + text + "'.")); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_SetAlly", new object[3] { myGuild, targetNameOrGuild, ally }); if (ally) { float num = ((TameGuildWarsPlugin.ConfigAllyAddCooldownSeconds != null) ? Mathf.Max(0f, TameGuildWarsPlugin.ConfigAllyAddCooldownSeconds.Value) : 0f); if (num > 0f) { AllyAddCooldownUntilTicks[text] = DateTime.UtcNow.AddSeconds(num).Ticks; } } return true; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("Applying ally " + (ally ? "add" : "remove") + " locally on server: key='" + text + "'.")); InternalSetAlly(text, ally); return true; } public static List ResolveAllyTargets(string targetNameOrGuild) { List list = new List(); if (string.IsNullOrWhiteSpace(targetNameOrGuild)) { return list; } string trimmedTarget = targetNameOrGuild.Trim(); list.Add(trimmedTarget); Player val = Player.GetAllPlayers().Find([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (Player player) => (Object)(object)player != (Object)null && string.Equals(player.GetPlayerName(), trimmedTarget, StringComparison.OrdinalIgnoreCase)); if ((Object)(object)val == (Object)null) { return list; } string matchedGuild = GetPlayerGuildName(val); if (!string.IsNullOrWhiteSpace(matchedGuild) && !list.Any([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string target) => string.Equals(target, matchedGuild, StringComparison.OrdinalIgnoreCase))) { list.Add(matchedGuild); } return list; } public static List GetLocalPlayerAllyRequestTargets(Player player) { List list = new List(); if ((Object)(object)player == (Object)null) { return list; } string playerGuildName = GetPlayerGuildName(player); if (!string.IsNullOrWhiteSpace(playerGuildName)) { list.Add(playerGuildName.Trim()); } string playerName = player.GetPlayerName(); if (!string.IsNullOrWhiteSpace(playerName) && !list.Any([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string target) => string.Equals(target, playerName, StringComparison.OrdinalIgnoreCase))) { list.Add(playerName.Trim()); } return list; } public static bool TryGetSenderGuild(long sender, out string guildName) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) guildName = string.Empty; if ((Object)(object)ZNet.instance == (Object)null) { return false; } foreach (PlayerInfo player in ZNet.instance.m_players) { if (TryGetPlayerInfoPeerId(player, out var peerId) && peerId == sender) { guildName = API.GetPlayerGuild(PlayerReference.fromPlayerInfo(player))?.Name ?? string.Empty; return true; } } return false; } private static bool TryGetPlayerInfoPeerId(PlayerInfo playerInfo, out long peerId) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) peerId = 0L; string[] obj = new string[6] { "m_host", "m_hostID", "m_peerID", "m_sender", "m_userID", "m_characterID" }; Type type = ((object)playerInfo).GetType(); string[] array = obj; foreach (string name in array) { FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null && TryConvertToLong(field.GetValue(playerInfo), out peerId)) { return true; } PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanRead && TryConvertToLong(property.GetValue(playerInfo, null), out peerId)) { return true; } } return false; } private static bool TryConvertToLong(object value, out long result) { result = 0L; if (value == null) { return false; } if (value is long num) { result = num; return true; } if (value is int num2) { result = num2; return true; } if (value is uint num3) { result = num3; return true; } if (value is ulong num4 && num4 <= long.MaxValue) { result = (long)num4; return true; } return long.TryParse(value.ToString(), out result); } public static void InternalSetAlly(string key, bool ally) { string path = Path.Combine(Paths.ConfigPath, "TameGuildWarsAllies.txt"); if (!File.Exists(path)) { File.WriteAllText(path, ""); } List list = (from line in File.ReadAllLines(path) select line.Trim() into line where line.Length > 0 select line).ToList(); int count = list.Count; if (ally) { if (!list.Any([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string line) => string.Equals(line, key, StringComparison.OrdinalIgnoreCase))) { list.Add(key); } AllianceGraceUntilTicks[key] = DateTime.UtcNow.AddSeconds(10.0).Ticks; float num = ((TameGuildWarsPlugin.ConfigAllyAddCooldownSeconds != null) ? Mathf.Max(0f, TameGuildWarsPlugin.ConfigAllyAddCooldownSeconds.Value) : 0f); if (num > 0f) { AllyAddCooldownUntilTicks[key] = DateTime.UtcNow.AddSeconds(num).Ticks; } else { AllyAddCooldownUntilTicks.Remove(key); } } else { list.RemoveAll([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (string line) => string.Equals(line, key, StringComparison.OrdinalIgnoreCase)); AllianceGraceUntilTicks.Remove(key); AllyAddCooldownUntilTicks.Remove(key); } File.WriteAllLines(path, list); TameGuildWarsPlugin.SyncedAllies.Value = string.Join("\n", list); TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)string.Format("InternalSetAlly {0}: key='{1}', before={2}, after={3}.", ally ? "add" : "remove", key, count, list.Count)); } public static List GetAlliesForGuild(string myGuild) { List list = new List(); if (string.IsNullOrEmpty(myGuild)) { return list; } if (TameGuildWarsPlugin.SyncedAllies.Value == null) { return list; } string text = "tgw_ally_" + myGuild.Trim().ToLowerInvariant() + "_"; string[] array = TameGuildWarsPlugin.SyncedAllies.Value.Split(new char[2] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text2 = array[i].Trim(); if (text2.StartsWith(text, StringComparison.OrdinalIgnoreCase)) { list.Add(text2.Substring(text.Length)); } } return list; } public static Sprite GetGuildIcon(string guildName) { if (string.IsNullOrEmpty(guildName)) { return null; } if (API.IsLoaded()) { Guild guild = API.GetGuild(guildName); if (guild != null) { return API.GetGuildIcon(guild); } } return null; } public static bool API_SetTamedGuildMobData(string payload, Character character) { TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!((Component)character).TryGetComponent(ref tamedGuildMob)) { return false; } tamedGuildMob.RestoreMobdata(payload); return true; } public static bool API_CanCaptureCreature(Player player, Character character) { return true; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func)Input.GetKey); } return false; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func)Input.GetKey); } return false; } } public enum GuildMobStance { Guard, Stay, GuardWard, Follow, FollowAttack, Static } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] public class TamedGuildMob : MonoBehaviour, Interactable { private static readonly HashSet ActiveGuildMobs = new HashSet(); private ZNetView m_nview; private BaseAI m_baseAI; public HitData m_lastHit; private const string ZdoGuildName = "TGW_GuildName"; private const string ZdoTamerId = "TGW_TamerID"; private const string ZdoTamerName = "TGW_TamerName"; private const string ZdoObedience = "TGW_Obedience"; private const string ZdoStance = "TGW_Stance"; private const string ZdoConfusion = "TGW_Confusion"; private const string ZdoAlarmPlayerId = "TGW_AlarmPlayerId"; private const string ZdoAlarmRaisedTicks = "TGW_AlarmRaisedTicks"; private const string ZdoFollowTargetPlayerId = "TGW_FollowTargetPlayerId"; private const string ZdoCommandLock = "TGW_CommandLock"; private const string ZdoSkipDecay = "TGW_SkipDecay"; private readonly float ObedienceRecoverRate = 1f; private readonly float MaxObedience = 100f; private readonly float UpdateInterval = 10f; private readonly float TamerProximityRange = 50f; private readonly float ObedienceDrop = 10f; private readonly float childStartingObedience = 20f; private float _swarmCheckTimer; private Character _rememberedSwarmTarget; private Vector3 _rememberedSwarmTargetLastKnownPos = Vector3.zero; private float _rememberedSwarmTargetUntil; private float _swarmTargetReassertTimer; private float _wardPatrolAngle; private Vector3 _currentWardPatrolPoint = Vector3.zero; private float _wardPatrolStuckTimer; private Vector3 _stanceAnchorPoint = Vector3.zero; private bool _ordersRefreshedForCurrentLoad; private float _stanceUpdateTimer; public MonsterAI MonsterAi { get; private set; } public Character Character { get; private set; } private float GuardMaxDistance => Mathf.Max(0f, TameGuildWarsPlugin.ConfigGuardLeashDistance.Value); private float ObedienceDecayRate => TameGuildWarsPlugin.ConfigObedienceDecayRate.Value; private float SwarmCheckInterval => Mathf.Max(0.1f, TameGuildWarsPlugin.ConfigSwarmCheckInterval.Value); private float SwarmRadius => Mathf.Max(0f, TameGuildWarsPlugin.ConfigSwarmRadius.Value); private bool MobActionLoggingEnabled { get { if (TameGuildWarsPlugin.ConfigMobActionLogging != null) { return TameGuildWarsPlugin.ConfigMobActionLogging.Value == TameGuildWarsPlugin.Toggle.On; } return false; } } public string GuildName { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return ""; } return m_nview.GetZDO().GetString("TGW_GuildName", ""); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_GuildName", value ?? ""); } } } public long TamerID { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0L; } return m_nview.GetZDO().GetLong("TGW_TamerID", 0L); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_TamerID", value); } } } public string TamerName { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return ""; } return m_nview.GetZDO().GetString("TGW_TamerName", ""); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_TamerName", value ?? ""); } } } public float Obedience { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0f; } return m_nview.GetZDO().GetFloat("TGW_Obedience", 0f); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_Obedience", Mathf.Clamp(value, 0f, MaxObedience)); } } } public GuildMobStance Stance { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return GuildMobStance.Guard; } return (GuildMobStance)m_nview.GetZDO().GetInt("TGW_Stance", 0); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_Stance", (int)value); } } } public float Confusion { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0f; } return m_nview.GetZDO().GetFloat("TGW_Confusion", 0f); } set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_Confusion", Mathf.Clamp(value, 0f, 100f)); } } } public long AlarmPlayerId { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0L; } return m_nview.GetZDO().GetLong("TGW_AlarmPlayerId", 0L); } set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid() && m_nview.IsOwner()) { m_nview.GetZDO().Set("TGW_AlarmPlayerId", value); } } } public long AlarmRaisedTicks { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0L; } return m_nview.GetZDO().GetLong("TGW_AlarmRaisedTicks", 0L); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid() && m_nview.IsOwner()) { m_nview.GetZDO().Set("TGW_AlarmRaisedTicks", value); } } } public bool CommandLocked { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return false; } return m_nview.GetZDO().GetBool("TGW_CommandLock", false); } set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_CommandLock", value); } } } public long FollowTargetPlayerId { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return 0L; } return m_nview.GetZDO().GetLong("TGW_FollowTargetPlayerId", 0L); } private set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_FollowTargetPlayerId", value); } } } public bool SkipDecay { get { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid()) { return false; } return m_nview.GetZDO().GetBool("TGW_SkipDecay", false); } set { if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { m_nview.GetZDO().Set("TGW_SkipDecay", value); } } } private void Awake() { MonsterAi = ((Component)this).GetComponent(); m_baseAI = ((Component)this).GetComponent(); Character = ((Component)this).GetComponent(); m_nview = ((Component)this).GetComponent(); _wardPatrolAngle = Random.Range(0f, 360f); m_nview.Register("RPC_ObedienceDrop", (Action)RPC_ObedienceDrop); m_nview.Register("RPC_TGW_AddConfusion", (Action)RPC_AddConfusion); if ((Object)(object)m_nview != (Object)null && m_nview.IsValid()) { ((MonoBehaviour)this).InvokeRepeating("UpdateObedience", Random.Range(1f, 5f), UpdateInterval); ((MonoBehaviour)this).InvokeRepeating("UpdateConfusion", Random.Range(1f, 5f), 2f); } } private void OnEnable() { ActiveGuildMobs.Add(this); _ordersRefreshedForCurrentLoad = false; ((MonoBehaviour)this).Invoke("RefreshOrdersForLoadedArea", 0.25f); } private void OnDisable() { ActiveGuildMobs.Remove(this); ((MonoBehaviour)this).CancelInvoke("RefreshOrdersForLoadedArea"); } public void RaiseAlarm(Character attacker) { if (!(Obedience <= 0f) && !((Object)(object)attacker == (Object)null) && !((Object)(object)attacker == (Object)(object)Character) && !((Object)(object)m_nview == (Object)null) && m_nview.IsValid() && m_nview.IsOwner()) { Player val = (Player)(object)((attacker is Player) ? attacker : null); bool num = (Object)(object)val != (Object)null; long num2 = (num ? val.GetPlayerID() : 0); long alarmPlayerId = AlarmPlayerId; long alarmRaisedTicks = AlarmRaisedTicks; long ticks = DateTime.UtcNow.Ticks; if (num) { AlarmPlayerId = num2; AlarmRaisedTicks = ticks; } LogMobAction("alarm raised on " + DescribeCharacter(attacker)); TryApplySwarmTarget(attacker, num2, ticks, "alarm"); if (!num || alarmPlayerId != num2 || alarmRaisedTicks == 0L || new TimeSpan(ticks - alarmRaisedTicks).TotalSeconds >= 1.0) { BroadcastSwarmAlarm(attacker, num2, ticks); } } } public void ClearAlarm() { if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid() && m_nview.IsOwner()) { bool num = AlarmPlayerId != 0L || AlarmRaisedTicks != 0; AlarmPlayerId = 0L; AlarmRaisedTicks = 0L; if (num) { LogMobAction("alarm cleared"); } } } private void BroadcastSwarmAlarm(Character attacker, long attackerPlayerId, long alarmTicks) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)attacker == (Object)null || attacker.IsDead() || string.IsNullOrEmpty(GuildName)) { return; } float num = SwarmRadius * SwarmRadius; Vector3 position = ((Component)this).transform.position; foreach (TamedGuildMob activeGuildMob in ActiveGuildMobs) { if (!((Object)(object)activeGuildMob == (Object)null) && !((Object)(object)activeGuildMob == (Object)(object)this) && !((Object)(object)activeGuildMob.Character == (Object)null) && activeGuildMob.IsSameGuild(GuildName)) { Vector3 val = ((Component)activeGuildMob).transform.position - position; if (!(((Vector3)(ref val)).sqrMagnitude > num)) { activeGuildMob.TryApplySwarmTarget(attacker, attackerPlayerId, alarmTicks, "broadcast swarm"); } } } } private bool TryApplySwarmTarget(Character target, long alarmPlayerId, long alarmTicks, string source) { if ((Object)(object)target == (Object)null || target.IsDead()) { return false; } if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner()) { return false; } if ((Object)(object)MonsterAi == (Object)null || (Object)(object)Character == (Object)null || Character.IsDead()) { return false; } if (string.IsNullOrEmpty(GuildName) || Obedience <= 0f) { return false; } if (Stance == GuildMobStance.Stay || Stance == GuildMobStance.Follow) { return false; } if (target.IsPlayer()) { Player val = (Player)(object)((target is Player) ? target : null); if ((Object)(object)val == (Object)null || val.GetPlayerID() != alarmPlayerId || TargetingPatches.IsPlayerGhost(val)) { return false; } AlarmPlayerId = alarmPlayerId; AlarmRaisedTicks = alarmTicks; } Character targetCreature = ((BaseAI)MonsterAi).GetTargetCreature(); if (!ShouldPrioritizeSwarmTarget(targetCreature, target, alarmPlayerId)) { return false; } ForceCombatTarget(target); Character targetCreature2 = ((BaseAI)MonsterAi).GetTargetCreature(); if ((Object)(object)targetCreature2 == (Object)(object)target && (Object)(object)targetCreature != (Object)(object)target) { RememberSwarmTarget(target); LogMobAction(source + ": targeting " + DescribeCharacter(target) + (((Object)(object)targetCreature != (Object)null) ? (" instead of " + DescribeCharacter(targetCreature)) : string.Empty)); } else if ((Object)(object)targetCreature2 != (Object)(object)target) { LogMobAction(source + ": failed to hold target " + DescribeCharacter(target)); } return (Object)(object)targetCreature2 == (Object)(object)target; } private void RememberSwarmTarget(Character target) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)target == (Object)null || target.IsDead()) { ClearRememberedSwarmTarget(); return; } _rememberedSwarmTarget = target; _rememberedSwarmTargetLastKnownPos = ((Component)target).transform.position; _rememberedSwarmTargetUntil = Time.time + Mathf.Max(5f, TameGuildWarsPlugin.ConfigAlarmDurationSeconds.Value); } private void ClearTargetAndAlert(bool alerted) { if (!((Object)(object)MonsterAi == (Object)null)) { Traverse.Create((object)MonsterAi).Field("m_targetCreature").SetValue((object)null); ((BaseAI)MonsterAi).SetAlerted(alerted); ClearRememberedSwarmTarget(); } } private void ClearRememberedSwarmTarget() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) _rememberedSwarmTarget = null; _rememberedSwarmTargetLastKnownPos = Vector3.zero; _rememberedSwarmTargetUntil = 0f; _swarmTargetReassertTimer = 0f; } public void ClearGhostAggro() { ClearAlarm(); ClearTargetAndAlert(alerted: false); } private bool HasRememberedSwarmTarget() { if ((Object)(object)_rememberedSwarmTarget != (Object)null) { return Time.time <= _rememberedSwarmTargetUntil; } return false; } private void RefreshRememberedSwarmTargetPosition() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_rememberedSwarmTarget != (Object)null && !_rememberedSwarmTarget.IsDead()) { _rememberedSwarmTargetLastKnownPos = ((Component)_rememberedSwarmTarget).transform.position; } } private void ApplyRememberedSwarmChaseState() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)MonsterAi == (Object)null)) { RefreshRememberedSwarmTargetPosition(); ((BaseAI)MonsterAi).SetAlerted(true); Traverse.Create((object)MonsterAi).Field("m_lastKnownTargetPos").SetValue((object)_rememberedSwarmTargetLastKnownPos); ((BaseAI)MonsterAi).SetPatrolPoint(_rememberedSwarmTargetLastKnownPos); } } private void MaintainRememberedSwarmTarget(float dt) { if ((Object)(object)_rememberedSwarmTarget == (Object)null) { return; } if (_rememberedSwarmTarget.IsPlayer() && TargetingPatches.IsPlayerGhost((Player)/*isinst with value type is only supported in some contexts*/)) { ClearRememberedSwarmTarget(); return; } if (_rememberedSwarmTarget.IsDead() || Time.time > _rememberedSwarmTargetUntil) { LogMobAction("forgot swarm target " + DescribeCharacter(_rememberedSwarmTarget)); ClearRememberedSwarmTarget(); return; } if ((Object)(object)MonsterAi == (Object)null || (Object)(object)Character == (Object)null || Character.IsDead() || Obedience <= 0f || Stance == GuildMobStance.Stay || Stance == GuildMobStance.Follow) { ClearRememberedSwarmTarget(); return; } ApplyRememberedSwarmChaseState(); if (!((Object)(object)((BaseAI)MonsterAi).GetTargetCreature() == (Object)(object)_rememberedSwarmTarget)) { _swarmTargetReassertTimer += dt; if (!(_swarmTargetReassertTimer < 0.5f)) { _swarmTargetReassertTimer = 0f; LogMobAction("reasserting swarm target " + DescribeCharacter(_rememberedSwarmTarget) + " after AI cleared target"); ForceCombatTarget(_rememberedSwarmTarget); ApplyRememberedSwarmChaseState(); } } } private void ForceCombatTarget(Character target) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) Traverse obj = Traverse.Create((object)MonsterAi); ((BaseAI)MonsterAi).SetAlerted(true); MonsterAi.SetTarget(target); obj.Field("m_targetCreature").SetValue((object)target); obj.Field("m_lastKnownTargetPos").SetValue((object)((Component)target).transform.position); } private void LogMobAction(string action) { if (MobActionLoggingEnabled) { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("[GuildMob:" + (Character?.m_name ?? ((Object)this).name) + "] " + action)); } } public string GetDebugHoverText() { if (!MobActionLoggingEnabled) { return string.Empty; } List list = new List(); Character val = (((Object)(object)MonsterAi != (Object)null) ? ((BaseAI)MonsterAi).GetTargetCreature() : null); if ((Object)(object)val != (Object)null && !val.IsDead()) { list.Add("Target: " + DescribeCharacter(val)); } else { list.Add("Target: none"); } if (AlarmPlayerId != 0L) { Player player = Player.GetPlayer(AlarmPlayerId); list.Add("Alarm: " + (((Object)(object)player != (Object)null) ? player.GetPlayerName() : AlarmPlayerId.ToString())); } list.Add($"Stance: {Stance}"); if (HasRememberedSwarmTarget()) { list.Add("Remembered: " + DescribeCharacter(_rememberedSwarmTarget)); } GameObject val2 = (((Object)(object)MonsterAi != (Object)null) ? MonsterAi.GetFollowTarget() : null); string text = ((Stance == GuildMobStance.Follow || Stance == GuildMobStance.FollowAttack) ? string.Empty : " (non-follow)"); list.Add("Follow: " + (((Object)(object)val2 != (Object)null) ? ((Object)val2).name : "none") + text); return "\nDebug: " + string.Join(" | ", list); } private static string DescribeCharacter(Character character) { if ((Object)(object)character == (Object)null) { return "none"; } string text = ((!string.IsNullOrEmpty(character.m_name)) ? character.m_name : ((Object)character).name); if (!character.IsPlayer()) { return text; } return "player " + text; } private bool ShouldPrioritizeSwarmTarget(Character currentTarget, Character swarmTarget, long swarmAlarmPlayerId) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)swarmTarget == (Object)null || swarmTarget.IsDead()) { return false; } if ((Object)(object)currentTarget == (Object)null || currentTarget.IsDead() || (Object)(object)currentTarget == (Object)(object)swarmTarget) { return true; } bool flag = IsAlarmedPlayerTarget(swarmTarget, swarmAlarmPlayerId); bool flag2 = IsAlarmedPlayerTarget(currentTarget, AlarmPlayerId); if (flag != flag2) { return flag; } Vector3 val = ((Component)currentTarget).transform.position - ((Component)this).transform.position; float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude; val = ((Component)swarmTarget).transform.position - ((Component)this).transform.position; return ((Vector3)(ref val)).sqrMagnitude + 16f < sqrMagnitude; } private static bool IsAlarmedPlayerTarget(Character target, long alarmPlayerId) { if (alarmPlayerId == 0L || (Object)(object)target == (Object)null || !target.IsPlayer()) { return false; } Player val = (Player)(object)((target is Player) ? target : null); if ((Object)(object)val != (Object)null) { return val.GetPlayerID() == alarmPlayerId; } return false; } public void CycleStance(Player player) { int newStance = (int)(Stance + 1) % 6; SetStance((GuildMobStance)newStance, player); } public void ToggleCommandLock(Player player) { CommandLocked = !CommandLocked; ((Character)player).Message((MessageType)2, Character.m_name + " command lock: " + (CommandLocked ? "On" : "Off"), 0, (Sprite)null); if ((Object)(object)m_nview != (Object)null && m_nview.IsValid() && !m_nview.IsOwner()) { m_nview.ClaimOwnership(); } } public void ToggleSkipDecay(Player player) { SkipDecay = !SkipDecay; ((Character)player).Message((MessageType)2, Character.m_name + " skip obedience decay: " + (SkipDecay ? "On" : "Off"), 0, (Sprite)null); if ((Object)(object)m_nview != (Object)null && m_nview.IsValid() && !m_nview.IsOwner()) { m_nview.ClaimOwnership(); } } public bool SetStance(GuildMobStance newStance, Player player = null, bool notifyPlayer = true) { //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player != (Object)null) { if (Obedience <= 0f) { if (notifyPlayer) { ((Character)player).Message((MessageType)2, Character.m_name + " will not obey new orders.", 0, (Sprite)null); } return false; } if (CommandLocked) { if (notifyPlayer) { ((Character)player).Message((MessageType)2, Character.m_name + " command is locked!", 0, (Sprite)null); } return false; } } Stance = newStance; if ((Object)(object)player != (Object)null && notifyPlayer) { ((Character)player).Message((MessageType)2, $"{Character.m_name} order: {newStance}", 0, (Sprite)null); } string arg = (((Object)(object)player != (Object)null) ? player.GetPlayerName() : "system"); LogMobAction($"stance changed to {newStance} by {arg}"); if ((Object)(object)m_nview != (Object)null && m_nview.IsValid() && !m_nview.IsOwner()) { m_nview.ClaimOwnership(); } switch (newStance) { case GuildMobStance.Guard: case GuildMobStance.Stay: case GuildMobStance.Static: _stanceAnchorPoint = ((Component)this).transform.position; FollowTargetPlayerId = 0L; ClearNonFollowOrders(_stanceAnchorPoint, newStance == GuildMobStance.Stay || newStance == GuildMobStance.Static); ((BaseAI)MonsterAi).SetPatrolPoint(_stanceAnchorPoint); break; case GuildMobStance.GuardWard: FollowTargetPlayerId = 0L; ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: false); break; case GuildMobStance.Follow: case GuildMobStance.FollowAttack: { Player val = player ?? Player.m_localPlayer; FollowTargetPlayerId = (((Object)(object)val != (Object)null) ? val.GetPlayerID() : TamerID); SetVanillaTameableFollowState(val); if ((Object)(object)player != (Object)null) { MonsterAi.SetFollowTarget(((Component)player).gameObject); ((BaseAI)MonsterAi).ResetPatrolPoint(); break; } MonsterAI monsterAi = MonsterAi; Player localPlayer = Player.m_localPlayer; monsterAi.SetFollowTarget((localPlayer != null) ? ((Component)localPlayer).gameObject : null); ((BaseAI)MonsterAi).ResetPatrolPoint(); break; } } return true; } private void EnsureStanceAnchor() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (_stanceAnchorPoint == Vector3.zero) { _stanceAnchorPoint = ((Component)this).transform.position; } } private void EnforceStanceLeash(float maxDistance, bool clearCombatTarget) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) EnsureStanceAnchor(); if (!(Vector3.Distance(((Component)this).transform.position, _stanceAnchorPoint) <= maxDistance)) { ClearNonFollowOrders(_stanceAnchorPoint, clearCombatState: false); if (clearCombatTarget && !((Object)(object)((BaseAI)MonsterAi).GetTargetCreature() == (Object)null)) { Traverse.Create((object)MonsterAi).Field("m_targetCreature").SetValue((object)null); Traverse.Create((object)MonsterAi).Method("SetAlerted", new object[1] { false }).GetValue(); } } } private void RefreshFollowTarget() { long num = FollowTargetPlayerId; if (num == 0L) { num = TamerID; if (num != 0L) { FollowTargetPlayerId = num; } } if (num == 0L) { ClearVanillaTameableFollowState(); MonsterAi.SetFollowTarget((GameObject)null); return; } Player player = Player.GetPlayer(num); if ((Object)(object)player == (Object)null) { MonsterAi.SetFollowTarget((GameObject)null); return; } SetVanillaTameableFollowState(player); if ((Object)(object)MonsterAi.GetFollowTarget() != (Object)(object)((Component)player).gameObject) { MonsterAi.SetFollowTarget(((Component)player).gameObject); ((BaseAI)MonsterAi).ResetPatrolPoint(); } } private void ClearNonFollowOrders(Vector3 patrolPoint, bool clearCombatState) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)MonsterAi == (Object)null)) { GameObject followTarget = MonsterAi.GetFollowTarget(); if ((Object)(object)followTarget != (Object)null) { LogMobAction($"clearing stale follow target {((Object)followTarget).name} for stance {Stance}"); } ClearVanillaTameableFollowState(); MonsterAi.SetFollowTarget((GameObject)null); ((BaseAI)MonsterAi).ResetPatrolPoint(); ((BaseAI)MonsterAi).SetPatrolPoint(patrolPoint); if (clearCombatState) { ClearAlarm(); ClearRememberedSwarmTarget(); ClearTargetAndAlert(alerted: false); } } } private void ClearVanillaTameableFollowState() { SetVanillaTameableFollowState(null); } private void SetVanillaTameableFollowState(Player followPlayer) { if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid()) { ZDO zDO = m_nview.GetZDO(); if (zDO != null) { zDO.Set(ZDOVars.s_follow, ((Object)(object)followPlayer != (Object)null) ? followPlayer.GetPlayerName() : string.Empty); } } } private void RefreshOrdersForLoadedArea() { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) if (_ordersRefreshedForCurrentLoad || (Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner() || (Object)(object)MonsterAi == (Object)null || (Object)(object)Character == (Object)null || !Character.IsTamed()) { return; } _ordersRefreshedForCurrentLoad = true; if (Obedience <= 0f) { ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: true); LogMobAction("refreshed loaded orders: no obedience"); return; } switch (Stance) { case GuildMobStance.Guard: EnsureStanceAnchor(); ClearRememberedSwarmTarget(); ClearNonFollowOrders(_stanceAnchorPoint, clearCombatState: false); break; case GuildMobStance.Stay: case GuildMobStance.Static: _stanceAnchorPoint = ((Component)this).transform.position; ClearNonFollowOrders(_stanceAnchorPoint, clearCombatState: true); break; case GuildMobStance.GuardWard: ClearRememberedSwarmTarget(); ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: false); break; case GuildMobStance.Follow: case GuildMobStance.FollowAttack: RefreshFollowTarget(); break; } LogMobAction($"refreshed loaded orders for stance {Stance}"); } public bool TryClaim(Player player, string guildName) { long playerID = player.GetPlayerID(); if ((TamerID == 0L || Obedience <= 0f || TamerID == playerID) && guildName != "No Guild") { TamerID = playerID; TamerName = player.GetPlayerName(); GuildName = guildName; Obedience = MaxObedience; ClearAlarm(); ClearTargetAndAlert(alerted: false); if (!Object.op_Implicit((Object)(object)((Component)this).gameObject.GetComponent())) { return true; } SetStance(GuildMobStance.Guard); return true; } return false; } public bool TryChangeTamer(Player player) { long playerID = player.GetPlayerID(); if (Obedience <= 0f && TamerID != playerID) { TamerID = playerID; TamerName = player.GetPlayerName(); ClearAlarm(); ClearTargetAndAlert(alerted: false); return true; } return false; } public bool TryChangeGuild(Player player, string newGuildName) { if (TamerID == player.GetPlayerID() && Obedience > 0f) { GuildName = newGuildName; ClearAlarm(); ClearTargetAndAlert(alerted: false); return true; } return false; } public bool IsSameGuild(string otherGuildName) { string guildName = GuildName; if (string.IsNullOrEmpty(guildName) || string.IsNullOrEmpty(otherGuildName)) { return false; } return guildName == otherGuildName; } private void UpdateObedience() { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_nview == (Object)null || !m_nview.IsValid() || !m_nview.IsOwner() || SkipDecay) { return; } long tamerID = TamerID; bool flag = tamerID == 0; float obedience = Obedience; if (flag && obedience <= 0f) { return; } bool flag2 = false; Player val = null; string text = string.Empty; if (!flag) { val = Player.GetPlayer(tamerID); if ((Object)(object)val != (Object)null) { text = GuildUtils.GetPlayerGuildName(val); if (Vector3.Distance(((Component)this).transform.position, ((Component)val).transform.position) <= TamerProximityRange) { flag2 = true; } } } if (flag2) { if (obedience < MaxObedience) { Obedience = obedience + ObedienceRecoverRate; } return; } float num = ObedienceDecayRate; bool flag3 = false; bool flag4 = false; if (!flag) { foreach (Player allPlayer in Player.GetAllPlayers()) { if (Vector3.Distance(((Component)this).transform.position, ((Component)allPlayer).transform.position) <= TamerProximityRange) { string playerGuildName = GuildUtils.GetPlayerGuildName(allPlayer); if (!string.IsNullOrEmpty(playerGuildName) && playerGuildName == GuildName && playerGuildName != "No Guild") { flag3 = true; } else { flag4 = true; } } } } if (flag4 && !flag3) { num *= TameGuildWarsPlugin.ConfigNonGuildMemberDecayMultiplier.Value; } int num2; int num3; if (!string.IsNullOrEmpty(text)) { num2 = ((text == "No Guild") ? 1 : 0); if (num2 == 0 && !string.IsNullOrEmpty(GuildName)) { num3 = ((text != GuildName) ? 1 : 0); goto IL_01ae; } } else { num2 = 1; } num3 = 0; goto IL_01ae; IL_01ae: bool flag5 = (byte)num3 != 0; if (((uint)num2 | (flag5 ? 1u : 0u)) != 0) { num *= TameGuildWarsPlugin.ConfigNoGuildDecayMultiplier.Value; } float num4 = obedience - num; if (num4 <= 0f) { Obedience = 0f; ClearAlarm(); TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"Mob {Character.m_name} lost obedience to tamer {tamerID} and reverted to neutral."); } else { Obedience = num4; } } private void RPC_ObedienceDrop(long uid) { if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid() && m_nview.IsOwner() && !string.IsNullOrEmpty(GuildName) && !(Obedience <= 0f)) { if (Obedience <= ObedienceDrop) { Obedience = 0f; } Obedience -= ObedienceDrop; } } private void RPC_AddConfusion(long uid, float amount) { if (!((Object)(object)m_nview == (Object)null) && m_nview.IsValid() && m_nview.IsOwner() && !(amount <= 0f)) { Confusion = Mathf.Clamp(Confusion + amount, 0f, 100f); } } private void UpdateConfusion() { if (!((Object)(object)m_nview != (Object)null) || !m_nview.IsValid() || !m_nview.IsOwner()) { return; } float confusion = Confusion; if (!(confusion > 0f)) { return; } float num = TameGuildWarsPlugin.ConfigConfusionDurationSeconds.Value; if (num <= 0f) { num = 1f; } Confusion = Mathf.Max(0f, confusion - 100f / num * 2f); if (Confusion > 50f) { ClearAlarm(); if (Random.value < 0.3f) { List list = Character.GetAllCharacters().FindAll(IsValidConfusionTarget); if (list.Count > 0) { Character val = list[Random.Range(0, list.Count)]; ForceCombatTarget(val); LogMobAction("confused: targeting " + DescribeCharacter(val)); } else if (Random.value < 0.5f) { ClearTargetAndAlert(alerted: true); } } } else if ((Object)(object)MonsterAi != (Object)null && (Object)(object)((BaseAI)MonsterAi).GetTargetCreature() != (Object)null && AlarmPlayerId != 0L) { ClearAlarm(); } } private bool IsValidConfusionTarget(Character candidate) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)candidate == (Object)null || (Object)(object)candidate == (Object)(object)Character || candidate.IsDead()) { return false; } Vector3 val = ((Component)candidate).transform.position - ((Component)this).transform.position; if (((Vector3)(ref val)).sqrMagnitude > 900f) { return false; } if (candidate.IsPlayer() && TargetingPatches.IsPlayerGhost((Player)(object)((candidate is Player) ? candidate : null))) { return false; } return true; } public void UpdateSwarmAggro(float dt) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) MaintainRememberedSwarmTarget(dt); if (string.IsNullOrEmpty(GuildName) || Obedience <= 0f || Stance == GuildMobStance.Stay || Stance == GuildMobStance.Follow) { return; } _swarmCheckTimer += dt; if (_swarmCheckTimer < SwarmCheckInterval) { return; } _swarmCheckTimer = 0f; float num = SwarmRadius * SwarmRadius; Vector3 position = ((Component)this).transform.position; foreach (TamedGuildMob activeGuildMob in ActiveGuildMobs) { if ((Object)(object)activeGuildMob == (Object)null || (Object)(object)activeGuildMob == (Object)(object)this || (Object)(object)activeGuildMob.Character == (Object)null || (Object)(object)activeGuildMob.MonsterAi == (Object)null || !activeGuildMob.IsSameGuild(GuildName)) { continue; } Vector3 val = ((Component)activeGuildMob).transform.position - position; if (((Vector3)(ref val)).sqrMagnitude > num) { continue; } Character targetCreature = ((BaseAI)activeGuildMob.MonsterAi).GetTargetCreature(); if (!((Object)(object)targetCreature != (Object)null) || targetCreature.IsDead()) { continue; } bool flag = false; if (targetCreature.IsPlayer()) { Player val2 = (Player)(object)((targetCreature is Player) ? targetCreature : null); if ((Object)(object)val2 != (Object)null && activeGuildMob.AlarmPlayerId == val2.GetPlayerID()) { flag = true; } } else { flag = true; } if (flag) { TryApplySwarmTarget(targetCreature, activeGuildMob.AlarmPlayerId, activeGuildMob.AlarmRaisedTicks, "fallback swarm"); break; } } } public void UpdateStanceBehavior(float dt) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) RefreshOrdersForLoadedArea(); _stanceUpdateTimer += dt; if (_stanceUpdateTimer < 2f) { return; } _stanceUpdateTimer = 0f; UpdateAlarmState(); Character targetCreature = ((BaseAI)MonsterAi).GetTargetCreature(); if ((Object)(object)targetCreature != (Object)null && !((BaseAI)MonsterAi).IsEnemy(targetCreature)) { ClearAlarm(); ClearTargetAndAlert(alerted: false); } if (Obedience <= 0f) { ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: true); if ((Object)(object)((BaseAI)MonsterAi).GetTargetCreature() != (Object)null) { Traverse.Create((object)MonsterAi).Field("m_targetCreature").SetValue((object)null); Traverse.Create((object)MonsterAi).Method("SetAlerted", new object[1] { false }).GetValue(); } } else if (HasRememberedSwarmTarget()) { ApplyRememberedSwarmChaseState(); } else if (Stance == GuildMobStance.GuardWard) { ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: false); if ((Object)(object)((BaseAI)MonsterAi).GetTargetCreature() != (Object)null) { return; } PrivateArea val = null; float num = float.MaxValue; foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if (allArea.IsEnabled()) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)allArea).transform.position); if (num2 < num) { num = num2; val = allArea; } } } if ((Object)(object)val != (Object)null) { float radius = val.m_radius; float num3 = Vector3.Distance(((Component)this).transform.position, _currentWardPatrolPoint); _wardPatrolStuckTimer += dt; if (_currentWardPatrolPoint == Vector3.zero || num3 < 6f || _wardPatrolStuckTimer > 20f) { _wardPatrolStuckTimer = 0f; _wardPatrolAngle += Random.Range(30f, 60f); if (_wardPatrolAngle >= 360f) { _wardPatrolAngle -= 360f; } float num4 = _wardPatrolAngle * ((float)Math.PI / 180f); _currentWardPatrolPoint = ((Component)val).transform.position + new Vector3(Mathf.Cos(num4) * radius, 0f, Mathf.Sin(num4) * radius); float y = default(float); if ((Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetSolidHeight(_currentWardPatrolPoint, ref y, 1000)) { _currentWardPatrolPoint.y = y; } } ((BaseAI)MonsterAi).SetPatrolPoint(_currentWardPatrolPoint); } else { ((BaseAI)MonsterAi).SetPatrolPoint(((Component)this).transform.position); } } else if (Stance == GuildMobStance.Stay) { ClearNonFollowOrders(((Component)this).transform.position, clearCombatState: true); if ((Object)(object)((BaseAI)MonsterAi).GetTargetCreature() != (Object)null) { Traverse.Create((object)MonsterAi).Field("m_targetCreature").SetValue((object)null); Traverse.Create((object)MonsterAi).Method("SetAlerted", new object[1] { false }).GetValue(); } } else if (Stance == GuildMobStance.Guard) { EnforceStanceLeash(GuardMaxDistance, clearCombatTarget: true); ClearNonFollowOrders((_stanceAnchorPoint == Vector3.zero) ? ((Component)this).transform.position : _stanceAnchorPoint, clearCombatState: false); } else if (Stance == GuildMobStance.Follow || Stance == GuildMobStance.FollowAttack) { RefreshFollowTarget(); } } public bool Interact(Humanoid user, bool hold, bool alt) { Tameable component = ((Component)this).GetComponent(); if (Object.op_Implicit((Object)(object)component)) { return component.Interact(user, hold, alt); } if (!m_nview.IsValid() || hold || (Object)(object)Character == (Object)null) { return false; } if (!Character.IsTamed()) { return false; } Player val = (Player)(object)((user is Player) ? user : null); if ((Object)(object)val == (Object)null || !Character.IsTamed()) { return true; } TamedGuildMob component2 = ((Component)this).GetComponent(); if ((Object)(object)component2 != (Object)null) { long playerID = val.GetPlayerID(); long tamerID = component2.TamerID; float obedience = component2.Obedience; string text = GuildUtils.GetPlayerGuildName(val); if (string.IsNullOrEmpty(text)) { text = "No Guild"; } if (tamerID == 0L || obedience <= 0f) { if (tamerID != 0L && tamerID != playerID) { if (!hold) { ((Character)val).Message((MessageType)2, "This beast is wild, but belongs to another.", 0, (Sprite)null); } return false; } if ((Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307)) && text != "No Guild" && component2.TryClaim(val, text)) { ((Character)val).Message((MessageType)2, "Mob claimed for guild: " + text, 0, (Sprite)null); return false; } } else if (tamerID == playerID && text != component2.GuildName && text != "No Guild") { if (alt) { return true; } if (component2.TryChangeGuild(val, text)) { ((Character)val).Message((MessageType)2, "Mob updated to guild: " + text, 0, (Sprite)null); return false; } } } return false; } public bool UseItem(Humanoid user, ItemData item) { return false; } private void UpdateAlarmState() { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) if (AlarmPlayerId == 0L) { return; } float num = Mathf.Max(0f, TameGuildWarsPlugin.ConfigAlarmDurationSeconds.Value); if (num == 0f) { ClearAlarm(); return; } long alarmRaisedTicks = AlarmRaisedTicks; if (alarmRaisedTicks > 0) { TimeSpan timeSpan = new TimeSpan(DateTime.UtcNow.Ticks - alarmRaisedTicks); if (timeSpan.TotalSeconds >= (double)num) { ClearAlarm(); return; } } Player player = Player.GetPlayer(AlarmPlayerId); if ((Object)(object)player == (Object)null) { return; } if (TargetingPatches.IsPlayerGhost(player)) { ClearAlarm(); return; } float num2 = Mathf.Max(0f, TameGuildWarsPlugin.ConfigAlarmLeashDistance.Value); if (num2 > 0f && Vector3.Distance(((Component)this).transform.position, ((Component)player).transform.position) > num2) { ClearAlarm(); } } public void inheritGuild(TamedGuildMob fromTGM, float obedience = -1f, bool newTamer = true) { if (!((Object)(object)fromTGM == (Object)null) && fromTGM.GuildName != null) { GuildName = fromTGM.GuildName; if (obedience >= 0f) { Obedience = obedience; } else { Obedience = childStartingObedience; } if (newTamer) { FindNearestTamer(); return; } TamerID = fromTGM.TamerID; TamerName = fromTGM.TamerName; } } public void EggStart(EggGrow growup) { if (!((Object)(object)growup == (Object)null)) { Obedience = childStartingObedience; FindNearestTamer(); } } private bool FindNearestTamer() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if (TamerID != 0L) { return true; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"Creature:{((Object)this).name}, Guild:{GuildName}, loc:{((Component)this).transform.position}, obedience:{Obedience}"); List allPlayers = Player.GetAllPlayers(); Player val = null; float num = 999999f; float num2 = 20f; Vector3 position = ((Component)this).transform.position; bool flag = string.IsNullOrEmpty(GuildName); foreach (Player item in allPlayers) { float num3 = Vector3.Distance(((Component)item).transform.position, position); if (num3 < num && num3 < num2 && (flag || IsSameGuild(GuildUtils.GetPlayerGuildName(item)))) { val = item; num = num3; } } if ((Object)(object)val == (Object)null) { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)"No guild member in range"); if ((Object)(object)((Component)this).GetComponent() != (Object)null) { ((MonoBehaviour)this).Invoke("FindNearestTamer", 10f); return false; } return false; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"Nearest tamer is {((Character)val).m_name} and is {num} away"); float obedience = Obedience; Obedience = 0f; if (TryClaim(val, GuildUtils.GetPlayerGuildName(val))) { Obedience = obedience; return true; } Obedience = obedience; ((MonoBehaviour)this).Invoke("FindNearestTamer", 10f); return false; } public string getGuildMobData() { return string.Concat(string.Concat(string.Concat(string.Concat(Obedience + ":", GuildName, ":"), TamerName, ":"), TamerID.ToString(), ":"), Confusion.ToString()); } public void RestoreMobdata(string payload) { string[] array = payload.Split(new char[1] { ':' }); if (array.Count() > 0 && float.TryParse(array[0], out var result)) { Obedience = result; } else { Obedience = 0f; } if (array.Count() > 1) { GuildName = array[1]; } if (array.Count() > 2) { TamerName = array[2]; } if (array.Count() > 3 && long.TryParse(array[3], out var result2)) { TamerID = result2; } if (array.Count() > 4 && float.TryParse(array[4], out var result3)) { Confusion = result3; } } } [HarmonyPatch(typeof(MonsterAI))] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] public static class MonsterAIPatches { [HarmonyPostfix] [HarmonyPatch(typeof(BaseAI), "Awake")] public static void AwakePostfix(BaseAI __instance) { if (((Component)__instance).GetComponent().IsTamed()) { TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!((Component)__instance).TryGetComponent(ref tamedGuildMob)) { tamedGuildMob = ((Component)__instance).gameObject.AddComponent(); } if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent()) && tamedGuildMob.TamerID == 0L) { ((MonoBehaviour)tamedGuildMob).Invoke("FindNearestTamer", 3f); } } } [HarmonyPrefix] [HarmonyPatch(typeof(BaseAI), "UpdateAI")] public static bool UpdateAIPrefix(BaseAI __instance) { if (!__instance.m_nview.IsValid()) { return true; } if (!__instance.m_nview.IsOwner()) { return true; } TamedGuildMob component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null && component.Stance == GuildMobStance.Static) { __instance.StopMoving(); return false; } return true; } [HarmonyPrefix] [HarmonyPatch("UpdateAI")] public static bool UpdateAIPrefix(MonsterAI __instance, float dt) { if ((Object)(object)((BaseAI)__instance).m_nview == (Object)null || !((BaseAI)__instance).m_nview.IsValid() || !((BaseAI)__instance).m_nview.IsOwner() || !((BaseAI)__instance).m_character.m_tamed) { return true; } Character targetCreature = ((BaseAI)__instance).GetTargetCreature(); if ((Object)(object)targetCreature != (Object)null && targetCreature.IsPlayer() && TargetingPatches.IsPlayerGhost((Player)(object)((targetCreature is Player) ? targetCreature : null))) { TamedGuildMob component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null) { component.ClearGhostAggro(); } else { Traverse obj = Traverse.Create((object)__instance); obj.Field("m_targetCreature").SetValue((object)null); obj.Method("SetAlerted", new object[1] { false }).GetValue(); } } TamedGuildMob component2 = ((Component)__instance).GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.UpdateSwarmAggro(dt); component2.UpdateStanceBehavior(dt); } return true; } } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] public static class ProcreationPatches { [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [HarmonyPatch(typeof(Procreation), "Procreate")] public static class InterceptProcreationAddGuild { private static GameObject OnCreateChild(GameObject child, Procreation _proc) { Character component = child.GetComponent(); TamedGuildMob component2 = ((Component)_proc).gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return child; } if (!Object.op_Implicit((Object)(object)component2)) { return child; } TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!child.gameObject.TryGetComponent(ref tamedGuildMob)) { tamedGuildMob = child.gameObject.AddComponent(); } tamedGuildMob.inheritGuild(component2); return child; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo procreationHook = AccessTools.DeclaredMethod(typeof(InterceptProcreationAddGuild), "OnCreateChild", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); List codes = new List(instructions); bool setProcHook = true; for (int i = 0; i < codes.Count; i++) { if (setProcHook && codes[i].opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(codes[i], (MemberInfo)instantiator)) { yield return codes[i]; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)procreationHook); setProcHook = false; i++; } yield return codes[i]; } } } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [HarmonyPatch(typeof(Growup), "GrowUpdate")] public static class InterceptGrowup { private static GameObject OnGrowup(GameObject adult, Growup growup) { Character component = adult.GetComponent(); TamedGuildMob component2 = ((Component)growup).gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return adult; } if (!Object.op_Implicit((Object)(object)component2)) { return adult; } TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!adult.gameObject.TryGetComponent(ref tamedGuildMob)) { tamedGuildMob = adult.gameObject.AddComponent(); } tamedGuildMob.inheritGuild(component2, component2.Obedience, newTamer: false); return adult; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo growupHook = AccessTools.DeclaredMethod(typeof(InterceptGrowup), "OnGrowup", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); foreach (CodeInstruction instruction in instructions) { yield return instruction; if (instruction.opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)instantiator)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)growupHook); } } } } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [HarmonyPatch(typeof(EggGrow), "GrowUpdate")] public static class InterceptEggGrowup { private static GameObject OnEggGrowup(GameObject adult, EggGrow growup) { Character component = adult.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return adult; } component.SetTamed(growup.m_tamed); TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!adult.TryGetComponent(ref tamedGuildMob)) { tamedGuildMob = adult.gameObject.AddComponent(); } if (Object.op_Implicit((Object)(object)adult.GetComponent()) && tamedGuildMob.TamerID == 0L) { tamedGuildMob.EggStart(growup); } return adult; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo growupHook = AccessTools.DeclaredMethod(typeof(InterceptEggGrowup), "OnEggGrowup", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); foreach (CodeInstruction instruction in instructions) { yield return instruction; if (instruction.opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)instantiator)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)growupHook); } } } } } internal static class TamedGuildMobVisuals { [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(1)] internal const string UnclaimedTameColor = "#ADFF2F"; } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] public sealed class GuildIconUiRefs : MonoBehaviour { public RectTransform RectTransform; public Image Image; } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [HarmonyPatch(typeof(Tameable))] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] public static class TamedMobPatches { private const string ZdoItemDropGuild = "TGW_Guild"; private const int MaxConsumeGuildDist = 30; private static readonly Regex RichTextTagRegex = new Regex("<.*?>", RegexOptions.Compiled); internal static string SanitizeGuildText(string value) { if (string.IsNullOrEmpty(value)) { return string.Empty; } return RichTextTagRegex.Replace(value, string.Empty).Trim(); } private static TamedGuildMob EnsureGuildMobComponent(Character character) { if ((Object)(object)character == (Object)null || !character.IsTamed()) { return null; } TamedGuildMob tamedGuildMob = ((Component)character).GetComponent(); if ((Object)(object)tamedGuildMob == (Object)null) { tamedGuildMob = ((Component)character).gameObject.AddComponent(); } return tamedGuildMob; } [HarmonyPatch("Tame")] [HarmonyPostfix] public static void TamePostfix(Tameable __instance) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_character.IsTamed()) { return; } TamedGuildMob tamedGuildMob = EnsureGuildMobComponent(__instance.m_character); if (tamedGuildMob.TamerID != 0L) { return; } Player closestPlayer = Player.GetClosestPlayer(((Component)__instance).transform.position, 20f); if ((Object)(object)closestPlayer != (Object)null) { string text = GuildUtils.GetPlayerGuildName(closestPlayer); if (string.IsNullOrEmpty(text)) { text = "No Guild"; } tamedGuildMob.TryClaim(closestPlayer, text); } } private static void GetGuildHoverText(TamedGuildMob guildMob, bool hasTameable, ref string __result) { string text = SanitizeGuildText(guildMob.GuildName); int num = __result.IndexOf('\n'); if (num == -1) { num = __result.Length; } string text2 = SanitizeGuildText(__result.Substring(0, num)); string text3 = __result.Substring(num); if (!string.IsNullOrEmpty(text)) { string text4 = (((Object)(object)Player.m_localPlayer != (Object)null) ? SanitizeGuildText(GuildUtils.GetPlayerGuildName(Player.m_localPlayer)) : ""); string text5 = "orange"; if (text == text4) { text5 = "#00BFFF"; } else if (GuildUtils.IsAlly(text4, text) || GuildUtils.IsAlly(text, text4)) { text5 = "#FFC0CB"; } text2 = "" + text + " " + text2; } if (guildMob.Confusion > 0f) { text2 = ((!(guildMob.Confusion > 50f)) ? $"{text2} (Dazed {Mathf.CeilToInt(guildMob.Confusion)}%)" : $"{text2} (Confused {Mathf.CeilToInt(guildMob.Confusion)}%)"); } __result = text2 + text3; long num2 = (((Object)(object)Player.m_localPlayer != (Object)null) ? Player.m_localPlayer.GetPlayerID() : 0); long tamerID = guildMob.TamerID; float obedience = guildMob.Obedience; string guildName = guildMob.GuildName; if (tamerID == 0) { text2 = "" + text2 + ""; __result = text2 + text3; } if (tamerID == 0L || obedience <= 0f) { if (obedience > 0f) { __result += $"\nObedience: {Mathf.CeilToInt(obedience)}%"; } if (tamerID == 0L || tamerID == num2) { if (!string.IsNullOrEmpty(GuildUtils.GetPlayerGuildName(Player.m_localPlayer))) { __result += "\n[Alt + E] Claim for Guild"; } else { __result += "\nJoin a Guild to Claim"; } } else if (!string.IsNullOrEmpty(guildMob.TamerName)) { __result = __result + "\nTamer: " + guildMob.TamerName + " (Obedience Broken)"; } return; } string playerGuildName = GuildUtils.GetPlayerGuildName(Player.m_localPlayer); bool flag = !string.IsNullOrEmpty(playerGuildName) && guildMob.IsSameGuild(playerGuildName); if (!string.IsNullOrEmpty(guildMob.TamerName)) { __result = __result + "\nTamer: " + guildMob.TamerName; } __result += $"\nObedience: {Mathf.CeilToInt(obedience)}%"; if (!hasTameable) { return; } if (flag || tamerID == num2) { string arg = ((guildMob.CommandLocked && obedience > 0f) ? " (Locked)" : ""); __result += $"\nStance: {guildMob.Stance}{arg}"; __result += "\n[Alt + E] Cycle Orders"; if (tamerID == num2) { __result = __result + "\n[Ctrl + E] " + (guildMob.CommandLocked ? "Unlock" : "Lock") + " Orders"; } } if ((Object)(object)Player.m_localPlayer != (Object)null && Player.m_localPlayer.NoCostCheat()) { __result = __result + "\n[O + E] " + (guildMob.SkipDecay ? "Enable" : "Disable") + " Obedience Decay"; } if (tamerID == num2 && !string.IsNullOrEmpty(playerGuildName) && playerGuildName != guildName) { __result += "\n[E] Sync to Current Guild"; } string debugHoverText = guildMob.GetDebugHoverText(); if (!string.IsNullOrEmpty(debugHoverText)) { __result += debugHoverText; } } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "GetHoverText")] private static void CharacterHoverTextPostfix(Character __instance, ref string __result) { if (__instance.IsTamed() && !Object.op_Implicit((Object)(object)((Component)__instance).GetComponent())) { TamedGuildMob tamedGuildMob = EnsureGuildMobComponent(__instance); if ((Object)(object)tamedGuildMob != (Object)null) { GetGuildHoverText(tamedGuildMob, hasTameable: false, ref __result); } } } [HarmonyPostfix] [HarmonyPatch("GetHoverText")] public static void GetHoverTextPostfix(Tameable __instance, ref string __result) { if (__instance.m_character.IsTamed()) { TamedGuildMob tamedGuildMob = EnsureGuildMobComponent(__instance.m_character); if ((Object)(object)tamedGuildMob != (Object)null) { GetGuildHoverText(tamedGuildMob, hasTameable: true, ref __result); } } } [HarmonyPrefix] [HarmonyPatch("Interact")] public static bool InteractPrefix(Tameable __instance, Humanoid user, bool hold, bool alt) { //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) if (hold) { return true; } Player val = (Player)(object)((user is Player) ? user : null); if ((Object)(object)val == (Object)null || !__instance.m_character.IsTamed()) { return true; } TamedGuildMob tamedGuildMob = EnsureGuildMobComponent(__instance.m_character); if ((Object)(object)tamedGuildMob != (Object)null) { long playerID = val.GetPlayerID(); long tamerID = tamedGuildMob.TamerID; float obedience = tamedGuildMob.Obedience; string text = GuildUtils.GetPlayerGuildName(val); if (string.IsNullOrEmpty(text)) { text = "No Guild"; } if (tamerID == 0L || obedience <= 0f) { if (tamerID != 0L && tamerID != playerID) { if (!hold) { ((Character)val).Message((MessageType)2, "This beast is wild, but belongs to another.", 0, (Sprite)null); } return false; } if ((Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307)) && text != "No Guild" && tamedGuildMob.TryClaim(val, text)) { ((Character)val).Message((MessageType)2, "Mob claimed for guild: " + text, 0, (Sprite)null); return false; } } else if (tamerID == playerID && text != tamedGuildMob.GuildName && text != "No Guild") { if (alt) { return true; } if (tamedGuildMob.TryChangeGuild(val, text)) { ((Character)val).Message((MessageType)2, "Mob updated to guild: " + text, 0, (Sprite)null); return false; } } else { if (tamerID == playerID || tamedGuildMob.IsSameGuild(text)) { if (alt) { return true; } if ((Input.GetKey((KeyCode)308) || Input.GetKey((KeyCode)307)) && !hold) { tamedGuildMob.CycleStance(val); return false; } if (tamerID == playerID && (Input.GetKey((KeyCode)306) || Input.GetKey((KeyCode)305)) && !hold) { tamedGuildMob.ToggleCommandLock(val); return false; } if (Input.GetKey((KeyCode)111) && val.NoCostCheat() && !hold) { tamedGuildMob.ToggleSkipDecay(val); return false; } if (!hold) { if (__instance.m_petEffect != null) { __instance.m_petEffect.Create(((Component)__instance).transform.position, Quaternion.identity, (Transform)null, 1f, -1); } return false; } return true; } if (tamerID != 0L && obedience > 0f) { if (!hold) { ((Character)val).Message((MessageType)2, "This beast belongs to another.", 0, (Sprite)null); } return false; } } } return true; } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "OnDeath")] public static void OnDeathPostfix(Character __instance) { if (TameGuildWarsPlugin.ConfigDeathNotifications.Value == TameGuildWarsPlugin.Toggle.Off) { return; } TamedGuildMob component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || string.IsNullOrEmpty(component.GuildName) || __instance.GetLevel() < 3) { return; } HitData lastHit = component.m_lastHit; if (lastHit == null) { return; } Character attacker = lastHit.GetAttacker(); if ((Object)(object)attacker == (Object)null || !attacker.IsPlayer()) { return; } Player val = (Player)(object)((attacker is Player) ? attacker : null); string playerGuildName = GuildUtils.GetPlayerGuildName(val); if (string.IsNullOrEmpty(playerGuildName) || !(playerGuildName == component.GuildName)) { string guildName = component.GuildName; string text = Localization.instance.Localize(__instance.m_name); string playerName = val.GetPlayerName(); string text2 = ((string.IsNullOrEmpty(playerGuildName) || playerGuildName == "No Guild") ? "a lone warrior" : ("<" + playerGuildName + "> " + playerName)); int num = __instance.GetLevel() - 1; string[] array = new string[5] { $"GUILD WAR: Our vanguard {text} ({num} Star) has been slain by {text2}!", $"GUILD WAR: High-value target {text} ({num} Star) was taken down by {text2}!", $"GUILD WAR: A dark day for {guildName}! Our {num} Star {text} fell to {text2}!", $"GUILD WAR: {text2} has eliminated a {num} Star {text} belonging to {guildName}!", $"GUILD WAR: {guildName}'s {num} Star {text} was crushed by {text2}!" }; string message = array[Random.Range(0, array.Length)]; if (IsLocalGuildDeathAnnouncer(guildName)) { TameGuildWarsPlugin.SendGuildChatInput(message); } } } private static bool IsLocalGuildDeathAnnouncer(string guildName) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || string.IsNullOrEmpty(guildName)) { return false; } if (!string.Equals(GuildUtils.GetPlayerGuildName(localPlayer), guildName, StringComparison.OrdinalIgnoreCase)) { return false; } long playerID = localPlayer.GetPlayerID(); long num = playerID; foreach (Player allPlayer in Player.GetAllPlayers()) { if (!((Object)(object)allPlayer == (Object)null) && string.Equals(GuildUtils.GetPlayerGuildName(allPlayer), guildName, StringComparison.OrdinalIgnoreCase)) { long playerID2 = allPlayer.GetPlayerID(); if (playerID2 != 0L && playerID2 < num) { num = playerID2; } } } return playerID == num; } [HarmonyPostfix] [HarmonyPatch(typeof(Aoe), "OnHit")] private static void AoeConfusionPatch(Aoe __instance, Collider collider) { if (!TryGetConfusionRange(((Object)((Component)__instance).gameObject).name, out var minConfusion, out var maxConfusion)) { return; } ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && !component.IsOwner()) { return; } Character componentInParent = ((Component)collider).GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null && componentInParent.IsTamed() && (TameGuildWarsPlugin.ConfigAllowBossConfusion.Value == TameGuildWarsPlugin.Toggle.On || !componentInParent.IsBoss()) && (Object)(object)((Component)componentInParent).GetComponent() != (Object)null) { float num = Random.Range(minConfusion, maxConfusion); float healthBasedConfusionResistance = GetHealthBasedConfusionResistance(componentInParent); float num2 = num * (1f - healthBasedConfusionResistance); ZNetView component2 = ((Component)componentInParent).GetComponent(); if ((Object)(object)component2 != (Object)null && component2.IsValid()) { component2.InvokeRPC(ZNetView.Everybody, "RPC_TGW_AddConfusion", new object[1] { num2 }); } } } private static float GetHealthBasedConfusionResistance(Character character) { float maxHealth = character.GetMaxHealth(); if (maxHealth <= 0f) { return 0f; } float value = TameGuildWarsPlugin.ConfigConfusionResistanceMinHealth.Value; float num = TameGuildWarsPlugin.ConfigConfusionResistanceMaxHealth.Value; if (num <= value) { num = value + 1f; } float num2 = Mathf.Clamp01(TameGuildWarsPlugin.ConfigConfusionResistanceMaxValue.Value); float num3 = Mathf.Clamp01(TameGuildWarsPlugin.ConfigConfusionResistanceLowHealthMultiplier.Value); float num4 = Mathf.InverseLerp(value, num, maxHealth) * num2; float num5 = Mathf.Clamp01(character.GetHealth() / maxHealth); float num6 = Mathf.Lerp(num3, 1f, num5); return Mathf.Clamp01(num4 * num6); } private static bool TryGetConfusionRange(string aoeName, out float minConfusion, out float maxConfusion) { minConfusion = 0f; maxConfusion = 0f; if (string.IsNullOrEmpty(aoeName)) { return false; } string text = aoeName.ToLowerInvariant(); if (text.Contains("tgw_confusionbomb3")) { return GetConfiguredConfusionRange(TameGuildWarsPlugin.ConfigConfusionBomb3Min.Value, TameGuildWarsPlugin.ConfigConfusionBomb3Max.Value, out minConfusion, out maxConfusion); } if (text.Contains("tgw_confusionbomb2")) { return GetConfiguredConfusionRange(TameGuildWarsPlugin.ConfigConfusionBomb2Min.Value, TameGuildWarsPlugin.ConfigConfusionBomb2Max.Value, out minConfusion, out maxConfusion); } if (text.Contains("tgw_confusionbomb1")) { return GetConfiguredConfusionRange(TameGuildWarsPlugin.ConfigConfusionBomb1Min.Value, TameGuildWarsPlugin.ConfigConfusionBomb1Max.Value, out minConfusion, out maxConfusion); } return false; } private static bool GetConfiguredConfusionRange(float configuredMin, float configuredMax, out float minConfusion, out float maxConfusion) { minConfusion = Mathf.Clamp(configuredMin, 0f, 100f); maxConfusion = Mathf.Clamp(configuredMax, 0f, 100f); if (maxConfusion < minConfusion) { float num = minConfusion; minConfusion = maxConfusion; maxConfusion = num; } return maxConfusion > 0f; } [HarmonyPatch(typeof(Humanoid), "DropItem")] [HarmonyPrefix] private static void SetItemGuild(Humanoid __instance, ItemData item, int amount) { if (amount == 0) { return; } Player val = (Player)(object)((__instance is Player) ? __instance : null); if (Object.op_Implicit((Object)(object)val)) { string playerGuildName = GuildUtils.GetPlayerGuildName(val); if (!string.IsNullOrEmpty(playerGuildName)) { item.m_customData.Remove("TGW_Guild"); item.m_customData.Add("TGW_Guild", playerGuildName + ":" + val.GetPlayerID()); } } } [HarmonyPostfix] [HarmonyPatch(typeof(Humanoid), "DropItem")] private static void RemoveItemGuild(Humanoid __instance, ItemData item, ref bool __result) { if (__result) { item.m_customData.Remove("TGW_Guild"); } } [HarmonyPatch(typeof(Tameable), "OnConsumedItem")] [HarmonyPostfix] private static void AdjustGuildObedience(ItemDrop item, Tameable __instance) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) TamedGuildMob component = ((Component)__instance).GetComponent(); if (!((Object)(object)component != (Object)null)) { return; } if (!item.m_itemData.m_customData.TryGetValue("TGW_Guild", out var value)) { return; } string[] array = value.Split(new char[1] { ':' }); if (array.Length != 2) { return; } float obedience = component.Obedience; string guildName = component.GuildName; bool flag = array[0] == guildName; if (obedience > 0f && flag) { return; } Character character = __instance.m_character; if (!long.TryParse(array[1], out var plrID)) { return; } Player val = Player.GetAllPlayers().Find([<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] (Player c) => plrID == c.GetPlayerID()); if (!((Object)(object)val == (Object)null) && !(Vector3.Distance(((Component)val).transform.position, ((Component)character).transform.position) > 30f)) { if (obedience <= 0f) { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)$"plr {plrID} attempting change tamerID"); component.TryChangeTamer(val); } else if (!flag) { __instance.m_nview.InvokeRPC(ZNetView.Everybody, "RPC_ObedienceDrop", Array.Empty()); } } } } [HarmonyPatch(typeof(Character))] public static class CharacterNamePatchesTGW { [HarmonyPatch("GetHoverName")] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [HarmonyPostfix] public static void GetHoverNamePostfix(Character __instance, ref string __result) { if (!__instance.IsTamed()) { return; } __result = TamedMobPatches.SanitizeGuildText(__result); TamedGuildMob component = ((Component)__instance).GetComponent(); if (!((Object)(object)component != (Object)null)) { return; } string guildName = component.GuildName; guildName = TamedMobPatches.SanitizeGuildText(guildName); string text = ""; if (!string.IsNullOrEmpty(guildName)) { string text2 = (((Object)(object)Player.m_localPlayer != (Object)null) ? TamedMobPatches.SanitizeGuildText(GuildUtils.GetPlayerGuildName(Player.m_localPlayer)) : ""); string text3 = "orange"; if (guildName == text2) { text3 = "#00BFFF"; } else if (GuildUtils.IsAlly(text2, guildName) || GuildUtils.IsAlly(guildName, text2)) { text3 = "#FFC0CB"; } text = "" + guildName + " "; } if (component.Confusion > 50f) { __result = "" + __result + ""; } else if ((Object)(object)Player.m_localPlayer != (Object)null) { long playerID = Player.m_localPlayer.GetPlayerID(); string text4 = TamedMobPatches.SanitizeGuildText(GuildUtils.GetPlayerGuildName(Player.m_localPlayer)); if (component.TamerID == 0L) { __result = "" + __result + ""; } else if (component.TamerID != 0L && component.TamerID == playerID) { __result = "" + __result + ""; } else if (!string.IsNullOrEmpty(guildName) && guildName == text4) { __result = "" + __result + ""; } else if (component.Obedience <= 0f) { __result = "" + __result + ""; } else if (!string.IsNullOrEmpty(guildName) && (GuildUtils.IsAlly(text4, guildName) || GuildUtils.IsAlly(guildName, text4))) { __result = "" + __result + ""; } else if (!string.IsNullOrEmpty(guildName)) { bool num = (Object)(object)component.MonsterAi != (Object)null && (Object)(object)((BaseAI)component.MonsterAi).GetTargetCreature() == (Object)(object)Player.m_localPlayer; bool flag = component.AlarmPlayerId == playerID; if (num || flag) { __result = "" + __result + ""; } else { __result = "" + __result + ""; } } } __result = text + __result; } } [HarmonyPatch(typeof(EnemyHud), "ShowHud")] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] public static class EnemyHudGuildIconPatch { private static readonly FieldInfo HudsField = AccessTools.Field(typeof(EnemyHud), "m_huds"); private static FieldInfo HudGuiField; private static readonly Vector2 GuildIconSize = new Vector2(32f, 32f); private static void Postfix(EnemyHud __instance, Character c) { //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) if (TameGuildWarsPlugin.ConfigShowGuildIcon.Value == TameGuildWarsPlugin.Toggle.Off || (Object)(object)c == (Object)null) { return; } TamedGuildMob component = ((Component)c).GetComponent(); if ((Object)(object)component == (Object)null || string.IsNullOrEmpty(component.GuildName)) { return; } Sprite guildIcon = GuildUtils.GetGuildIcon(component.GuildName); if ((Object)(object)guildIcon == (Object)null || HudsField == null || !(HudsField.GetValue(__instance) is IDictionary dictionary) || !dictionary.Contains(c)) { return; } object obj = dictionary[c]; if (obj == null) { return; } if (HudGuiField == null) { HudGuiField = obj.GetType().GetField("m_gui", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } if (HudGuiField == null) { return; } object? value = HudGuiField.GetValue(obj); GameObject val = (GameObject)((value is GameObject) ? value : null); if ((Object)(object)val == (Object)null) { return; } GuildIconUiRefs guildIconUiRefs = val.GetComponent(); if ((Object)(object)guildIconUiRefs == (Object)null) { GameObject val2 = new GameObject("TGW_GuildIcon", new Type[1] { typeof(RectTransform) }); val2.transform.SetParent(val.transform, false); RectTransform component2 = val2.GetComponent(); Image val3 = val2.AddComponent(); val3.preserveAspect = true; guildIconUiRefs = val.AddComponent(); guildIconUiRefs.RectTransform = component2; guildIconUiRefs.Image = val3; Shadow obj2 = val2.AddComponent(); obj2.effectColor = new Color(0f, 0f, 0f, 0.75f); obj2.effectDistance = new Vector2(1f, -1f); Outline obj3 = val2.AddComponent(); ((Shadow)obj3).effectColor = new Color(0f, 0f, 0f, 0.5f); ((Shadow)obj3).effectDistance = new Vector2(0.5f, 0.5f); } RectTransform rectTransform = guildIconUiRefs.RectTransform; if ((Object)(object)rectTransform != (Object)null) { Vector2 val4 = default(Vector2); ((Vector2)(ref val4))..ctor(TameGuildWarsPlugin.ConfigGuildIconOffsetX.Value, TameGuildWarsPlugin.ConfigGuildIconOffsetY.Value); if (rectTransform.sizeDelta != GuildIconSize) { rectTransform.sizeDelta = GuildIconSize; } if (rectTransform.anchoredPosition != val4) { rectTransform.anchoredPosition = val4; } } Image image = guildIconUiRefs.Image; if ((Object)(object)image != (Object)null) { if ((Object)(object)image.sprite != (Object)(object)guildIcon) { image.sprite = guildIcon; } if (!((Behaviour)image).enabled) { ((Behaviour)image).enabled = true; } } } } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [HarmonyPatch(typeof(Humanoid))] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] public static class CommandHornPatches { private static readonly GuildMobStance[] HornCycle = new GuildMobStance[5] { GuildMobStance.Guard, GuildMobStance.Stay, GuildMobStance.GuardWard, GuildMobStance.Follow, GuildMobStance.FollowAttack }; private static readonly Dictionary HornCycleIndexByPlayer = new Dictionary(); [HarmonyPostfix] [HarmonyPatch("StartAttack", new Type[] { typeof(Character), typeof(bool) })] private static void StartAttackPostfix(Humanoid __instance, Character target, bool secondaryAttack, bool __result) { if (!__result) { return; } Player val = (Player)(object)((__instance is Player) ? __instance : null); if ((Object)(object)val == (Object)null || (Object)(object)val != (Object)(object)Player.m_localPlayer) { return; } ItemData currentWeapon = ((Humanoid)val).GetCurrentWeapon(); if (currentWeapon == null || !IsCommandHornItem(currentWeapon)) { return; } if (currentWeapon.m_shared != null) { currentWeapon.m_shared.m_useDurability = false; if (currentWeapon.m_shared.m_attack != null && currentWeapon.m_shared.m_attack.m_hitEffect != null) { currentWeapon.m_shared.m_attack.m_hitEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; } if (currentWeapon.m_shared.m_startEffect != null) { currentWeapon.m_shared.m_startEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; } if (currentWeapon.m_shared.m_holdStartEffect != null) { currentWeapon.m_shared.m_holdStartEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; } if (currentWeapon.m_shared.m_triggerEffect != null) { currentWeapon.m_shared.m_triggerEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; } if (currentWeapon.m_shared.m_trailStartEffect != null) { currentWeapon.m_shared.m_trailStartEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; } } ActivateCommandHorn(val); } private static bool IsCommandHornItem(ItemData item) { if ((Object)(object)item?.m_dropPrefab == (Object)null) { return false; } return ((Object)item.m_dropPrefab).name.ToLowerInvariant().Contains("tgw_command"); } private static void ActivateCommandHorn(Player player) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) PlayHornSound(player); string playerGuildName = GuildUtils.GetPlayerGuildName(player); if (string.IsNullOrEmpty(playerGuildName)) { ((Character)player).Message((MessageType)2, "You are not in a guild.", 0, (Sprite)null); return; } GuildMobStance nextHornStance = GetNextHornStance(player.GetPlayerID()); float num = Mathf.Max(1f, TameGuildWarsPlugin.ConfigCommandHornRadius.Value); int num2 = 0; foreach (Character allCharacter in Character.GetAllCharacters()) { if (allCharacter.IsTamed()) { TamedGuildMob component = ((Component)allCharacter).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsSameGuild(playerGuildName) && !(Vector3.Distance(((Component)player).transform.position, ((Component)allCharacter).transform.position) > num) && component.SetStance(nextHornStance, player, notifyPlayer: false)) { num2++; } } } ((Character)player).Message((MessageType)2, $"Horn order: {nextHornStance} ({num2} mobs)", 0, (Sprite)null); } private static GuildMobStance GetNextHornStance(long playerId) { int num = (HornCycleIndexByPlayer.TryGetValue(playerId, out num) ? ((num + 1) % HornCycle.Length) : 0); HornCycleIndexByPlayer[playerId] = num; return HornCycle[num]; } private static void PlayHornSound(Player player) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) string value = TameGuildWarsPlugin.ConfigCommandHornSound.Value; if (string.IsNullOrEmpty(value) || (Object)(object)ZNetScene.instance == (Object)null) { return; } GameObject val = ResolveSfxPrefab(value); if ((Object)(object)val == (Object)null) { TameGuildWarsPlugin.TameGuildWarsLogger.LogWarning((object)("Command horn SFX prefab not found: '" + value + "'")); return; } GameObject val2 = Object.Instantiate(val, ((Component)player).transform.position, Quaternion.identity); if ((Object)(object)val2 != (Object)null) { val2.SetActive(true); } } private static GameObject ResolveSfxPrefab(string soundName) { GameObject prefab = ZNetScene.instance.GetPrefab(soundName); if ((Object)(object)prefab != (Object)null) { return prefab; } return null; } } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] [HarmonyPatch] public static class TargetingPatches { [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(0)] private struct GhostCacheEntry { public bool IsGhost; public long CachedAtTicks; } [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] private sealed class GhostModeSync : MonoBehaviour { private Player _player; private ZNetView _nview; private void Awake() { _player = ((Component)this).GetComponent(); _nview = ((Component)this).GetComponent(); ((MonoBehaviour)this).InvokeRepeating("SyncGhostMode", 1f, 5f); } private void OnDestroy() { ((MonoBehaviour)this).CancelInvoke("SyncGhostMode"); } private void SyncGhostMode() { if (!((Object)(object)_player == (Object)null) && !((Object)(object)_player != (Object)(object)Player.m_localPlayer) && !((Object)(object)_nview == (Object)null) && _nview.IsValid() && _nview.IsOwner()) { bool flag = ReadGhostFlag(_player); _nview.GetZDO().Set("TGW_GhostMode", flag); CachePlayerGhostState(_player.GetPlayerID(), DateTime.UtcNow.Ticks, flag); } } } private const double PlayerGhostCacheSeconds = 2.0; private const string GhostModeZdoKey = "TGW_GhostMode"; private static readonly MethodInfo PlayerInGhostModeMethod = AccessTools.Method(typeof(Player), "InGhostMode", (Type[])null, (Type[])null); private static readonly FieldInfo PlayerGhostModeField = AccessTools.Field(typeof(Player), "m_ghostMode"); private static readonly Dictionary PlayerGhostCache = new Dictionary(); [HarmonyPatch(typeof(Player), "Awake")] [HarmonyPostfix] private static void PlayerAwakePostfix(Player __instance) { if ((Object)(object)__instance != (Object)null && (Object)(object)((Component)__instance).GetComponent() == (Object)null) { ((Component)__instance).gameObject.AddComponent(); } } [HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[] { typeof(Character) })] [HarmonyPostfix] public static void BaseAIIsEnemyPostfix(BaseAI __instance, Character other, ref bool __result) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance.m_character == (Object)null) && !((Object)(object)other == (Object)null)) { __result = EvaluateGuildEnemy(__instance.m_character, other, __result); } } [HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[] { typeof(Character), typeof(Character) })] [HarmonyPostfix] public static void BaseAIIsEnemyStaticPostfix(Character a, Character b, ref bool __result) { if (!((Object)(object)a == (Object)null) && !((Object)(object)b == (Object)null)) { __result = EvaluateGuildEnemy(a, b, __result); } } private static bool EvaluateGuildEnemy(Character attacker, Character target, bool vanillaResult) { //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected O, but got Unknown //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) TamedGuildMob tamedGuildMob = default(TamedGuildMob); ((Component)attacker).TryGetComponent(ref tamedGuildMob); TamedGuildMob tamedGuildMob2 = default(TamedGuildMob); ((Component)target).TryGetComponent(ref tamedGuildMob2); bool flag = (Object)(object)tamedGuildMob != (Object)null && attacker.IsTamed(); bool flag2 = (Object)(object)tamedGuildMob2 != (Object)null && target.IsTamed(); bool flag3 = flag && tamedGuildMob.Obedience > 0f && !string.IsNullOrEmpty(tamedGuildMob.GuildName); bool flag4 = flag2 && tamedGuildMob2.Obedience > 0f && !string.IsNullOrEmpty(tamedGuildMob2.GuildName); if (target.IsPlayer() && IsPlayerGhost((Player)(object)((target is Player) ? target : null))) { return false; } if (attacker.IsPlayer() && IsPlayerGhost((Player)(object)((attacker is Player) ? attacker : null))) { return false; } if (flag && tamedGuildMob.Confusion > 50f && (Object)(object)attacker != (Object)(object)target) { return true; } if (flag2 && tamedGuildMob2.Confusion > 50f && (Object)(object)attacker != (Object)(object)target) { return true; } if (!flag3 && !flag4) { return vanillaResult; } if (flag3 && tamedGuildMob.Stance == GuildMobStance.Stay) { return false; } string text = ""; string text2 = ""; bool flag5 = false; if (flag3) { text = tamedGuildMob.GuildName; } else if (attacker.IsPlayer()) { text = GuildUtils.GetPlayerGuildName((Player)attacker); } Character obj = ((attacker is Humanoid) ? attacker : null); ItemData val = ((obj != null) ? ((Humanoid)obj).GetCurrentWeapon() : null); if (val != null && val.m_shared.m_tamedOnly) { flag5 = true; } if (flag4) { text2 = tamedGuildMob2.GuildName; if (string.IsNullOrEmpty(text2) && flag5) { return false; } } else if (target.IsPlayer()) { text2 = GuildUtils.GetPlayerGuildName((Player)target); } bool flag6 = vanillaResult; if (!string.IsNullOrEmpty(text) && !string.IsNullOrEmpty(text2)) { flag6 = ((text == text2) ? flag5 : ((!GuildUtils.IsAlly(text, text2) && !GuildUtils.IsAlly(text2, text)) ? ((target.IsPlayer() && GuildUtils.IsAlly(text, ((Player)target).GetPlayerName())) ? flag5 : ((!attacker.IsPlayer() || !GuildUtils.IsAlly(text2, ((Player)attacker).GetPlayerName())) ? (!flag5) : flag5)) : flag5)); } else if (flag3 && target.IsPlayer() && string.IsNullOrEmpty(text2)) { flag6 = !GuildUtils.IsAlly(text, ((Player)target).GetPlayerName()) && TameGuildWarsPlugin.ConfigHostileToNeutrals.Value == TameGuildWarsPlugin.Toggle.On; } else if (attacker.IsPlayer() && flag4 && string.IsNullOrEmpty(text)) { if (GuildUtils.IsAlly(text2, ((Player)attacker).GetPlayerName())) { flag6 = false; } else if (TameGuildWarsPlugin.ConfigHostileToNeutrals.Value == TameGuildWarsPlugin.Toggle.On) { flag6 = true; } } if (flag6 && flag3 && tamedGuildMob.Stance == GuildMobStance.Follow) { bool flag7 = false; if ((Object)(object)((BaseAI)tamedGuildMob.MonsterAi).GetTargetCreature() == (Object)(object)target) { flag7 = true; } else { BaseAI component = ((Component)target).GetComponent(); if ((Object)(object)component != (Object)null) { Character targetCreature = component.GetTargetCreature(); if ((Object)(object)targetCreature != (Object)null) { if ((Object)(object)targetCreature == (Object)(object)attacker) { flag7 = true; } else { GameObject followTarget = tamedGuildMob.MonsterAi.GetFollowTarget(); if ((Object)(object)followTarget != (Object)null && (Object)(object)((Component)targetCreature).gameObject == (Object)(object)followTarget) { flag7 = true; } } } } } if (!flag7) { flag6 = false; } } return flag6; } public static bool IsPlayerGhost(Player player) { if ((Object)(object)player == (Object)null) { return false; } long playerID = player.GetPlayerID(); long ticks = DateTime.UtcNow.Ticks; if (playerID != 0L && PlayerGhostCache.TryGetValue(playerID, out var value) && new TimeSpan(ticks - value.CachedAtTicks).TotalSeconds <= 2.0) { return value.IsGhost; } bool flag = false; if ((Object)(object)player == (Object)(object)Player.m_localPlayer) { flag = ReadGhostFlag(player); CachePlayerGhostState(playerID, ticks, flag); return flag; } ZNetView component = ((Component)player).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { flag = component.GetZDO().GetBool("TGW_GhostMode", false); CachePlayerGhostState(playerID, ticks, flag); return flag; } flag = ReadGhostFlag(player); CachePlayerGhostState(playerID, ticks, flag); return flag; } private static bool ReadGhostFlag(Player player) { if ((Object)(object)player == (Object)null) { return false; } if (PlayerInGhostModeMethod != null) { try { return (bool)PlayerInGhostModeMethod.Invoke(player, null); } catch { } } if (PlayerGhostModeField != null) { try { return (bool)PlayerGhostModeField.GetValue(player); } catch { } } return false; } private static void CachePlayerGhostState(long playerId, long nowTicks, bool isGhost) { if (playerId != 0L) { PlayerGhostCache[playerId] = new GhostCacheEntry { IsGhost = isGhost, CachedAtTicks = nowTicks }; } } [HarmonyPatch(typeof(Character), "RPC_Damage")] [HarmonyPrefix] public static bool RpcDamagePrefix(Character __instance, HitData hit, out bool __state) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Expected O, but got Unknown //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Expected O, but got Unknown __state = false; if (hit == null || (Object)(object)hit.GetAttacker() == (Object)null || (Object)(object)__instance == (Object)null) { return true; } TamedGuildMob tamedGuildMob = default(TamedGuildMob); ((Component)__instance).TryGetComponent(ref tamedGuildMob); if ((Object)(object)tamedGuildMob != (Object)null) { tamedGuildMob.m_lastHit = hit; } Character attacker = hit.GetAttacker(); if (__instance.m_tamed && attacker.IsPlayer()) { TamedGuildMob tamedGuildMob2 = default(TamedGuildMob); ((Component)__instance).TryGetComponent(ref tamedGuildMob2); if ((Object)(object)tamedGuildMob2 != (Object)null && tamedGuildMob2.Confusion > 50f) { __instance.m_tamed = false; __state = true; } } string text = ""; TamedGuildMob tamedGuildMob3 = default(TamedGuildMob); ((Component)__instance).TryGetComponent(ref tamedGuildMob3); if ((Object)(object)tamedGuildMob3 != (Object)null) { text = tamedGuildMob3.GuildName; } else if (__instance.IsPlayer()) { text = GuildUtils.GetPlayerGuildName((Player)__instance); } if (!string.IsNullOrEmpty(text)) { string text2 = ""; TamedGuildMob tamedGuildMob4 = default(TamedGuildMob); ((Component)attacker).TryGetComponent(ref tamedGuildMob4); if ((Object)(object)tamedGuildMob4 != (Object)null) { text2 = tamedGuildMob4.GuildName; } else if (attacker.IsPlayer()) { text2 = GuildUtils.GetPlayerGuildName((Player)attacker); } bool flag = false; if (text != string.Empty) { if (text2 != string.Empty && (GuildUtils.IsAlly(text, text2) || GuildUtils.IsAlly(text2, text))) { if (GuildUtils.IsAllianceBreakGraceActive(text, text2) || GuildUtils.IsAllianceBreakGraceActive(text2, text)) { return false; } GuildUtils.SetAlly(text, text2, ally: false); GuildUtils.SetAlly(text2, text, ally: false); flag = true; if (attacker.IsPlayer()) { Player val = (Player)attacker; ((Character)val).Message((MessageType)2, "You have broken your guild's alliance with " + text + "!", 0, (Sprite)null); if ((Object)val == (Object)(object)Player.m_localPlayer) { TameGuildWarsPlugin.SendShoutChatInput("Guild " + text2 + " has broken their alliance with " + text + "!"); } } } else if (attacker.IsPlayer()) { string playerName = ((Player)attacker).GetPlayerName(); if (GuildUtils.IsAlly(text, playerName)) { if (GuildUtils.IsAllianceBreakGraceActive(text, playerName)) { return false; } GuildUtils.SetAlly(text, playerName, ally: false); flag = true; Player val2 = (Player)attacker; ((Character)val2).Message((MessageType)2, "You have broken your alliance with " + text + "!", 0, (Sprite)null); if ((Object)val2 == (Object)(object)Player.m_localPlayer) { TameGuildWarsPlugin.SendShoutChatInput("Player " + playerName + " has broken their alliance with " + text + "!"); } } } if (flag) { return true; } } } if (!EvaluateGuildEnemy(attacker, __instance, vanillaResult: true)) { if (__state) { __instance.m_tamed = true; } hit.ApplyModifier(0f); return false; } return true; } [HarmonyPatch(typeof(Character), "RPC_Damage")] [HarmonyPostfix] public static void RpcDamagePostfix(Character __instance, HitData hit, ref bool __state) { if (__state) { __instance.m_tamed = true; } if (hit == null || (Object)(object)hit.GetAttacker() == (Object)null || (Object)(object)__instance == (Object)null) { return; } Character attacker = hit.GetAttacker(); if (!__instance.IsDead()) { TamedGuildMob component = ((Component)__instance).GetComponent(); if ((Object)(object)component != (Object)null && component.Obedience > 0f && EvaluateGuildEnemy(attacker, __instance, vanillaResult: true)) { component.RaiseAlarm(attacker); } } if (__instance.IsPlayer() && !__instance.IsDead() && EvaluateGuildEnemy(attacker, __instance, vanillaResult: true)) { RaiseNearbyGuildMobAlarms((Player)(object)((__instance is Player) ? __instance : null), attacker); } } private static void RaiseNearbyGuildMobAlarms(Player victim, Character attacker) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)victim == (Object)null || (Object)(object)attacker == (Object)null) { return; } float num = TameGuildWarsPlugin.ConfigSwarmRadius.Value * TameGuildWarsPlugin.ConfigSwarmRadius.Value; Vector3 position = ((Component)victim).transform.position; foreach (Character allCharacter in Character.GetAllCharacters()) { if ((Object)(object)allCharacter == (Object)null) { continue; } Vector3 val = ((Component)allCharacter).transform.position - position; if (!(((Vector3)(ref val)).sqrMagnitude > num)) { TamedGuildMob component = ((Component)allCharacter).GetComponent(); if (!((Object)(object)component == (Object)null) && !(component.Obedience <= 0f) && !EvaluateGuildEnemy(allCharacter, (Character)(object)victim, vanillaResult: false) && EvaluateGuildEnemy(allCharacter, attacker, vanillaResult: true)) { component.RaiseAlarm(attacker); } } } } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] public static class TerminalCommandPatches { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; public static ConsoleEvent <>9__0_1; [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] internal void b__0_0(ConsoleEventArgs args) { //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) if (args.Length < 2) { args.Context.AddString("Usage: guild_order [guard/stay/ward/follow/attack/static] [radius]"); return; } string text = args.Args[1].ToLower(); float result = 20f; if (args.Length >= 3) { float.TryParse(args.Args[2], out result); } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } GuildMobStance guildMobStance = GuildMobStance.Guard; switch (text) { case "stay": guildMobStance = GuildMobStance.Stay; break; case "guard": guildMobStance = GuildMobStance.Guard; break; case "ward": guildMobStance = GuildMobStance.GuardWard; break; case "follow": guildMobStance = GuildMobStance.Follow; break; case "attack": guildMobStance = GuildMobStance.FollowAttack; break; case "static": guildMobStance = GuildMobStance.Static; break; default: args.Context.AddString("Unknown order: " + text + ". Valid orders: guard, stay, ward, follow, attack, static"); return; } string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (string.IsNullOrEmpty(playerGuildName)) { args.Context.AddString("You are not in a guild."); return; } int num = 0; foreach (Character allCharacter in Character.GetAllCharacters()) { TamedGuildMob component = ((Component)allCharacter).GetComponent(); if ((Object)(object)component != (Object)null && component.IsSameGuild(playerGuildName) && Vector3.Distance(((Component)localPlayer).transform.position, ((Component)allCharacter).transform.position) <= result && component.SetStance(guildMobStance, localPlayer, notifyPlayer: false)) { num++; } } args.Context.AddString($"Ordered {num} guild mobs to '{guildMobStance}' within {result}m."); } [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] internal void b__0_1(ConsoleEventArgs args) { if (args.Length < 2) { args.Context.AddString("Usage: guild_ally [add/remove/list/accept/deny] [PlayerOrGuildName]"); return; } Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (string.IsNullOrEmpty(playerGuildName)) { args.Context.AddString("You are not in a guild. You cannot set or view allies."); return; } string text = args.Args[1].ToLower(); switch (text) { case "list": { List alliesForGuild = GuildUtils.GetAlliesForGuild(playerGuildName); if (alliesForGuild.Count == 0) { args.Context.AddString("Guild '" + playerGuildName + "' currently has no allies."); ((Character)localPlayer).Message((MessageType)2, "Guild '" + playerGuildName + "' has no allies.", 0, (Sprite)null); } else { args.Context.AddString($"Allies for guild '{playerGuildName}' ({alliesForGuild.Count}):\n- " + string.Join("\n- ", alliesForGuild)); ((Character)localPlayer).Message((MessageType)2, $"Listed {alliesForGuild.Count} allies for '{playerGuildName}'.", 0, (Sprite)null); } return; } case "accept": case "deny": { if (args.Length < 4) { args.Context.AddString("Usage: guild_ally [accept/deny] [RequesterGuild] [TargetNameOrGuild]"); return; } string text2 = args.Args[2].Trim(); string text3 = string.Join(" ", args.Args.Skip(3).ToArray()).Trim(); if (!GuildUtils.TryGetPendingAllyRequest(text2, text3, out var _)) { args.Context.AddString("No pending ally request found for '" + text2 + "' -> '" + text3 + "'."); ((Character)localPlayer).Message((MessageType)2, "No pending ally request found.", 0, (Sprite)null); return; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("guild_ally command: action='" + text + "', requester='" + text2 + "', target='" + text3 + "'.")); ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_RespondAllyRequest", new object[3] { text2, text3, text == "accept" }); } args.Context.AddString("Sent ally request response '" + text + "' for '" + text2 + "' -> '" + text3 + "'."); ((Character)localPlayer).Message((MessageType)2, "Sent ally " + text + ".", 0, (Sprite)null); return; } } if (args.Length < 3) { args.Context.AddString("Usage: guild_ally [add/remove] [PlayerOrGuildName]"); args.Context.AddString("Usage: guild_ally [accept/deny] [RequesterGuild] [TargetNameOrGuild]"); return; } string text4 = string.Join(" ", args.Args.Skip(2).ToArray()).Trim(); List list = GuildUtils.ResolveAllyTargets(text4); TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("guild_ally command: action='" + text + "', guild='" + playerGuildName + "', target='" + text4 + "', resolved='" + string.Join(",", list) + "'.")); bool flag = true; if (text == "add") { flag = true; foreach (string item in list) { if (ZRoutedRpc.instance == null) { flag = false; break; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("Sending ally request from guild '" + playerGuildName + "' to target '" + item + "'.")); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_RequestAlly", new object[2] { playerGuildName, item }); } if (flag) { string text5 = ((list.Count > 1) ? (" (resolved: " + string.Join(", ", list) + ")") : string.Empty); args.Context.AddString("Sent ally request for '" + text4 + "' from guild '" + playerGuildName + "'" + text5 + "."); ((Character)localPlayer).Message((MessageType)2, "Ally request sent: " + text4, 0, (Sprite)null); return; } double num = 0.0; foreach (string item2 in list) { if (GuildUtils.TryGetAllyAddCooldownRemaining(playerGuildName, item2, out var remainingSeconds)) { num = Math.Max(num, remainingSeconds); } } if (num > 0.0) { args.Context.AddString($"Failed to add '{text4}' as an ally for guild '{playerGuildName}'. Cooldown active: {num:0.0}s remaining."); ((Character)localPlayer).Message((MessageType)2, $"Ally add cooldown: {num:0.0}s", 0, (Sprite)null); return; } args.Context.AddString("Failed to add '" + text4 + "' as an ally for guild '" + playerGuildName + "'. Check logs for details."); ((Character)localPlayer).Message((MessageType)2, "Failed to add ally: " + text4, 0, (Sprite)null); } else if (text == "remove") { flag = true; foreach (string item3 in list) { flag &= GuildUtils.SetAlly(playerGuildName, item3, ally: false); flag &= GuildUtils.SetAlly(item3, playerGuildName, ally: false); if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_BroadcastAllyRemoved", new object[2] { playerGuildName, item3 }); } } if (flag) { string text6 = ((list.Count > 1) ? (" (resolved: " + string.Join(", ", list) + ")") : string.Empty); args.Context.AddString("Removed '" + text4 + "' from allies for guild '" + playerGuildName + "'" + text6 + "."); ((Character)localPlayer).Message((MessageType)2, "Removed ally: " + text4, 0, (Sprite)null); } else { args.Context.AddString("Failed to remove '" + text4 + "' from allies for guild '" + playerGuildName + "'. Check logs for details."); ((Character)localPlayer).Message((MessageType)2, "Failed to remove ally: " + text4, 0, (Sprite)null); } } else { args.Context.AddString("Usage: guild_ally [add/remove/list/accept/deny] [PlayerOrGuildName]"); } } } [HarmonyPostfix] public static void TerminalInitPostfix() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] (ConsoleEventArgs args) => { //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) if (args.Length < 2) { args.Context.AddString("Usage: guild_order [guard/stay/ward/follow/attack/static] [radius]"); } else { string text = args.Args[1].ToLower(); float result = 20f; if (args.Length >= 3) { float.TryParse(args.Args[2], out result); } Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { GuildMobStance guildMobStance = GuildMobStance.Guard; switch (text) { case "stay": guildMobStance = GuildMobStance.Stay; break; case "guard": guildMobStance = GuildMobStance.Guard; break; case "ward": guildMobStance = GuildMobStance.GuardWard; break; case "follow": guildMobStance = GuildMobStance.Follow; break; case "attack": guildMobStance = GuildMobStance.FollowAttack; break; case "static": guildMobStance = GuildMobStance.Static; break; default: args.Context.AddString("Unknown order: " + text + ". Valid orders: guard, stay, ward, follow, attack, static"); return; } string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (string.IsNullOrEmpty(playerGuildName)) { args.Context.AddString("You are not in a guild."); } else { int num = 0; foreach (Character allCharacter in Character.GetAllCharacters()) { TamedGuildMob component = ((Component)allCharacter).GetComponent(); if ((Object)(object)component != (Object)null && component.IsSameGuild(playerGuildName) && Vector3.Distance(((Component)localPlayer).transform.position, ((Component)allCharacter).transform.position) <= result && component.SetStance(guildMobStance, localPlayer, notifyPlayer: false)) { num++; } } args.Context.AddString($"Ordered {num} guild mobs to '{guildMobStance}' within {result}m."); } } } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("guild_order", "Order nearby tamed guild mobs. [guard/stay/ward/follow/attack/static] [radius=20]", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); object obj2 = <>c.<>9__0_1; if (obj2 == null) { ConsoleEvent val2 = [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] (ConsoleEventArgs args) => { if (args.Length < 2) { args.Context.AddString("Usage: guild_ally [add/remove/list/accept/deny] [PlayerOrGuildName]"); } else { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { string playerGuildName = GuildUtils.GetPlayerGuildName(localPlayer); if (string.IsNullOrEmpty(playerGuildName)) { args.Context.AddString("You are not in a guild. You cannot set or view allies."); } else { string text = args.Args[1].ToLower(); switch (text) { case "list": { List alliesForGuild = GuildUtils.GetAlliesForGuild(playerGuildName); if (alliesForGuild.Count == 0) { args.Context.AddString("Guild '" + playerGuildName + "' currently has no allies."); ((Character)localPlayer).Message((MessageType)2, "Guild '" + playerGuildName + "' has no allies.", 0, (Sprite)null); } else { args.Context.AddString($"Allies for guild '{playerGuildName}' ({alliesForGuild.Count}):\n- " + string.Join("\n- ", alliesForGuild)); ((Character)localPlayer).Message((MessageType)2, $"Listed {alliesForGuild.Count} allies for '{playerGuildName}'.", 0, (Sprite)null); } break; } case "accept": case "deny": if (args.Length < 4) { args.Context.AddString("Usage: guild_ally [accept/deny] [RequesterGuild] [TargetNameOrGuild]"); } else { string text5 = args.Args[2].Trim(); string text6 = string.Join(" ", args.Args.Skip(3).ToArray()).Trim(); if (!GuildUtils.TryGetPendingAllyRequest(text5, text6, out var _)) { args.Context.AddString("No pending ally request found for '" + text5 + "' -> '" + text6 + "'."); ((Character)localPlayer).Message((MessageType)2, "No pending ally request found.", 0, (Sprite)null); } else { TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("guild_ally command: action='" + text + "', requester='" + text5 + "', target='" + text6 + "'.")); ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null) { instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_RespondAllyRequest", new object[3] { text5, text6, text == "accept" }); } args.Context.AddString("Sent ally request response '" + text + "' for '" + text5 + "' -> '" + text6 + "'."); ((Character)localPlayer).Message((MessageType)2, "Sent ally " + text + ".", 0, (Sprite)null); } } break; default: if (args.Length < 3) { args.Context.AddString("Usage: guild_ally [add/remove] [PlayerOrGuildName]"); args.Context.AddString("Usage: guild_ally [accept/deny] [RequesterGuild] [TargetNameOrGuild]"); } else { string text2 = string.Join(" ", args.Args.Skip(2).ToArray()).Trim(); List list = GuildUtils.ResolveAllyTargets(text2); TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("guild_ally command: action='" + text + "', guild='" + playerGuildName + "', target='" + text2 + "', resolved='" + string.Join(",", list) + "'.")); bool flag = true; if (text == "add") { flag = true; foreach (string item in list) { if (ZRoutedRpc.instance == null) { flag = false; break; } TameGuildWarsPlugin.TameGuildWarsLogger.LogInfo((object)("Sending ally request from guild '" + playerGuildName + "' to target '" + item + "'.")); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_RequestAlly", new object[2] { playerGuildName, item }); } if (flag) { string text3 = ((list.Count > 1) ? (" (resolved: " + string.Join(", ", list) + ")") : string.Empty); args.Context.AddString("Sent ally request for '" + text2 + "' from guild '" + playerGuildName + "'" + text3 + "."); ((Character)localPlayer).Message((MessageType)2, "Ally request sent: " + text2, 0, (Sprite)null); } else { double num = 0.0; foreach (string item2 in list) { if (GuildUtils.TryGetAllyAddCooldownRemaining(playerGuildName, item2, out var remainingSeconds)) { num = Math.Max(num, remainingSeconds); } } if (num > 0.0) { args.Context.AddString($"Failed to add '{text2}' as an ally for guild '{playerGuildName}'. Cooldown active: {num:0.0}s remaining."); ((Character)localPlayer).Message((MessageType)2, $"Ally add cooldown: {num:0.0}s", 0, (Sprite)null); } else { args.Context.AddString("Failed to add '" + text2 + "' as an ally for guild '" + playerGuildName + "'. Check logs for details."); ((Character)localPlayer).Message((MessageType)2, "Failed to add ally: " + text2, 0, (Sprite)null); } } } else if (text == "remove") { flag = true; foreach (string item3 in list) { flag &= GuildUtils.SetAlly(playerGuildName, item3, ally: false); flag &= GuildUtils.SetAlly(item3, playerGuildName, ally: false); if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "TGW_BroadcastAllyRemoved", new object[2] { playerGuildName, item3 }); } } if (flag) { string text4 = ((list.Count > 1) ? (" (resolved: " + string.Join(", ", list) + ")") : string.Empty); args.Context.AddString("Removed '" + text2 + "' from allies for guild '" + playerGuildName + "'" + text4 + "."); ((Character)localPlayer).Message((MessageType)2, "Removed ally: " + text2, 0, (Sprite)null); } else { args.Context.AddString("Failed to remove '" + text2 + "' from allies for guild '" + playerGuildName + "'. Check logs for details."); ((Character)localPlayer).Message((MessageType)2, "Failed to remove ally: " + text2, 0, (Sprite)null); } } else { args.Context.AddString("Usage: guild_ally [add/remove/list/accept/deny] [PlayerOrGuildName]"); } } break; } } } } }; <>c.<>9__0_1 = val2; obj2 = (object)val2; } new ConsoleCommand("guild_ally", "Request, remove, or list allies so guild mobs do not attack them. Usage: guild_ally [add/remove/list/accept/deny] [PlayerOrGuildName]", (ConsoleEvent)obj2, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } } namespace TameGuildWars.Compatibility { [<3caa0b4f-4b82-489f-b8ce-dd36932aef56>NullableContext(1)] [<01a73d35-473a-4adb-86fb-c7fd269b4cb1>Nullable(0)] public static class PortablePalsPatches { private const string ZdoItemDropGuild = "TGW_Guild"; private const string ZdoItemDropTamer = "TGW_Tamer"; private const string ZdoItemDropObedience = "TGW_Obedience"; private const string ZdoTamedGuildMob = "TGW_TamedGuildMob"; public static void TryPatch(Harmony harmony) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown Type type = AccessTools.TypeByName("PortablePals.API"); if (!(type == null)) { MethodInfo methodInfo = AccessTools.Method(type, "SaveDataToPalStone", new Type[2] { typeof(Character), typeof(Dictionary) }, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(type, "ReleaseCreature_PostAwake", new Type[2] { typeof(Character), typeof(Dictionary) }, (Type[])null); MethodInfo methodInfo3 = AccessTools.Method(type, "CanCapture", new Type[2] { typeof(Character), typeof(Player) }, (Type[])null); if (!(methodInfo == null) && !(methodInfo2 == null)) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(PortablePalsPatches), "SaveDataPostfix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, new HarmonyMethod(typeof(PortablePalsPatches), "SaveMobData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); harmony.Patch((MethodBase)methodInfo3, (HarmonyMethod)null, new HarmonyMethod(typeof(PortablePalsPatches), "CanCaptureGuild", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } } public static void SaveDataPostfix(Character character, Dictionary customData) { TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (((Component)character).TryGetComponent(ref tamedGuildMob)) { string guildMobData = tamedGuildMob.getGuildMobData(); customData["TGW_TamedGuildMob"] = guildMobData; } } public static void CanCaptureGuild(Character character, Player player, ref bool __result) { TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (((Component)character).TryGetComponent(ref tamedGuildMob) && __result && !tamedGuildMob.IsSameGuild(GuildUtils.GetPlayerGuildName(player))) { __result = false; ((Character)player).Message((MessageType)2, "Cannot capture another guilds creatures.", 0, (Sprite)null); } } public static void SaveMobData(Character character, Dictionary customData) { TamedGuildMob tamedGuildMob = default(TamedGuildMob); if (!((Component)character).TryGetComponent(ref tamedGuildMob)) { return; } ZNetView component = ((Component)character).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { if (!component.IsOwner()) { component.ClaimOwnership(); } if (component.IsOwner() && customData.TryGetValue("TGW_TamedGuildMob", out var value)) { tamedGuildMob.RestoreMobdata(value); } } } } } [CompilerGenerated] internal sealed class <45b1dd8a-3fa7-4ccc-b0ad-9e52a46a9e3d> { [StructLayout(LayoutKind.Explicit, Pack = 1, Size = 20)] internal struct __StaticArrayInitTypeSize=20 { } internal static readonly __StaticArrayInitTypeSize=20 E528F4309E1413E6BC35AEA5D8DB8519384D2FCC33F9DD5D1126D73F104CF92A/* Not supported: data(00 00 00 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00) */; } namespace Microsoft.CodeAnalysis { [Embedded] [CompilerGenerated] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class <1ee2369c-83d5-416c-831c-76ef108db83f>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <1ee2369c-83d5-416c-831c-76ef108db83f>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <1ee2369c-83d5-416c-831c-76ef108db83f>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [Embedded] [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContextAttribute : Attribute { public readonly byte Flag; public <9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class <67eb955e-180e-4013-b097-2a5234f3a87a>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <67eb955e-180e-4013-b097-2a5234f3a87a>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] [PublicAPI] internal abstract class OwnConfigEntryBase { [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] internal class SyncedConfigEntry<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] T>(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(2)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(1)] public readonly string Identifier; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(1)] public readonly Type Type; private object boxedValue; protected bool localIsOwner; public readonly int Priority; public object BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action ValueChanged; [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [PublicAPI] internal sealed class CustomSyncedValue<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] private static class SnatchCurrentlyHandlingRPC { [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public static ZRpc currentRpc; [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] internal static class RegisterRPCPatch { [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] private class ParsedConfigs { [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary configValues = new Dictionary(); [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary customValues = new Dictionary(); } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix([<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] private class PackageEntry { public string section = null; public string key = null; public Type type = null; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public object value; } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] private static class PreventConfigRereadChangingValues { [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public string DisplayName; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public string CurrentVersion; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public string MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private OwnConfigEntryBase lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 1, 0, 1 })] private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] [method: <9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(2)] [field: <1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] public event Action SourceOfTruthChanged; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] [method: <9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(2)] [field: <1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private event Action lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] T>(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (object _, EventArgs _) => { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] T>(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (object _, EventArgs _) => { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(([<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 0, 1 })] KeyValuePair kv) => { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } [return: <1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private static OwnConfigEntryBase configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } [return: <1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1 })] public static SyncedConfigEntry ConfigData<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] T>(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute<[<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] T>(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage([<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1 })] IEnumerable configs = null, [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1 })] IEnumerable customValues = null, [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1 })] IEnumerable packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] object value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(1)] [PublicAPI] [HarmonyPatch] [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(0)] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private string displayName; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private string currentVersion; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private string minimumRequiredVersion; public bool ModRequired = true; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private string ReceivedCurrentVersion; [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private string ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] private ConfigSync ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error([<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(2)] ZRpc rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(new byte[] { 2, 1, 1 })] Action original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (ZRpc rpc, [<1ee2369c-83d5-416c-831c-76ef108db83f>Nullable(1)] ZPackage pkg) => { CheckVersion(rpc, pkg, action); })); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy([<9b0ea3c5-d602-4e90-949b-7e68176069bc>NullableContext(0)] (KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace YamlDotNet { [NullableContext(1)] [Nullable(0)] internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } [NullableContext(2)] public override object GetFormat(Type formatType) { return provider.GetFormat(formatType); } } [Nullable(0)] [NullableContext(1)] internal static class ReflectionExtensions { [Nullable(2)] private static readonly FieldInfo RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); [return: Nullable(2)] public static Type BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (allowPrivateConstructors) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsValueType) { return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } [return: Nullable(2)] public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } [return: Nullable(2)] public static FieldInfo GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (includeNonPublic) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsInterface) { return type.GetProperties(bindingFlags); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany([NullableContext(0)] (Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } [return: Nullable(2)] public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } [return: Nullable(2)] public static MethodInfo GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if (RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes<[Nullable(2)] TAttribute>(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true); } } internal static class PropertyInfoExtensions { [NullableContext(1)] [return: Nullable(2)] public static object ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { [Nullable(0)] [NullableContext(1)] internal abstract class BuilderSkeleton<[Nullable(0)] TBuilder> where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride<[Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[Nullable(0)] TYamlTypeConverter>(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<[Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory<[Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory<[Nullable(2)] TArgument, [Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } [Nullable(0)] [NullableContext(1)] internal sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize<[Nullable(2)] T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize<[Nullable(2)] T>(TextReader input) { return Deserialize(new Parser(input)); } [return: Nullable(2)] public object Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } [return: Nullable(2)] public object Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } [return: Nullable(2)] public object Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize<[Nullable(2)] T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } [return: Nullable(2)] public object Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } [return: Nullable(2)] public object Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume(out event2); object result = null; if (!parser.Accept(out var _) && !parser.Accept(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume(); } if (flag) { parser.Consume(); } return result; } } [Nullable(new byte[] { 0, 1 })] [NullableContext(1)] internal sealed class DeserializerBuilder : BuilderSkeleton { private Lazy objectFactory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly Dictionary typeMappings; private readonly ITypeConverter typeConverter; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy(() => objectFactory, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public DeserializerBuilder WithNodeDeserializer<[Nullable(0)] TNodeDeserializer>(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<[Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public DeserializerBuilder WithNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping<[Nullable(2)] TInterface, [Nullable(0)] TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public DeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } [NullableContext(1)] [Nullable(0)] internal sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable> preProcessingPhaseVisitors; public IObjectGraphVisitor InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor innerVisitor, IEventEmitter eventEmitter, IEnumerable> preProcessingPhaseVisitors, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] T>() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } [NullableContext(1)] [Nullable(0)] internal abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } [NullableContext(1)] public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } [NullableContext(1)] protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } [Nullable(0)] [NullableContext(1)] internal sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } internal sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } [NullableContext(1)] public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { [NullableContext(1)] public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } [NullableContext(1)] public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { [NullableContext(1)] public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } [NullableContext(1)] internal interface IAliasProvider { AnchorName GetAlias(object target); } [NullableContext(1)] internal interface IDeserializer { T Deserialize<[Nullable(2)] T>(string input); T Deserialize<[Nullable(2)] T>(TextReader input); [return: Nullable(2)] object Deserialize(TextReader input); [return: Nullable(2)] object Deserialize(string input, Type type); [return: Nullable(2)] object Deserialize(TextReader input, Type type); T Deserialize<[Nullable(2)] T>(IParser parser); [return: Nullable(2)] object Deserialize(IParser parser); [return: Nullable(2)] object Deserialize(IParser parser, Type type); } [NullableContext(1)] internal interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } [NullableContext(1)] internal interface INamingConvention { string Apply(string value); } [NullableContext(1)] internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value); } [NullableContext(1)] internal interface INodeTypeResolver { bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType); } [NullableContext(1)] internal interface IObjectAccessor { void Set(string name, object target, object value); [return: Nullable(2)] object Read(string name, object target); } [NullableContext(1)] internal interface IObjectDescriptor { [Nullable(2)] object Value { [NullableContext(2)] get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { [NullableContext(1)] public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } [NullableContext(1)] internal interface IObjectFactory { object Create(Type type); [return: Nullable(2)] object CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments); Type GetValueType(Type type); } [NullableContext(1)] internal interface IObjectGraphTraversalStrategy { void Traverse<[Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); } [NullableContext(1)] internal interface IObjectGraphVisitor<[Nullable(2)] TContext> { bool Enter(IObjectDescriptor value, TContext context); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); void VisitScalar(IObjectDescriptor scalar, TContext context); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); void VisitMappingEnd(IObjectDescriptor mapping, TContext context); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); } [NullableContext(1)] internal interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } [Nullable(2)] Type TypeOverride { [NullableContext(2)] get; [NullableContext(2)] set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } [NullableContext(0)] [return: Nullable(2)] T GetCustomAttribute() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, [Nullable(2)] object value); } internal interface IRegistrationLocationSelectionSyntax<[Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax<[Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } [NullableContext(1)] internal interface ISerializer { void Serialize(TextWriter writer, [Nullable(2)] object graph); string Serialize([Nullable(2)] object graph); void Serialize(TextWriter writer, [Nullable(2)] object graph, Type type); void Serialize(IEmitter emitter, [Nullable(2)] object graph); void Serialize(IEmitter emitter, [Nullable(2)] object graph, Type type); } [NullableContext(1)] internal interface ITypeInspector { IEnumerable GetProperties(Type type, [Nullable(2)] object container); IPropertyDescriptor GetProperty(Type type, [Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched); } [NullableContext(1)] internal interface ITypeResolver { Type Resolve(Type staticType, [Nullable(2)] object actualValue); } [NullableContext(1)] internal interface IValueDeserializer { [return: Nullable(2)] object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { [Nullable(new byte[] { 1, 2 })] event Action ValueAvailable; } [NullableContext(2)] internal interface IValueSerializer { void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type); } [NullableContext(1)] internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } [return: Nullable(2)] internal delegate object ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object value, Type type = null); [Obsolete("Please use IYamlConvertible instead")] [NullableContext(1)] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } [NullableContext(1)] internal interface IYamlTypeConverter { bool Accepts(Type type); [return: Nullable(2)] object ReadYaml(IParser parser, Type type); void WriteYaml(IEmitter emitter, [Nullable(2)] object value, Type type); } [Nullable(0)] [NullableContext(1)] internal sealed class LazyComponentRegistrationList<[Nullable(2)] TArgument, [Nullable(2)] TComponent> : IEnumerable>, IEnumerable { [Nullable(0)] public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [Nullable(0)] public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [NullableContext(0)] private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { [Nullable(1)] private readonly LazyComponentRegistrationList registrations; [Nullable(new byte[] { 1, 0, 0 })] private readonly LazyComponentRegistration newRegistration; [NullableContext(1)] public RegistrationLocationSelector(LazyComponentRegistrationList registrations, [Nullable(new byte[] { 1, 0, 0 })] LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax.After() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax.Before() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } [NullableContext(0)] private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { [Nullable(1)] private readonly LazyComponentRegistrationList registrations; [Nullable(new byte[] { 1, 0, 0 })] private readonly TrackingLazyComponentRegistration newRegistration; [NullableContext(1)] public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, [Nullable(new byte[] { 1, 0, 0 })] TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); Func innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, [NullableContext(1)] (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } [Nullable(new byte[] { 1, 1, 0, 0 })] private readonly List entries = new List(); public int Count => entries.Count; public IEnumerable> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList Clone() { LazyComponentRegistrationList lazyComponentRegistrationList = new LazyComponentRegistrationList(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Clear() { entries.Clear(); } public void Add(Type componentType, Func factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if (entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax CreateRegistrationLocationSelector(Type componentType, Func factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax CreateTrackingRegistrationLocationSelector(Type componentType, Func factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator> GetEnumerator() { return entries.Select([NullableContext(0)] (LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if (registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } [NullableContext(2)] private int EnsureRegistrationExists() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } [NullableContext(1)] [Nullable(0)] internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<[Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, [NullableContext(0)] (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain<[Nullable(2)] TArgument, [Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { return registrations.InReverseOrder.Aggregate(innerComponent, [NullableContext(0)] (TComponent inner, Func factory) => factory(argumentBuilder(inner))); } public static List BuildComponentList<[Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations) { return registrations.Select([NullableContext(0)] (Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList<[Nullable(2)] TArgument, [Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TArgument argument) { return registrations.Select([NullableContext(0)] (Func factory) => factory(argument)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } [Nullable(0)] [NullableContext(1)] internal sealed class ObjectDescriptor : IObjectDescriptor { [Nullable(2)] [field: Nullable(2)] public object Value { [NullableContext(2)] get; [NullableContext(2)] private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor([Nullable(2)] object value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor([Nullable(2)] object value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } internal delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion); [Nullable(0)] [NullableContext(1)] internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public string Name { get; set; } public Type Type => baseDescriptor.Type; [Nullable(2)] public Type TypeOverride { [NullableContext(2)] get { return baseDescriptor.TypeOverride; } [NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, [Nullable(2)] object value) { baseDescriptor.Write(target, value); } [NullableContext(0)] [return: Nullable(2)] public T GetCustomAttribute() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } [Nullable(0)] [NullableContext(1)] internal sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public void Serialize(TextWriter writer, [Nullable(2)] object graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public string Serialize([Nullable(2)] object graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public void Serialize(TextWriter writer, [Nullable(2)] object graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, [Nullable(2)] object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, [Nullable(2)] object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } [NullableContext(2)] private void EmitDocument([Nullable(1)] IEmitter emitter, object graph, Type type) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true)); emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } } [Nullable(new byte[] { 0, 1 })] [NullableContext(1)] internal sealed class SerializerBuilder : BuilderSkeleton { [Nullable(0)] private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } [NullableContext(2)] public void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new EmittingObjectGraphVisitor(eventEmitter), [NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter); [NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner))); return Self; } public SerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter<[Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter([NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector([NullableContext(0)] ([Nullable(1)] ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new YamlDotNet.Serialization.Converters.DateTimeConverter(DateTimeKind.Utc, null, true)).WithEventEmitter([NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal class Settings { public bool AllowPrivateConstructors { get; set; } } [Nullable(0)] [NullableContext(1)] internal abstract class StaticBuilderSkeleton<[Nullable(0)] TBuilder> where TBuilder : StaticBuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(ITypeResolver typeResolver) { typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[Nullable(0)] TYamlTypeConverter>(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector<[Nullable(0)] TTypeInspector>(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector<[Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } [NullableContext(1)] [Nullable(0)] internal abstract class StaticContext { public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } [Nullable(new byte[] { 0, 1 })] [NullableContext(1)] internal sealed class StaticDeserializerBuilder : StaticBuilderSkeleton { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly ITypeConverter typeConverter; private readonly Dictionary typeMappings; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base((ITypeResolver)new StaticTypeResolver()) { this.context = context; factory = context.GetFactory(); typeMappings = new Dictionary(); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(StaticArrayNodeDeserializer), (Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new NullTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public StaticDeserializerBuilder WithNodeDeserializer<[Nullable(0)] TNodeDeserializer>(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeDeserializer<[Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver<[Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override StaticDeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public StaticDeserializerBuilder WithTypeMapping<[Nullable(2)] TInterface, [Nullable(0)] TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public StaticDeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public StaticDeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public StaticDeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } [NullableContext(1)] [Nullable(new byte[] { 0, 1 })] internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { [Nullable(0)] private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } [NullableContext(2)] public void SerializeValue([Nullable(1)] IEmitter emitter, object value, Type type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new EmittingObjectGraphVisitor(eventEmitter), [NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter); [NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, v, t); } } } private readonly StaticContext context; private readonly StaticObjectFactory factory; private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; protected override StaticSerializerBuilder Self => this; public StaticSerializerBuilder(StaticContext context) : base((ITypeResolver)new DynamicTypeResolver()) { this.context = context; factory = context.GetFactory(); typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory); } public StaticSerializerBuilder WithQuotingNecessaryStrings() { quoteNecessaryStrings = true; return this; } public StaticSerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public StaticSerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner))); return Self; } public StaticSerializerBuilder WithEventEmitter<[Nullable(0)] TEventEmitter>(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public StaticSerializerBuilder WithoutEventEmitter<[Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override StaticSerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public StaticSerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public StaticSerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, factory); WithEventEmitter([NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector([NullableContext(0)] ([Nullable(1)] ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public StaticSerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public StaticSerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public StaticSerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public StaticSerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithEventEmitter([NullableContext(0)] ([Nullable(1)] IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } [Nullable(0)] [NullableContext(1)] internal sealed class StreamFragment : IYamlConvertible { private readonly List events = new List(); public IList Events => events; void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { events.Clear(); int num = 0; do { if (!parser.MoveNext()) { throw new InvalidOperationException("The parser has reached the end before deserialization completed."); } ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (ParsingEvent @event in events) { emitter.Emit(@event); } } } [Nullable(0)] [NullableContext(1)] internal sealed class TagMappings { private readonly IDictionary mappings; public TagMappings() { mappings = new Dictionary(); } public TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } [return: Nullable(2)] internal Type GetMapping(string tag) { if (!mappings.TryGetValue(tag, out var value)) { return null; } return value; } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlAttributeOverrides { [Nullable(0)] private struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } [NullableContext(2)] public override bool Equals(object obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } [Nullable(0)] private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } [NullableContext(2)] public override bool Equals(object obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); } public int Matches(Type matchType) { int num = 0; Type type = matchType; while (type != null) { num++; if (type == RegisteredType) { return num; } type = type.BaseType(); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); [return: MaybeNull] public T GetAttribute<[Nullable(0)] T>(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out var value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out var value)) { value = new List(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public YamlAttributeOverrides Clone() { YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides(); foreach (KeyValuePair> @override in overrides) { foreach (AttributeMapping item in @override.Value) { yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return yamlAttributeOverrides; } public void Add<[Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { [Nullable(0)] public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; [Nullable(2)] public Type TypeOverride { [NullableContext(2)] get { return baseDescriptor.TypeOverride; } [NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, [Nullable(2)] object value) { baseDescriptor.Write(target, value); } [NullableContext(0)] [return: Nullable(2)] public T GetCustomAttribute() where T : Attribute { return overrides.GetAttribute(classType, Name) ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { IEnumerable enumerable = innerTypeDescriptor.GetProperties(type, container); if (overrides != null) { enumerable = enumerable.Select((Func)([NullableContext(0)] (IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type))); } return enumerable; } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)([NullableContext(0)] (IPropertyDescriptor p) => { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return propertyDescriptor; })) orderby p.Order select p; } } [NullableContext(1)] [Nullable(0)] internal static class YamlFormatter { public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public static string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public static string FormatNumber(double number) { return number.ToString("G", NumberFormat); } public static string FormatNumber(float number) { return number.ToString("G", NumberFormat); } public static string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public static string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public static string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan/*cast due to .constrained prefix*/).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] [Nullable(0)] [NullableContext(2)] internal sealed class YamlMemberAttribute : Attribute { private DefaultValuesHandling? defaultValuesHandling; public string Description { get; set; } public Type SerializeAs { get; set; } public int Order { get; set; } public string Alias { get; set; } public bool ApplyNamingConventions { get; set; } public ScalarStyle ScalarStyle { get; set; } public DefaultValuesHandling DefaultValuesHandling { get { return defaultValuesHandling.GetValueOrDefault(); } set { defaultValuesHandling = value; } } public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue; public YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } [NullableContext(1)] public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] internal sealed class YamlSerializableAttribute : Attribute { } internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class AliasValueDeserializer : IValueDeserializer { [Nullable(new byte[] { 0, 1 })] private sealed class AliasState : Dictionary, IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { YamlDotNet.Core.Events.AnchorAlias alias = value.Alias; throw new AnchorNotFoundException(alias.Start, alias.End, $"Anchor '{alias.Value}' not found"); } } } } [NullableContext(2)] [Nullable(0)] private sealed class ValuePromise : IValuePromise { private object value; public readonly YamlDotNet.Core.Events.AnchorAlias Alias; public bool HasValue { get; private set; } public object Value { get { if (!HasValue) { throw new InvalidOperationException("Value not set"); } return value; } set { if (HasValue) { throw new InvalidOperationException("Value already set"); } HasValue = true; this.value = value; this.ValueAvailable?.Invoke(value); } } public event Action ValueAvailable; [NullableContext(1)] public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object value) { HasValue = true; this.value = value; } } [Nullable(1)] private readonly IValueDeserializer innerDeserializer; [NullableContext(1)] public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } [NullableContext(1)] [return: Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { if (!state.Get().TryGetValue(@event.Value, out var value)) { throw new AnchorNotFoundException(@event.Start, @event.End, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } AnchorName anchorName = AnchorName.Empty; if (parser.Accept(out var event2) && !event2.Anchor.IsEmpty) { anchorName = event2.Anchor; AliasState aliasState = state.Get(); if (!aliasState.ContainsKey(anchorName)) { aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState2 = state.Get(); if (!aliasState2.TryGetValue(anchorName, out var value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } [NullableContext(1)] [Nullable(0)] internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; private readonly ITypeConverter typeConverter; public NodeValueDeserializer(IList deserializers, IList typeResolvers, ITypeConverter typeConverter) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } [return: Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, [return: Nullable(2)] (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out var value)) { return typeConverter.ChangeType(value, expectedType); } } } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "Exception during deserialization", innerException); } throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent([Nullable(2)] NodeEvent nodeEvent, Type currentType) { using (IEnumerator enumerator = typeResolvers.GetEnumerator()) { while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType)) { } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } [NullableContext(2)] internal interface ITypeConverter { object ChangeType(object value, [Nullable(1)] Type expectedType); } internal class NullTypeConverter : ITypeConverter { [NullableContext(2)] public object ChangeType(object value, [Nullable(1)] Type expectedType) { return value; } } [NullableContext(1)] [Nullable(0)] internal sealed class ObjectAnchorCollection { private readonly IDictionary objectsByAnchor = new Dictionary(); private readonly IDictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out var value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [Nullable(2)][MaybeNullWhen(false)] out string anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { [NullableContext(2)] public object ChangeType(object value, [Nullable(1)] Type expectedType) { return TypeConverter.ChangeType(value, expectedType); } } [Nullable(0)] [NullableContext(1)] internal static class ReflectionUtility { [return: Nullable(2)] public static Type GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (implementedInterface.IsGenericType() && implementedInterface.GetGenericTypeDefinition() == genericInterfaceType) { return implementedInterface; } } return null; } public static IEnumerable GetImplementedInterfaces(Type type) { if (type.IsInterface()) { yield return type; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { yield return interfaces[i]; } } } internal sealed class SerializerState : IDisposable { [Nullable(1)] private readonly IDictionary items = new Dictionary(); [NullableContext(1)] public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out var value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (IPostDeserializationCallback item in items.Values.OfType()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType()) { item.Dispose(); } } } [Nullable(0)] [NullableContext(1)] internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", [NullableContext(0)] (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { str = char.ToLower(str[0]) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", [NullableContext(0)] (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } [NullableContext(1)] [Nullable(0)] internal static class TypeConverter { [NullableContext(2)] [return: Nullable(1)] public static T ChangeType(object value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType<[Nullable(2)] T>([Nullable(2)] object value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType<[Nullable(2)] T>([Nullable(2)] object value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } [NullableContext(2)] public static object ChangeType(object value, [Nullable(1)] Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [return: Nullable(2)] public static object ChangeType([Nullable(2)] object value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } [return: Nullable(2)] public static object ChangeType([Nullable(2)] object value, Type destinationType, CultureInfo culture) { if (value == null || value.IsDbNull()) { if (!destinationType.IsValueType()) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType() && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture); return Activator.CreateInstance(destinationType, obj); } if (destinationType.IsEnum()) { if (!(value is string value2)) { return value; } return Enum.Parse(destinationType, value2, ignoreCase: true); } if (destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; for (int i = 0; i < array.Length; i++) { foreach (MethodInfo publicStaticMethod2 in array[i].GetPublicStaticMethods()) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.Unwrap(); } } } } if (type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [NullableContext(0)] public static void RegisterTypeConverter<[Nullable(2)] TConvertible, TConverter>() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any([NullableContext(0)] (TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { [NullableContext(1)] public Type Resolve(Type staticType, [Nullable(2)] object actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal sealed class StaticTypeResolver : ITypeResolver { [NullableContext(1)] public Type Resolve(Type staticType, [Nullable(2)] object actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { [NullableContext(1)] [Nullable(0)] internal sealed class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container).ToList()); } } [Nullable(0)] [NullableContext(1)] internal sealed class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable)typeInspectors) { } public CompositeTypeInspector(IEnumerable typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return typeInspectors.SelectMany([NullableContext(0)] (ITypeInspector i) => i.GetProperties(type, container)); } } [Nullable(0)] [NullableContext(1)] internal sealed class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return innerTypeDescriptor.GetProperties(type, container).Select([NullableContext(0)] (IPropertyDescriptor p) => { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } [NullableContext(1)] [Nullable(0)] internal sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } [Nullable(0)] [NullableContext(1)] internal sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [NullableContext(2)] get; [NullableContext(2)] set; } public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; ScalarStyle = ScalarStyle.Any; } public void Write(object target, [Nullable(2)] object value) { fieldInfo.SetValue(target, value); } [NullableContext(0)] [return: Nullable(2)] public T GetCustomAttribute() where T : Attribute { return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return type.GetPublicFields().Select((Func)([NullableContext(0)] (FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } [NullableContext(1)] [Nullable(0)] internal sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [NullableContext(2)] get; [NullableContext(2)] set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, [Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [NullableContext(0)] [return: Nullable(2)] public T GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public ReadablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanRead) { return property.GetGetMethod(nonPublic: true).GetParameters().Length == 0; } return false; } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { [NullableContext(1)] public abstract IEnumerable GetProperties(Type type, [Nullable(2)] object container); [NullableContext(1)] public IPropertyDescriptor GetProperty(Type type, [Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched) { IEnumerable enumerable = from p in GetProperties(type, container) where p.Name == name select p; using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } [NullableContext(1)] [Nullable(0)] internal sealed class WritablePropertiesTypeInspector : TypeInspectorSkeleton { [Nullable(0)] private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; [Nullable(2)] [field: Nullable(2)] public Type TypeOverride { [NullableContext(2)] get; [NullableContext(2)] set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, [Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [NullableContext(0)] [return: Nullable(2)] public T GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public WritablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public WritablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanWrite) { return property.GetSetMethod(nonPublic: true).GetParameters().Length == 1; } return false; } public override IEnumerable GetProperties(Type type, [Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))) .ToArray(); } } } namespace YamlDotNet.Serialization.Schemas { internal sealed class FailsafeSchema { public static class Tags { public static readonly TagName Map = new TagName("tag:yaml.org,2002:map"); public static readonly TagName Seq = new TagName("tag:yaml.org,2002:seq"); public static readonly TagName Str = new TagName("tag:yaml.org,2002:str"); } } internal sealed class JsonSchema { public static class Tags { public static readonly TagName Null = new TagName("tag:yaml.org,2002:null"); public static readonly TagName Bool = new TagName("tag:yaml.org,2002:bool"); public static readonly TagName Int = new TagName("tag:yaml.org,2002:int"); public static readonly TagName Float = new TagName("tag:yaml.org,2002:float"); } } internal sealed class CoreSchema { public static class Tags { } } internal sealed class DefaultSchema { public static class Tags { public static readonly TagName Timestamp = new TagName("tag:yaml.org,2002:timestamp"); } } } namespace YamlDotNet.Serialization.ObjectGraphVisitors { [Nullable(0)] [NullableContext(1)] internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { [NullableContext(0)] private class AnchorAssignment { public AnchorName Anchor; } private readonly IDictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value) { if (value.Value != null && assignments.TryGetValue(value.Value, out var value2)) { if (value2.Anchor.IsEmpty) { value2.Anchor = new AnchorName("o" + nextId.ToString(CultureInfo.InvariantCulture)); nextId++; } return false; } return true; } protected override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value) { return true; } protected override void VisitScalar(IObjectDescriptor scalar) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence) { } private void VisitObject(IObjectDescriptor value) { if (value.Value != null) { assignments.Add(value.Value, new AnchorAssignment()); } } AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out var value)) { return value.Anchor; } return AnchorName.Empty; } } [Nullable(0)] [NullableContext(1)] internal sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEventEmitter eventEmitter; private readonly IAliasProvider aliasProvider; private readonly HashSet emittedAliases = new HashSet(); public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) : base(nextVisitor) { this.eventEmitter = eventEmitter; this.aliasProvider = aliasProvider; } public override bool Enter(IObjectDescriptor value, IEmitter context) { if (value.Value != null) { AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { AliasEventInfo aliasEventInfo = new AliasEventInfo(value, alias); eventEmitter.Emit(aliasEventInfo, context); return aliasEventInfo.NeedsExpansion; } } return base.Enter(value, context); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } [NullableContext(1)] [Nullable(0)] internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter(IObjectDescriptor value, IEmitter context) { return nextVisitor.Enter(value, context); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context) { nextVisitor.VisitScalar(scalar, context); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { nextVisitor.VisitMappingEnd(mapping, context); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { nextVisitor.VisitSequenceStart(sequence, elementType, context); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { nextVisitor.VisitSequenceEnd(sequence, context); } } [NullableContext(1)] [Nullable(0)] internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new YamlDotNet.Core.Events.Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context); } } [NullableContext(1)] [Nullable(0)] internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEnumerable typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter(IObjectDescriptor value, IEmitter context) { IYamlTypeConverter yamlTypeConverter = typeConverters.FirstOrDefault([NullableContext(0)] (IYamlTypeConverter t) => t.Accepts(value.Type)); if (yamlTypeConverter != null) { yamlTypeConverter.WriteYaml(context, value.Value, value.Type); return false; } if (value.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(value, context); } } [NullableContext(1)] [Nullable(0)] internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } [return: Nullable(2)] private static object GetDefault(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValueAttribute customAttribute = key.GetCustomAttribute(); object objB = ((customAttribute != null) ? customAttribute.Value : GetDefault(key.Type)); if (!object.Equals(value.Value, objB)) { return base.EnterMapping(key, value, context); } return false; } } [Nullable(0)] [NullableContext(1)] internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; private readonly IObjectFactory factory; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor nextVisitor, IObjectFactory factory) : base(nextVisitor) { this.handling = handling; this.factory = factory; } [return: Nullable(2)] private object GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValuesHandling defaultValuesHandling = handling; YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.IsDefaultValuesHandlingSpecified) { defaultValuesHandling = customAttribute.DefaultValuesHandling; } if ((defaultValuesHandling & DefaultValuesHandling.OmitNull) != DefaultValuesHandling.Preserve && value.Value == null) { return false; } if ((defaultValuesHandling & DefaultValuesHandling.OmitEmptyCollections) != DefaultValuesHandling.Preserve && value.Value is IEnumerable enumerable) { IEnumerator enumerator = enumerable.GetEnumerator(); bool flag = enumerator.MoveNext(); if (enumerator is IDisposable disposable) { disposable.Dispose(); } if (!flag) { return false; } } if ((defaultValuesHandling & DefaultValuesHandling.OmitDefaults) != DefaultValuesHandling.Preserve) { object objB = key.GetCustomAttribute()?.Value ?? GetDefault(key.Type); if (object.Equals(value.Value, objB)) { return false; } } return base.EnterMapping(key, value, context); } } [Nullable(0)] [NullableContext(1)] internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } [Nullable(0)] [NullableContext(1)] internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, Nothing context) { if (typeConverters.FirstOrDefault([NullableContext(0)] (IYamlTypeConverter t) => t.Accepts(value.Type)) != null) { return false; } if (value.Value is IYamlConvertible) { return false; } if (value.Value is IYamlSerializable) { return false; } return Enter(value); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context) { VisitMappingEnd(mapping); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context) { VisitMappingStart(mapping, keyType, valueType); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context) { VisitScalar(scalar); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context) { VisitSequenceEnd(sequence); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context) { VisitSequenceStart(sequence, elementType); } protected abstract bool Enter(IObjectDescriptor value); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value); protected abstract void VisitMappingEnd(IObjectDescriptor mapping); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType); protected abstract void VisitScalar(IObjectDescriptor scalar); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { [Nullable(0)] [NullableContext(1)] internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { [Nullable(0)] protected struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly ITypeResolver typeResolver; private readonly INamingConvention namingConvention; private readonly IObjectFactory objectFactory; public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, IObjectFactory objectFactory) { if (maxRecursion <= 0) { throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1"); } this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.maxRecursion = maxRecursion; this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } void IObjectGraphTraversalStrategy.Traverse<[Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) { Traverse("", graph, visitor, context, new Stack(maxRecursion)); } protected virtual void Traverse<[Nullable(2)] TContext>(object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = item.Name?.ToString() ?? string.Empty; num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(value, context)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = value.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: visitor.VisitScalar(value, context); return; case TypeCode.Empty: throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } if (value.IsDbNull()) { visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); if (underlyingType != null) { Traverse("Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path); } else { TraverseObject(value, visitor, context, path); } } finally { path.Pop(); } } protected virtual void TraverseObject<[Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(value, visitor, typeof(object), typeof(object), context, path); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(new ObjectDescriptor(dictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(value, visitor, context, path); } else { TraverseProperties(value, visitor, context, path); } } protected virtual void TraverseDictionary<[Nullable(2)] TContext>(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path) { visitor.VisitMappingStart(dictionary, keyType, valueType, context); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); IObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); IObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context)) { Traverse(obj, objectDescriptor, visitor, context, path); Traverse(obj, objectDescriptor2, visitor, context, path); } } visitor.VisitMappingEnd(dictionary, context); } private void TraverseList<[Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(num, GetObjectDescriptor(item, valueType), visitor, context, path); num++; } visitor.VisitSequenceEnd(value, context); } protected virtual void TraverseProperties<[Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { visitor.VisitMappingStart(value, typeof(string), typeof(object), context); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context)) { Traverse(property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string), ScalarStyle.Plain), visitor, context, path); Traverse(property.Name, value2, visitor, context, path); } } visitor.VisitMappingEnd(value, context); } private IObjectDescriptor GetObjectDescriptor([Nullable(2)] object value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } [NullableContext(1)] [Nullable(0)] internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly IEnumerable converters; private readonly Settings settings; public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, Settings settings, IObjectFactory factory) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention, factory) { this.converters = converters; this.settings = settings; } protected override void TraverseProperties<[Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (!value.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.Any([NullableContext(0)] (IYamlTypeConverter c) => c.Accepts(value.Type))) { throw new InvalidOperationException($"Type '{value.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value, visitor, context, path); } } } namespace YamlDotNet.Serialization.ObjectFactories { [Nullable(0)] [NullableContext(1)] internal sealed class DefaultObjectFactory : ObjectFactoryBase { private readonly Dictionary DefaultGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable<>), typeof(List<>) }, { typeof(ICollection<>), typeof(List<>) }, { typeof(IList<>), typeof(List<>) }, { typeof(IDictionary<, >), typeof(Dictionary<, >) } }; private readonly Dictionary DefaultNonGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable), typeof(List) }, { typeof(ICollection), typeof(List) }, { typeof(IList), typeof(List) }, { typeof(IDictionary), typeof(Dictionary) } }; private readonly Settings settings; public DefaultObjectFactory() : this(new Dictionary(), new Settings()) { } public DefaultObjectFactory(IDictionary mappings) : this(mappings, new Settings()) { } public DefaultObjectFactory(IDictionary mappings, Settings settings) { foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } DefaultNonGenericInterfaceImplementations.Add(mapping.Key, mapping.Value); } this.settings = settings; } public override object Create(Type type) { if (type.IsInterface()) { Type value2; if (type.IsGenericType()) { if (DefaultGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out var value)) { type = value.MakeGenericType(type.GetGenericArguments()); } } else if (DefaultNonGenericInterfaceImplementations.TryGetValue(type, out value2)) { type = value2; } } try { return Activator.CreateInstance(type, settings.AllowPrivateConstructors); } catch (Exception innerException) { throw new InvalidOperationException("Failed to create an instance of type '" + type.FullName + "'.", innerException); } } } [Nullable(0)] [NullableContext(1)] internal sealed class LambdaObjectFactory : ObjectFactoryBase { private readonly Func factory; public LambdaObjectFactory(Func factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public override object Create(Type type) { return factory(type); } } [NullableContext(1)] [Nullable(0)] internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); [return: Nullable(2)] public virtual object CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual bool GetDictionary(IObjectDescriptor descriptor, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(descriptor.Type, typeof(IDictionary<, >)); if (implementedGenericInterface != null) { genericArguments = implementedGenericInterface.GetGenericArguments(); object obj = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), descriptor.Value); dictionary = obj as IDictionary; return true; } genericArguments = null; dictionary = null; return false; } public virtual Type GetValueType(Type type) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(type, typeof(IEnumerable<>)); if (!(implementedGenericInterface != null)) { return typeof(object); } return implementedGenericInterface.GetGenericArguments()[0]; } } [NullableContext(1)] [Nullable(0)] internal abstract class StaticObjectFactory : IObjectFactory { public abstract object Create(Type type); public abstract Array CreateArray(Type type, int count); public abstract bool IsDictionary(Type type); public abstract bool IsArray(Type type); public abstract bool IsList(Type type); public abstract Type GetKeyType(Type type); public abstract Type GetValueType(Type type); [return: Nullable(2)] public virtual object CreatePrimitive(Type type) { return Type.GetTypeCode(type) switch { TypeCode.Boolean => false, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, TypeCode.Int32 => 0, TypeCode.Int64 => 0L, TypeCode.SByte => (sbyte)0, TypeCode.UInt16 => (ushort)0, TypeCode.UInt32 => 0u, TypeCode.UInt64 => 0uL, TypeCode.Single => 0f, TypeCode.Double => 0.0, TypeCode.Decimal => 0m, TypeCode.Char => '\0', TypeCode.DateTime => default(DateTime), _ => null, }; } public bool GetDictionary(IObjectDescriptor descriptor, [Nullable(2)] out IDictionary dictionary, [Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { dictionary = null; genericArguments = null; return false; } } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { [NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (currentType == typeof(object)) { if (nodeEvent is SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } [Nullable(0)] [NullableContext(1)] internal class MappingNodeTypeResolver : INodeTypeResolver { private readonly IDictionary _mappings; public MappingNodeTypeResolver(IDictionary mappings) { if (mappings == null) { throw new ArgumentNullException("mappings"); } foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } } _mappings = mappings; } public bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (_mappings.TryGetValue(currentType, out var value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { [NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { throw new YamlException(nodeEvent.Start, nodeEvent.End, $"Encountered an unresolved tag '{nodeEvent.Tag}'"); } return false; } } [Nullable(0)] [NullableContext(1)] internal sealed class TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary tagMappings; public TagNodeTypeResolver(IDictionary tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out var value)) { currentType = value; return true; } return false; } } [Obsolete("The mechanism that this class uses to specify type names is non-standard. Register the tags explicitly instead of using this convention.")] internal sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver { [NullableContext(1)] bool INodeTypeResolver.Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Type type = Type.GetType(nodeEvent.Tag.Value.Substring(1), throwOnError: false); if (type != null) { currentType = type; return true; } } return false; } } internal sealed class YamlConvertibleTypeResolver : INodeTypeResolver { [NullableContext(1)] public bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { [NullableContext(1)] public bool Resolve([Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { internal sealed class ArrayNodeDeserializer : INodeDeserializer { [NullableContext(2)] [Nullable(0)] private sealed class ArrayList : IList, ICollection, IEnumerable { [Nullable(new byte[] { 1, 2 })] private object[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; [Nullable(1)] public object SyncRoot { [NullableContext(1)] get { return data; } } public ArrayList() { Clear(); } public int Add(object value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object value) { throw new NotSupportedException(); } int IList.IndexOf(object value) { throw new NotSupportedException(); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } [NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } [NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!expectedType.IsArray) { value = false; return false; } Type? elementType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(elementType, parser, nestedObjectDeserializer, arrayList, canUpdate: true); Array array = Array.CreateInstance(elementType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal abstract class CollectionDeserializer { [NullableContext(1)] protected static void DeserializeHelper(Type tItem, IParser parser, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, bool canUpdate, IObjectFactory objectFactory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? Mark.Empty, current?.End ?? Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(objectFactory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [NullableContext(1)] [Nullable(0)] internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public CollectionNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { bool canUpdate = true; Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); Type type; IList list; if (implementedGenericInterface != null) { type = implementedGenericInterface.GetGenericArguments()[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { canUpdate = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>)) != null; list = (IList)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(type), value); } } else { if (!typeof(IList).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); value = objectFactory.Create(expectedType); list = (IList)value; } DeserializeHelper(type, parser, nestedObjectDeserializer, list, canUpdate); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, bool canUpdate) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? Mark.Empty, current?.End ?? Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null); valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { result[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem); }; } else { result.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem)); } } } } [Nullable(0)] [NullableContext(1)] internal abstract class DictionaryDeserializer { private readonly bool duplicateKeyChecking; public DictionaryDeserializer(bool duplicateKeyChecking) { this.duplicateKeyChecking = duplicateKeyChecking; } private void TryAssign(IDictionary result, object key, object value, MappingStart propertyName) { if (duplicateKeyChecking && result.Contains(key)) { throw new YamlException(propertyName.Start, propertyName.End, $"Encountered duplicate key {key}"); } result[key] = value; } protected virtual void Deserialize(Type tKey, Type tValue, IParser parser, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IDictionary result) { MappingStart property = parser.Consume(); MappingEnd @event; while (!parser.TryConsume(out @event)) { object key = nestedObjectDeserializer(parser, tKey); object value = nestedObjectDeserializer(parser, tValue); IValuePromise valuePromise = value as IValuePromise; if (key is IValuePromise valuePromise2) { if (valuePromise == null) { valuePromise2.ValueAvailable += [NullableContext(2)] (object v) => { result[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += [NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, key, v, property); } else { value = v; hasFirstPart = true; } }; continue; } if (key == null) { throw new ArgumentException("Empty key names are not supported yet.", "key"); } if (valuePromise == null) { TryAssign(result, key, value, property); continue; } valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { result[key] = v; }; } } } [NullableContext(1)] [Nullable(0)] internal class DictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly IObjectFactory objectFactory; public DictionaryNodeDeserializer(IObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementedGenericInterface != null) { Type[] genericArguments = implementedGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } Deserialize(type, type2, parser, nestedObjectDeserializer, dictionary); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { [NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); if (implementedGenericInterface != expectedType) { value = null; return false; } type = implementedGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { [NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } [NullableContext(1)] private bool NodeIsNull(NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is YamlDotNet.Core.Events.Scalar { Style: ScalarStyle.Plain, IsKey: false, Value: var value }) { switch (value) { default: return value == "NULL"; case "": case "~": case "null": case "Null": return true; } } return false; } } [NullableContext(1)] [Nullable(0)] internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly ITypeInspector typeDescriptor; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.ignoreUnmatched = ignoreUnmatched; this.duplicateKeyChecking = duplicateKeyChecking; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); HashSet hashSet = new HashSet(StringComparer.Ordinal); MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); if (duplicateKeyChecking && !hashSet.Add(scalar.Value)) { throw new YamlException(scalar.Start, scalar.End, "Encountered duplicate key " + scalar.Value); } try { IPropertyDescriptor property = typeDescriptor.GetProperty(type, null, scalar.Value, ignoreUnmatched); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } object obj = nestedObjectDeserializer(parser, property.Type); if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { object value3 = typeConverter.ChangeType(v, property.Type); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type); property.Write(value, value2); } } catch (SerializationException ex) { throw new YamlException(scalar.Start, scalar.End, ex.Message); } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(scalar.Start, scalar.End, "Exception during deserialization", innerException); } } return true; } } [Nullable(0)] [NullableContext(1)] internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; private readonly bool attemptUnknownTypeDeserialization; private readonly ITypeConverter typeConverter; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; if (type.IsEnum()) { value = Enum.Parse(type, @event.Value, ignoreCase: true); return true; } TypeCode typeCode = type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { if (!@event.IsKey && attemptUnknownTypeDeserialization) { value = AttemptUnknownTypeDeserialization(@event); } else { value = @event.Value; } } else { value = typeConverter.ChangeType(@event.Value, expectedType); } break; } return true; } private object DeserializeBooleanHelper(string value) { bool flag; if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { flag = true; } else { if (!Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } flag = false; } return flag; } private static object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; int i = 0; bool flag = false; ulong num = 0uL; if (value[0] == '-') { i++; flag = true; } else if (value[0] == '+') { i++; } if (value[i] == '0') { int num2; if (i == value.Length - 1) { num2 = 10; num = 0uL; } else { i++; if (value[i] == 'b') { num2 = 2; i++; } else if (value[i] == 'x') { num2 = 16; i++; } else { num2 = 8; } } for (; i < value.Length; i++) { if (value[i] != '_') { builder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(builder.ToString(), num2); break; case 16: num = ulong.Parse(builder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", "")); } } if (!flag) { return CastInteger(num, typeCode); } long number = ((num != 9223372036854775808uL) ? checked(-(long)num) : long.MinValue); return CastInteger(number, typeCode); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private static object CastInteger(long number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => (ulong)number, _ => number, }); } private static object CastInteger(ulong number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => (long)number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => number, _ => number, }); } [return: Nullable(2)] private static object AttemptUnknownTypeDeserialization(YamlDotNet.Core.Events.Scalar value) { if (value.Style == ScalarStyle.SingleQuoted || value.Style == ScalarStyle.DoubleQuoted || value.Style == ScalarStyle.Folded) { return value.Value; } string v = value.Value; switch (v) { case "": case "~": case "null": case "Null": case "NULL": return null; case "true": case "True": case "TRUE": return true; case "false": case "False": case "FALSE": return false; default: { object value2; if (Regex.IsMatch(v, "0x[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 16), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 16), out value2)) { return v; } } else if (Regex.IsMatch(v, "0o[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 8), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 8), out value2)) { return v; } } else { if (!Regex.IsMatch(v, "[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?")) { if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (v.StartsWith("-")) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } if (!TryAndSwallow(() => byte.Parse(v), out value2) && !TryAndSwallow(() => short.Parse(v), out value2) && !TryAndSwallow(() => int.Parse(v), out value2) && !TryAndSwallow(() => long.Parse(v), out value2) && !TryAndSwallow(() => ulong.Parse(v), out value2) && !TryAndSwallow(() => float.Parse(v), out value2) && !TryAndSwallow(() => double.Parse(v), out value2)) { return v; } } return value2; } } } private static bool TryAndSwallow(Func attempt, [Nullable(2)] out object value) { try { value = attempt(); return true; } catch { value = null; return false; } } } [NullableContext(1)] [Nullable(0)] internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { [NullableContext(2)] [Nullable(0)] private sealed class ArrayList : IList, ICollection, IEnumerable { [Nullable(new byte[] { 1, 2 })] private object[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; [Nullable(1)] public object SyncRoot { [NullableContext(1)] get { return data; } } public ArrayList() { Clear(); } public int Add(object value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object value) { throw new NotSupportedException(); } int IList.IndexOf(object value) { throw new NotSupportedException(); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } [NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly StaticObjectFactory factory; public StaticArrayNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!factory.IsArray(expectedType)) { value = false; return false; } Type valueType = factory.GetValueType(expectedType); ArrayList arrayList = new ArrayList(); StaticCollectionNodeDeserializer.DeserializeHelper(valueType, parser, nestedObjectDeserializer, arrayList, factory); Array array = factory.CreateArray(expectedType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } [Nullable(0)] [NullableContext(1)] internal sealed class StaticCollectionNodeDeserializer : INodeDeserializer { private readonly StaticObjectFactory factory; public StaticCollectionNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!factory.IsList(expectedType)) { value = null; return false; } DeserializeHelper(result: (IList)(value = factory.Create(expectedType) as IList), tItem: factory.GetValueType(expectedType), parser: parser, nestedObjectDeserializer: nestedObjectDeserializer, factory: factory); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, IObjectFactory factory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { _ = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += [NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [NullableContext(1)] [Nullable(0)] internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory _objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { _objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser reader, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (_objectFactory.IsDictionary(expectedType)) { if (!(_objectFactory.Create(expectedType) is IDictionary dictionary)) { value = null; return false; } Type keyType = _objectFactory.GetKeyType(expectedType); Type valueType = _objectFactory.GetValueType(expectedType); value = dictionary; base.Deserialize(keyType, valueType, reader, nestedObjectDeserializer, dictionary); return true; } value = null; return false; } } [NullableContext(1)] [Nullable(0)] internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly IEnumerable converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = converters ?? throw new ArgumentNullException("converters"); } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { IYamlTypeConverter yamlTypeConverter = converters.FirstOrDefault([NullableContext(0)] (IYamlTypeConverter c) => c.Accepts(expectedType)); if (yamlTypeConverter == null) { value = null; return false; } value = yamlTypeConverter.ReadYaml(parser, expectedType); return true; } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser, expectedType, [return: Nullable(2)] (Type type) => nestedObjectDeserializer(parser, type)); value = yamlConvertible; return true; } value = null; return false; } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (typeof(IYamlSerializable).IsAssignableFrom(expectedType)) { IYamlSerializable yamlSerializable = (IYamlSerializable)objectFactory.Create(expectedType); yamlSerializable.ReadYaml(parser); value = yamlSerializable; return true; } value = null; return false; } } } namespace YamlDotNet.Serialization.NamingConventions { internal sealed class CamelCaseNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value.ToCamelCase(); } } internal sealed class HyphenatedNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value.FromCamelCase("-"); } } internal sealed class LowerCaseNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value.ToCamelCase().ToLower(); } } internal sealed class NullNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value; } } internal sealed class PascalCaseNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value.ToPascalCase(); } } internal sealed class UnderscoredNamingConvention : INamingConvention { [Nullable(1)] public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } [NullableContext(1)] public string Apply(string value) { return value.FromCamelCase("_"); } } } namespace YamlDotNet.Serialization.EventEmitters { [NullableContext(1)] [Nullable(0)] internal abstract class ChainedEventEmitter : IEventEmitter { protected readonly IEventEmitter nextEmitter; protected ChainedEventEmitter(IEventEmitter nextEmitter) { this.nextEmitter = nextEmitter ?? throw new ArgumentNullException("nextEmitter"); } public virtual void Emit(AliasEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } } [NullableContext(1)] [Nullable(0)] internal sealed class JsonEventEmitter : ChainedEventEmitter { public JsonEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { } public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) { eventInfo.NeedsExpansion = true; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { eventInfo.IsPlainImplicit = true; eventInfo.Style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.RenderedValue = "null"; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum()) { eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; } else { eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } [Nullable(0)] [NullableContext(1)] internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly bool requireTagWhenStaticAndActualTypesAreDifferent; private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; [Nullable(2)] private readonly Regex isSpecialStringValue_Regex; private static readonly string SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\\.inf|\\.Inf|\\.INF)|\\.nan|\\.NaN|\\.NAN)$"; private static readonly string CombinedYaml1_1SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?0b[0-1_]+|[-+]?0o?[0-7_]+|[-+]?(0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(:[0-5]?[0-9])+|[-+]?([0-9][0-9_]*)?\\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(inf|Inf|INF)|\\.(nan|NaN|NAN))$"; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(quoteYaml1_1Strings ? CombinedYaml1_1SpecialStrings_Pattern : SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings) : base(nextEmitter) { this.requireTagWhenStaticAndActualTypesAreDifferent = requireTagWhenStaticAndActualTypesAreDifferent; this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { ScalarStyle style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = JsonSchema.Tags.Bool; eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum) { eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); } else { eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } eventInfo.IsPlainImplicit = true; if (eventInfo.Style == ScalarStyle.Any) { eventInfo.Style = style; } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } private void AssignTypeIfNeeded(ObjectEventInfo eventInfo) { if (tagMappings.TryGetValue(eventInfo.Source.Type, out var value)) { eventInfo.Tag = value; } else if (requireTagWhenStaticAndActualTypesAreDifferent && eventInfo.Source.Value != null && eventInfo.Source.Type != eventInfo.Source.StaticType) { throw new YamlException("Cannot serialize type '" + eventInfo.Source.Type.FullName + "' where a '" + eventInfo.Source.StaticType.FullName + "' was expected because no tag mapping has been registered for '" + eventInfo.Source.Type.FullName + "', which means that it won't be possible to deserialize the document.\nRegister a tag mapping using the SerializerBuilder.WithTagMapping method.\n\nE.g: builder.WithTagMapping(\"!" + eventInfo.Source.Type.Name + "\", typeof(" + eventInfo.Source.Type.FullName + "));"); } } private bool IsSpecialStringValue(string value) { if (value.Trim() == string.Empty) { return true; } return isSpecialStringValue_Regex?.IsMatch(value) ?? false; } } [NullableContext(1)] [Nullable(0)] internal sealed class WriterEventEmitter : IEventEmitter { void IEventEmitter.Emit(AliasEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(eventInfo.Alias)); } void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); } void IEventEmitter.Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingEnd()); } void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceEnd()); } } } namespace YamlDotNet.Serialization.Converters { [Nullable(0)] [NullableContext(1)] internal class DateTimeConverter : IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly bool doubleQuotes; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, [Nullable(2)] IFormatProvider provider = null, bool doubleQuotes = false, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.doubleQuotes = doubleQuotes; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type) { return EnsureDateTimeKind(DateTime.ParseExact(parser.Consume().Value, style: (kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal, formats: formats, provider: provider), kind); } public void WriteYaml(IEmitter emitter, [Nullable(2)] object value, Type type) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, doubleQuotes ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } private static DateTime EnsureDateTimeKind(DateTime dt, DateTimeKind kind) { if (dt.Kind == DateTimeKind.Local && kind == DateTimeKind.Utc) { return dt.ToUniversalTime(); } if (dt.Kind == DateTimeKind.Utc && kind == DateTimeKind.Local) { return dt.ToLocalTime(); } return dt; } } [NullableContext(1)] [Nullable(0)] internal class GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(IParser parser, Type type) { return new Guid(parser.Consume().Value); } public void WriteYaml(IEmitter emitter, [Nullable(2)] object value, Type type) { Guid guid = (Guid)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } [NullableContext(1)] [Nullable(0)] internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type) { return Type.GetType(parser.Consume().Value, throwOnError: true); } public void WriteYaml(IEmitter emitter, [Nullable(2)] object value, Type type) { Type type2 = (Type)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, type2.AssemblyQualifiedName, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization { [NullableContext(1)] internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator<[Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator<[Nullable(2)] T>(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : IParser { [Nullable(1)] private readonly LinkedList buffer; [Nullable(new byte[] { 2, 1 })] private LinkedListNode current; [Nullable(2)] public ParsingEvent Current { [NullableContext(2)] get { return current?.Value; } } [NullableContext(1)] public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength) { buffer = new LinkedList(); buffer.AddLast(parserToBuffer.Consume()); int num = 0; do { ParsingEvent parsingEvent = parserToBuffer.Consume(); num += parsingEvent.NestingIncrease; buffer.AddLast(parsingEvent); if (maxDepth > -1 && num > maxDepth) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max depth"); } if (maxLength > -1 && buffer.Count > maxLength) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max length"); } } while (num >= 0); current = buffer.First; } public bool MoveNext() { current = current?.Next; return current != null; } public void Reset() { current = buffer.First; } } [NullableContext(1)] [Nullable(0)] internal class TypeDiscriminatingNodeDeserializer : INodeDeserializer { private readonly IList innerDeserializers; private readonly IList typeDiscriminators; private readonly int maxDepthToBuffer; private readonly int maxLengthToBuffer; public TypeDiscriminatingNodeDeserializer(IList innerDeserializers, IList typeDiscriminators, int maxDepthToBuffer, int maxLengthToBuffer) { this.innerDeserializers = innerDeserializers; this.typeDiscriminators = typeDiscriminators; this.maxDepthToBuffer = maxDepthToBuffer; this.maxLengthToBuffer = maxLengthToBuffer; } public bool Deserialize(IParser reader, Type expectedType, [Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [Nullable(2)] out object value) { if (!reader.Accept(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where([NullableContext(0)] (ITypeDiscriminator t) => t.BaseType.IsAssignableFrom(expectedType)); if (!enumerable.Any()) { value = null; return false; } Mark start = reader.Current.Start; Type expectedType2 = expectedType; ParserBuffer parserBuffer; try { parserBuffer = new ParserBuffer(reader, maxDepthToBuffer, maxLengthToBuffer); } catch (Exception innerException) { throw new YamlException(in start, reader.Current.End, "Failed to buffer yaml node", innerException); } try { foreach (ITypeDiscriminator item in enumerable) { parserBuffer.Reset(); if (item.TryDiscriminate(parserBuffer, out var suggestedType)) { expectedType2 = suggestedType; break; } } } catch (Exception innerException2) { throw new YamlException(in start, reader.Current.End, "Failed to discriminate type", innerException2); } parserBuffer.Reset(); foreach (INodeDeserializer innerDeserializer in innerDeserializers) { if (innerDeserializer.Deserialize(parserBuffer, expectedType2, nestedObjectDeserializer, out value)) { return true; } } value = null; return false; } } [NullableContext(1)] [Nullable(0)] internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator<[Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator<[Nullable(2)] T>(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { [NullableContext(1)] internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(IParser buffer, [Nullable(2)] out Type suggestedType); } [Nullable(0)] [NullableContext(1)] internal class KeyValueTypeDiscriminator : ITypeDiscriminator { private readonly string targetKey; private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public KeyValueTypeDiscriminator(Type baseType, string targetKey, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.targetKey = targetKey; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, [Nullable(2)] out Type suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar2) => targetKey == scalar2.Value, out var _, out var value) && value is YamlDotNet.Core.Events.Scalar scalar && typeMapping.TryGetValue(scalar.Value, out var value2)) { suggestedType = value2; return true; } suggestedType = null; return false; } } [Nullable(0)] [NullableContext(1)] internal class UniqueKeyTypeDiscriminator : ITypeDiscriminator { private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public UniqueKeyTypeDiscriminator(Type baseType, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, [Nullable(2)] out Type suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => typeMapping.ContainsKey(scalar.Value), out var key, out var _)) { suggestedType = typeMapping[key.Value]; return true; } suggestedType = null; return false; } } } namespace YamlDotNet.RepresentationModel { [NullableContext(1)] [Nullable(0)] internal class DocumentLoadingState { private readonly IDictionary anchors = new Dictionary(); private readonly IList nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } if (anchors.ContainsKey(node.Anchor)) { anchors[node.Anchor] = node; } else { anchors.Add(node.Anchor, node); } } public YamlNode GetNode(AnchorName anchor, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out var value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } [NullableContext(2)] public bool TryGetNode(AnchorName anchor, [NotNullWhen(true)] out YamlNode node) { return anchors.TryGetValue(anchor, out node); } public void AddNodeWithUnresolvedAliases(YamlNode node) { nodesWithUnresolvedAliases.Add(node); } public void ResolveAliases() { foreach (YamlNode nodesWithUnresolvedAlias in nodesWithUnresolvedAliases) { nodesWithUnresolvedAlias.ResolveAliases(this); } } } [NullableContext(1)] [Nullable(0)] internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } [NullableContext(1)] internal interface IYamlVisitor { void Visit(YamlStream stream); void Visit(YamlDocument document); void Visit(YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(YamlMappingNode mapping); } [NullableContext(1)] [Nullable(0)] internal class LibYamlEventStream { private readonly IParser parser; public LibYamlEventStream(IParser iParser) { parser = iParser ?? throw new ArgumentNullException("iParser"); } public void WriteTo(TextWriter textWriter) { while (parser.MoveNext()) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.AnchorAlias anchorAlias)) { if (!(current is YamlDotNet.Core.Events.DocumentEnd documentEnd)) { if (!(current is YamlDotNet.Core.Events.DocumentStart documentStart)) { if (!(current is MappingEnd)) { if (!(current is MappingStart nodeEvent)) { if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (!(current is SequenceEnd)) { if (!(current is SequenceStart nodeEvent2)) { if (!(current is YamlDotNet.Core.Events.StreamEnd)) { if (current is YamlDotNet.Core.Events.StreamStart) { textWriter.Write("+STR"); } } else { textWriter.Write("-STR"); } } else { textWriter.Write("+SEQ"); WriteAnchorAndTag(textWriter, nodeEvent2); } } else { textWriter.Write("-SEQ"); } } else { textWriter.Write("=VAL"); WriteAnchorAndTag(textWriter, scalar); switch (scalar.Style) { case ScalarStyle.DoubleQuoted: textWriter.Write(" \""); break; case ScalarStyle.SingleQuoted: textWriter.Write(" '"); break; case ScalarStyle.Folded: textWriter.Write(" >"); break; case ScalarStyle.Literal: textWriter.Write(" |"); break; default: textWriter.Write(" :"); break; } string value = scalar.Value; foreach (char c in value) { switch (c) { case '\b': textWriter.Write("\\b"); break; case '\t': textWriter.Write("\\t"); break; case '\n': textWriter.Write("\\n"); break; case '\r': textWriter.Write("\\r"); break; case '\\': textWriter.Write("\\\\"); break; default: textWriter.Write(c); break; } } } } else { textWriter.Write("+MAP"); WriteAnchorAndTag(textWriter, nodeEvent); } } else { textWriter.Write("-MAP"); } } else { textWriter.Write("+DOC"); if (!documentStart.IsImplicit) { textWriter.Write(" ---"); } } } else { textWriter.Write("-DOC"); if (!documentEnd.IsImplicit) { textWriter.Write(" ..."); } } } else { textWriter.Write("=ALI *"); textWriter.Write(anchorAlias.Value); } textWriter.WriteLine(); } } private void WriteAnchorAndTag(TextWriter textWriter, NodeEvent nodeEvent) { if (!nodeEvent.Anchor.IsEmpty) { textWriter.Write(" &"); textWriter.Write(nodeEvent.Anchor); } if (!nodeEvent.Tag.IsEmpty) { textWriter.Write(" <"); textWriter.Write(nodeEvent.Tag.Value); textWriter.Write(">"); } } } [NullableContext(1)] [Nullable(0)] internal class YamlAliasNode : YamlNode { public override YamlNodeType NodeType => YamlNodeType.Alias; internal YamlAliasNode(AnchorName anchor) { base.Anchor = anchor; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); } public override void Accept(IYamlVisitor visitor) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); } [NullableContext(2)] public override bool Equals(object obj) { if (obj is YamlAliasNode yamlAliasNode && Equals(yamlAliasNode)) { return object.Equals(base.Anchor, yamlAliasNode.Anchor); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal override string ToString(RecursionLevel level) { return "*" + base.Anchor.ToString(); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } } [Nullable(0)] [NullableContext(1)] internal class YamlDocument { [Nullable(0)] private class AnchorAssigningVisitor : YamlVisitorBase { private readonly HashSet existingAnchors = new HashSet(); private readonly Dictionary visitedNodes = new Dictionary(); public void AssignAnchors(YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (KeyValuePair visitedNode in visitedNodes) { if (!visitedNode.Value) { continue; } AnchorName anchorName; if (!visitedNode.Key.Anchor.IsEmpty && !existingAnchors.Contains(visitedNode.Key.Anchor)) { anchorName = visitedNode.Key.Anchor; } else { do { anchorName = new AnchorName(random.Next().ToString(CultureInfo.InvariantCulture)); } while (existingAnchors.Contains(anchorName)); } existingAnchors.Add(anchorName); visitedNode.Key.Anchor = anchorName; } } private bool VisitNodeAndFindDuplicates(YamlNode node) { if (visitedNodes.TryGetValue(node, out var value)) { if (!value) { visitedNodes[node] = true; } return !value; } visitedNodes.Add(node, value: false); return false; } public override void Visit(YamlScalarNode scalar) { VisitNodeAndFindDuplicates(scalar); } public override void Visit(YamlMappingNode mapping) { if (!VisitNodeAndFindDuplicates(mapping)) { base.Visit(mapping); } } public override void Visit(YamlSequenceNode sequence) { if (!VisitNodeAndFindDuplicates(sequence)) { base.Visit(sequence); } } } public YamlNode RootNode { get; private set; } public IEnumerable AllNodes => RootNode.AllNodes; public YamlDocument(YamlNode rootNode) { RootNode = rootNode; } public YamlDocument(string rootNode) { RootNode = new YamlScalarNode(rootNode); } internal YamlDocument(IParser parser) { DocumentLoadingState documentLoadingState = new DocumentLoadingState(); parser.Consume(); YamlDotNet.Core.Events.DocumentEnd @event; while (!parser.TryConsume(out @event)) { RootNode = YamlNode.ParseNode(parser, documentLoadingState); if (RootNode is YamlAliasNode) { throw new YamlException("A document cannot contain only an alias"); } } documentLoadingState.ResolveAliases(); if (RootNode == null) { throw new ArgumentException("Atempted to parse an empty document"); } } private void AssignAnchors() { new AnchorAssigningVisitor().AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: false)); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } } [Nullable(0)] [NullableContext(1)] internal sealed class YamlMappingNode : YamlNode, IEnumerable>, IEnumerable, IYamlConvertible { private readonly OrderedDictionary children = new OrderedDictionary(); public IOrderedDictionary Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { MappingStart mappingStart = parser.Consume(); Load(mappingStart, state); Style = mappingStart.Style; bool flag = false; MappingEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); YamlNode yamlNode2 = YamlNode.ParseNode(parser, state); try { children.Add(yamlNode, yamlNode2); } catch (ArgumentException innerException) { throw new YamlException(yamlNode.Start, yamlNode.End, "Duplicate key", innerException); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode([Nullable(new byte[] { 1, 0, 1, 1 })] params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode([Nullable(new byte[] { 1, 0, 1, 1 })] IEnumerable> children) { foreach (KeyValuePair child in children) { this.children.Add(child); } } public YamlMappingNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlMappingNode(IEnumerable children) { using IEnumerator enumerator = children.GetEnumerator(); while (enumerator.MoveNext()) { YamlNode current = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(current, enumerator.Current); } } public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } internal override void ResolveAliases(DocumentLoadingState state) { Dictionary dictionary = null; Dictionary dictionary2 = null; foreach (KeyValuePair child in children) { if (child.Key is YamlAliasNode) { if (dictionary == null) { dictionary = new Dictionary(); } dictionary.Add(child.Key, state.GetNode(child.Key.Anchor, child.Key.Start, child.Key.End)); } if (child.Value is YamlAliasNode) { if (dictionary2 == null) { dictionary2 = new Dictionary(); } dictionary2.Add(child.Key, state.GetNode(child.Value.Anchor, child.Value.Start, child.Value.End)); } } if (dictionary2 != null) { foreach (KeyValuePair item in dictionary2) { children[item.Key] = item.Value; } } if (dictionary == null) { return; } foreach (KeyValuePair item2 in dictionary) { YamlNode value = children[item2.Key]; children.Remove(item2.Key); children.Add(item2.Value, value); } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(base.Anchor, base.Tag, isImplicit: true, Style)); foreach (KeyValuePair child in children) { child.Key.Save(emitter, state); child.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } [NullableContext(2)] public override bool Equals(object obj) { if (!(obj is YamlMappingNode yamlMappingNode) || !object.Equals(base.Tag, yamlMappingNode.Tag) || children.Count != yamlMappingNode.children.Count) { return false; } foreach (KeyValuePair child in children) { if (!yamlMappingNode.children.TryGetValue(child.Key, out var value) || !object.Equals(child.Value, value)) { return false; } } return true; } public override int GetHashCode() { int num = base.GetHashCode(); foreach (KeyValuePair child in children) { num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Key); num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value); } return num; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair child in children) { foreach (YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("{ "); foreach (KeyValuePair child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } builder.Append(" }"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } [return: Nullable(new byte[] { 1, 0, 1, 1 })] public IEnumerator> GetEnumerator() { return children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } public static YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } YamlMappingNode yamlMappingNode = new YamlMappingNode(); foreach (PropertyInfo publicProperty in mapping.GetType().GetPublicProperties()) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); YamlNode yamlNode = value as YamlNode; if (yamlNode == null) { yamlNode = Convert.ToString(value) ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } [Nullable(0)] [NullableContext(1)] internal abstract class YamlNode { private const int MaximumRecursionLevel = 1000; internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; public AnchorName Anchor { get; set; } public TagName Tag { get; set; } public Mark Start { get; private set; } = Mark.Empty; public Mark End { get; private set; } = Mark.Empty; public IEnumerable AllNodes { get { RecursionLevel level = new RecursionLevel(1000); return SafeAllNodes(level); } } public abstract YamlNodeType NodeType { get; } public YamlNode this[int index] { get { if (!(this is YamlSequenceNode yamlSequenceNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {index}. Only Sequences can be indexed by number."); } return yamlSequenceNode.Children[index]; } } public YamlNode this[YamlNode key] { get { if (!(this is YamlMappingNode yamlMappingNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {key}. Only Mappings can be indexed by key."); } return yamlMappingNode.Children[key]; } } internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) { Tag = yamlEvent.Tag; if (!yamlEvent.Anchor.IsEmpty) { Anchor = yamlEvent.Anchor; state.AddAnchor(this); } Start = yamlEvent.Start; End = yamlEvent.End; } internal static YamlNode ParseNode(IParser parser, DocumentLoadingState state) { if (parser.Accept(out var _)) { return new YamlScalarNode(parser, state); } if (parser.Accept(out var _)) { return new YamlSequenceNode(parser, state); } if (parser.Accept(out var _)) { return new YamlMappingNode(parser, state); } if (parser.TryConsume(out var event4)) { if (!state.TryGetNode(event4.Value, out var node)) { return new YamlAliasNode(event4.Value); } return node; } throw new ArgumentException("The current event is of an unsupported type.", "parser"); } internal abstract void ResolveAliases(DocumentLoadingState state); internal void Save(IEmitter emitter, EmitterState state) { if (!Anchor.IsEmpty && !state.EmittedAnchors.Add(Anchor)) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(Anchor)); } else { Emit(emitter, state); } } internal abstract void Emit(IEmitter emitter, EmitterState state); public abstract void Accept(IYamlVisitor visitor); public override string ToString() { RecursionLevel recursionLevel = new RecursionLevel(1000); return ToString(recursionLevel); } internal abstract string ToString(RecursionLevel level); internal abstract IEnumerable SafeAllNodes(RecursionLevel level); public static implicit operator YamlNode(string value) { return new YamlScalarNode(value); } public static implicit operator YamlNode(string[] sequence) { return new YamlSequenceNode(((IEnumerable)sequence).Select((Func)([NullableContext(0)] (string i) => i))); } [return: Nullable(2)] public static explicit operator string(YamlNode node) { if (!(node is YamlScalarNode yamlScalarNode)) { throw new ArgumentException($"Attempted to convert a '{node.NodeType}' to string. This conversion is valid only for Scalars."); } return yamlScalarNode.Value; } } [NullableContext(1)] [Nullable(0)] internal sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer { public bool Equals([AllowNull] YamlNode x, [AllowNull] YamlNode y) { return x == y; } public int GetHashCode(YamlNode obj) { return obj.GetHashCode(); } } internal enum YamlNodeType { Alias, Mapping, Scalar, Sequence } [DebuggerDisplay("{Value}")] [Nullable(0)] [NullableContext(1)] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { [Nullable(2)] [field: Nullable(2)] public string Value { [NullableContext(2)] get; [NullableContext(2)] set; } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); Value = scalar.Value; Style = scalar.Style; } public YamlScalarNode() { } [NullableContext(2)] public YamlScalarNode(string value) { Value = value; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, base.Tag, Value ?? string.Empty, Style, base.Tag.IsEmpty, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } [NullableContext(2)] public override bool Equals(object obj) { if (obj is YamlScalarNode yamlScalarNode && object.Equals(base.Tag, yamlScalarNode.Tag)) { return object.Equals(Value, yamlScalarNode.Value); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(base.Tag.GetHashCode(), Value); } [return: Nullable(2)] public static explicit operator string(YamlScalarNode value) { return value.Value; } internal override string ToString(RecursionLevel level) { return Value ?? string.Empty; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } [Nullable(0)] [DebuggerDisplay("Count = {children.Count}")] [NullableContext(1)] internal sealed class YamlSequenceNode : YamlNode, IEnumerable, IEnumerable, IYamlConvertible { private readonly IList children = new List(); public IList Children => children; public SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { SequenceStart sequenceStart = parser.Consume(); Load(sequenceStart, state); Style = sequenceStart.Style; bool flag = false; SequenceEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); children.Add(yamlNode); flag = flag || yamlNode is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlSequenceNode(IEnumerable children) { foreach (YamlNode child in children) { this.children.Add(child); } } public void Add(YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new YamlScalarNode(child)); } internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } [NullableContext(2)] public override bool Equals(object obj) { if (!(obj is YamlSequenceNode yamlSequenceNode) || !object.Equals(base.Tag, yamlSequenceNode.Tag) || children.Count != yamlSequenceNode.children.Count) { return false; } for (int i = 0; i < children.Count; i++) { if (!object.Equals(children[i], yamlSequenceNode.children[i])) { return false; } } return true; } public override int GetHashCode() { int h = 0; foreach (YamlNode child in children) { h = YamlDotNet.Core.HashCode.CombineHashCodes(h, child); } return YamlDotNet.Core.HashCode.CombineHashCodes(h, base.Tag); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (YamlNode child in children) { foreach (YamlNode item in child.SafeAllNodes(level)) { yield return item; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("[ "); foreach (YamlNode child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append(child.ToString(level)); } builder.Append(" ]"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } public IEnumerator GetEnumerator() { return Children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } [NullableContext(1)] [Nullable(0)] internal class YamlStream : IEnumerable, IEnumerable { private readonly IList documents = new List(); public IList Documents => documents; public YamlStream() { } public YamlStream(params YamlDocument[] documents) : this((IEnumerable)documents) { } public YamlStream(IEnumerable documents) { foreach (YamlDocument document in documents) { this.documents.Add(document); } } public void Add(YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(IParser parser) { documents.Clear(); parser.Consume(); YamlDotNet.Core.Events.StreamEnd @event; while (!parser.TryConsume(out @event)) { YamlDocument item = new YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); foreach (YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NullableContext(1)] [Nullable(0)] [Obsolete("Use YamlVisitorBase")] internal abstract class YamlVisitor : IYamlVisitor { protected virtual void Visit(YamlStream stream) { } protected virtual void Visited(YamlStream stream) { } protected virtual void Visit(YamlDocument document) { } protected virtual void Visited(YamlDocument document) { } protected virtual void Visit(YamlScalarNode scalar) { } protected virtual void Visited(YamlScalarNode scalar) { } protected virtual void Visit(YamlSequenceNode sequence) { } protected virtual void Visited(YamlSequenceNode sequence) { } protected virtual void Visit(YamlMappingNode mapping) { } protected virtual void Visited(YamlMappingNode mapping) { } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { child.Key.Accept(this); child.Value.Accept(this); } } void IYamlVisitor.Visit(YamlStream stream) { Visit(stream); VisitChildren(stream); Visited(stream); } void IYamlVisitor.Visit(YamlDocument document) { Visit(document); VisitChildren(document); Visited(document); } void IYamlVisitor.Visit(YamlScalarNode scalar) { Visit(scalar); Visited(scalar); } void IYamlVisitor.Visit(YamlSequenceNode sequence) { Visit(sequence); VisitChildren(sequence); Visited(sequence); } void IYamlVisitor.Visit(YamlMappingNode mapping) { Visit(mapping); VisitChildren(mapping); Visited(mapping); } } [NullableContext(1)] [Nullable(0)] internal abstract class YamlVisitorBase : IYamlVisitor { public virtual void Visit(YamlStream stream) { VisitChildren(stream); } public virtual void Visit(YamlDocument document) { VisitChildren(document); } public virtual void Visit(YamlScalarNode scalar) { } public virtual void Visit(YamlSequenceNode sequence) { VisitChildren(sequence); } public virtual void Visit(YamlMappingNode mapping) { VisitChildren(mapping); } protected virtual void VisitPair(YamlNode key, YamlNode value) { key.Accept(this); value.Accept(this); } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { VisitPair(child.Key, child.Value); } } } } namespace YamlDotNet.Helpers { [NullableContext(1)] [Nullable(0)] [DebuggerStepThrough] internal sealed class ConcurrentObjectPool where T : class { [NullableContext(0)] [DebuggerDisplay("{value,nq}")] private struct Element { [Nullable(2)] internal T value; } [NullableContext(0)] internal delegate T Factory(); [Nullable(2)] private T firstItem; [Nullable(new byte[] { 1, 0, 0 })] private readonly Element[] items; [Nullable(new byte[] { 1, 0 })] private readonly Factory factory; internal ConcurrentObjectPool([Nullable(new byte[] { 1, 0 })] Factory factory) : this(factory, Environment.ProcessorCount * 2) { } internal ConcurrentObjectPool([Nullable(new byte[] { 1, 0 })] Factory factory, int size) { this.factory = factory; items = new Element[size - 1]; } private T CreateInstance() { return factory(); } internal T Allocate() { T val = firstItem; if (val == null || val != Interlocked.CompareExchange(ref firstItem, null, val)) { val = AllocateSlow(); } return val; } private T AllocateSlow() { Element[] array = items; for (int i = 0; i < array.Length; i++) { T value = array[i].value; if (value != null && value == Interlocked.CompareExchange(ref array[i].value, null, value)) { return value; } } return CreateInstance(); } internal void Free(T obj) { if (firstItem == null) { firstItem = obj; } else { FreeSlow(obj); } } private void FreeSlow(T obj) { Element[] array = items; for (int i = 0; i < array.Length; i++) { if (array[i].value == null) { array[i].value = obj; break; } } } [Conditional("DEBUG")] private void Validate(object obj) { Element[] array = items; for (int i = 0; i < array.Length && array[i].value != null; i++) { } } } [Nullable(0)] [NullableContext(1)] internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { PropertyInfo propertyInfo = TryGetMemberExpression(propertyAccessor); if (propertyInfo == null) { throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } return propertyInfo; } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression<[Nullable(0)] TMemberInfo>(LambdaExpression lambdaExpression) where TMemberInfo : MemberInfo { if (lambdaExpression.Parameters.Count != 1) { return null; } Expression expression = lambdaExpression.Body; if (expression is UnaryExpression unaryExpression) { if (unaryExpression.NodeType != ExpressionType.Convert) { return null; } expression = unaryExpression.Operand; } if (expression is MemberExpression memberExpression) { if (memberExpression.Expression != lambdaExpression.Parameters[0]) { return null; } return memberExpression.Member as TMemberInfo; } return null; } } [NullableContext(2)] [Nullable(0)] internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { [Nullable(1)] private readonly ICollection genericCollection; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public object this[int index] { get { throw new NotSupportedException(); } set { ((IList)genericCollection)[index] = (T)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } [Nullable(1)] public object SyncRoot { [NullableContext(1)] get { throw new NotSupportedException(); } } [NullableContext(1)] public GenericCollectionToNonGenericAdapter(ICollection genericCollection) { this.genericCollection = genericCollection ?? throw new ArgumentNullException("genericCollection"); } public int Add(object value) { int count = genericCollection.Count; genericCollection.Add((T)value); return count; } public void Clear() { genericCollection.Clear(); } public bool Contains(object value) { throw new NotSupportedException(); } public int IndexOf(object value) { throw new NotSupportedException(); } public void Insert(int index, object value) { throw new NotSupportedException(); } public void Remove(object value) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } [NullableContext(1)] public void CopyTo(Array array, int index) { throw new NotSupportedException(); } [NullableContext(1)] public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } [NullableContext(1)] [Nullable(0)] internal sealed class GenericDictionaryToNonGenericAdapterNullable(2)] TValue> : IDictionary, ICollection, IEnumerable { [Nullable(0)] private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { [Nullable(new byte[] { 1, 0, 1, 1 })] private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; [Nullable(2)] public object Value { [NullableContext(2)] get { return enumerator.Current.Value; } } public object Current => Entry; public DictionaryEnumerator([Nullable(new byte[] { 1, 0, 1, 1 })] IEnumerator> enumerator) { this.enumerator = enumerator; } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } private readonly IDictionary genericDictionary; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public ICollection Keys { get { throw new NotSupportedException(); } } public ICollection Values { get { throw new NotSupportedException(); } } [Nullable(2)] public object this[object key] { [return: Nullable(2)] get { throw new NotSupportedException(); } [param: Nullable(2)] set { genericDictionary[(TKey)key] = (TValue)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericDictionaryToNonGenericAdapter(IDictionary genericDictionary) { this.genericDictionary = genericDictionary ?? throw new ArgumentNullException("genericDictionary"); } public void Add(object key, [Nullable(2)] object value) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(object key) { throw new NotSupportedException(); } public IDictionaryEnumerator GetEnumerator() { return new DictionaryEnumerator(genericDictionary.GetEnumerator()); } public void Remove(object key) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NullableContext(1)] internal interface IOrderedDictionaryNullable(2)] TValue> : IDictionary, ICollection>, IEnumerable>, IEnumerable { [Nullable(new byte[] { 0, 1, 1 })] KeyValuePair this[int index] { [return: Nullable(new byte[] { 0, 1, 1 })] get; [param: Nullable(new byte[] { 0, 1, 1 })] set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } internal static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] [NullableContext(1)] [Nullable(0)] internal sealed class OrderedDictionaryNullable(2)] TValue> : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable { [Nullable(0)] private class KeyCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TKey item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TKey item) { return Enumerable.Contains(orderedDictionary.dictionary.Keys, item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select([NullableContext(0)] (KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Nullable(0)] private class ValueCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TValue item) { return orderedDictionary.dictionary.Values.Contains(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select([NullableContext(0)] (KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; [Nullable(new byte[] { 1, 0, 1, 1 })] private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); dictionary[key] = value; list[index] = new KeyValuePair(key, value); } else { Add(key, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; [Nullable(new byte[] { 0, 1, 1 })] public KeyValuePair this[int index] { [return: Nullable(new byte[] { 0, 1, 1 })] get { return list[index]; } [param: Nullable(new byte[] { 0, 1, 1 })] set { list[index] = value; } } public OrderedDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public OrderedDictionary(IEqualityComparer comparer) { list = new List>(); dictionary = new Dictionary(comparer); this.comparer = comparer; } public void Add(TKey key, TValue value) { Add(new KeyValuePair(key, value)); } public void Add([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { dictionary.Add(item.Key, item.Value); list.Add(item); } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo([Nullable(new byte[] { 1, 0, 1, 1 })] KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } [return: Nullable(new byte[] { 1, 0, 1, 1 })] public IEnumerator> GetEnumerator() { return list.GetEnumerator(); } public void Insert(int index, TKey key, TValue value) { dictionary.Add(key, value); list.Insert(index, new KeyValuePair(key, value)); } public bool Remove(TKey key) { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); list.RemoveAt(index); if (!dictionary.Remove(key)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove([Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return Remove(item.Key); } public void RemoveAt(int index) { TKey key = list[index].Key; dictionary.Remove(key); list.RemoveAt(index); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return dictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { dictionary = new Dictionary(); foreach (KeyValuePair item in list) { dictionary[item.Key] = item.Value; } } } [Nullable(0)] [NullableContext(1)] [DebuggerStepThrough] internal static class StringBuilderPool { [Nullable(0)] internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ConcurrentObjectPool _pool; public BuilderWrapper(StringBuilder builder, ConcurrentObjectPool pool) { Builder = builder; _pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { StringBuilder builder = Builder; if (builder.Capacity <= 1024) { builder.Length = 0; _pool.Free(builder); } } } private static readonly ConcurrentObjectPool Pool; static StringBuilderPool() { Pool = new ConcurrentObjectPool(() => new StringBuilder()); } public static BuilderWrapper Rent() { return new BuilderWrapper(Pool.Allocate(), Pool); } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] [NullableContext(1)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } internal static class Lazy { [NullableContext(1)] public static Lazy FromValue<[Nullable(2)] T>(T value) { Lazy lazy = new Lazy(() => value, isThreadSafe: false); _ = lazy.Value; return lazy; } } [NullableContext(1)] [Nullable(0)] internal static class ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList<[Nullable(2)] T>(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionaryNullable(2)] TValue>(this Dictionary dictionary) { return dictionary; } } } namespace YamlDotNet.Core { [NullableContext(1)] [Nullable(0)] internal struct AnchorName : IEquatable { public static readonly AnchorName Empty = default(AnchorName); private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); [Nullable(2)] private readonly string value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of an empty anchor"); public bool IsEmpty => value == null; public AnchorName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (!AnchorPattern.IsMatch(value)) { throw new ArgumentException("Anchor cannot be empty or contain disallowed characters: []{},\nThe value was '" + value + "'.", "value"); } } public override string ToString() { return value ?? "[empty]"; } public bool Equals(AnchorName other) { return object.Equals(value, other.value); } [NullableContext(2)] public override bool Equals(object obj) { if (obj is AnchorName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(AnchorName left, AnchorName right) { return left.Equals(right); } public static bool operator !=(AnchorName left, AnchorName right) { return !(left == right); } [NullableContext(2)] public static implicit operator AnchorName(string value) { if (value != null) { return new AnchorName(value); } return Empty; } } [NullableContext(1)] [Nullable(0)] internal class AnchorNotFoundException : YamlException { public AnchorNotFoundException(string message) : base(message) { } public AnchorNotFoundException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } [Nullable(0)] [DebuggerStepThrough] [NullableContext(1)] internal sealed class CharacterAnalyzer where TBuffer : class, ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { Buffer = buffer ?? throw new ArgumentNullException("buffer"); } public char Peek(int offset) { return Buffer.Peek(offset); } public void Skip(int length) { Buffer.Skip(length); } public bool IsAlphaNumericDashOrUnderscore(int offset = 0) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && c != '_') { return c == '-'; } return true; } public bool IsAscii(int offset = 0) { return Buffer.Peek(offset) <= '\u007f'; } public bool IsPrintable(int offset = 0) { char c = Buffer.Peek(offset); switch (c) { default: if (c != '\u0085' && (c < '\u00a0' || c > '\ud7ff')) { if (c >= '\ue000') { return c <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } public bool IsDigit(int offset = 0) { char c = Buffer.Peek(offset); if (c >= '0') { return c <= '9'; } return false; } public int AsDigit(int offset = 0) { return Buffer.Peek(offset) - 48; } public bool IsHex(int offset) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } public int AsHex(int offset) { char c = Buffer.Peek(offset); if (c <= '9') { return c - 48; } if (c <= 'F') { return c - 65 + 10; } return c - 97 + 10; } public bool IsSpace(int offset = 0) { return Check(' ', offset); } public bool IsZero(int offset = 0) { return Check('\0', offset); } public bool IsTab(int offset = 0) { return Check('\t', offset); } public bool IsWhite(int offset = 0) { if (!IsSpace(offset)) { return IsTab(offset); } return true; } public bool IsBreak(int offset = 0) { return Check("\r\n\u0085\u2028\u2029", offset); } public bool IsCrLf(int offset = 0) { if (Check('\r', offset)) { return Check('\n', offset + 1); } return false; } public bool IsBreakOrZero(int offset = 0) { if (!IsBreak(offset)) { return IsZero(offset); } return true; } public bool IsWhiteBreakOrZero(int offset = 0) { if (!IsWhite(offset)) { return IsBreakOrZero(offset); } return true; } public bool Check(char expected, int offset = 0) { return Buffer.Peek(offset) == expected; } public bool Check(string expectedCharacters, int offset = 0) { char value = Buffer.Peek(offset); return expectedCharacters.IndexOf(value) != -1; } } internal static class Constants { [Nullable(1)] public static readonly TagDirective[] DefaultTagDirectives = new TagDirective[2] { new TagDirective("!", "!"), new TagDirective("!!", "tag:yaml.org,2002:") }; public const int MajorVersion = 1; public const int MinorVersion = 3; } [DebuggerStepThrough] internal sealed class Cursor { public int Index { get; private set; } public int Line { get; private set; } public int LineOffset { get; private set; } public Cursor() { Line = 1; } [NullableContext(1)] public Cursor(Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public Mark Mark() { return new Mark(Index, Line, LineOffset + 1); } public void Skip() { Index++; LineOffset++; } public void SkipLineByOffset(int offset) { Index += offset; Line++; LineOffset = 0; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0) { Line++; LineOffset = 0; } } } [NullableContext(1)] [Nullable(0)] internal class Emitter : IEmitter { [NullableContext(0)] private class AnchorData { public AnchorName Anchor; public bool IsAlias; } [Nullable(0)] [NullableContext(2)] private class TagData { public string Handle; public string Suffix; } [NullableContext(0)] private class ScalarData { [Nullable(1)] public string Value = string.Empty; public bool IsMultiline; public bool IsFlowPlainAllowed; public bool IsBlockPlainAllowed; public bool IsSingleQuotedAllowed; public bool IsBlockAllowed; public bool HasSingleQuotes; public ScalarStyle Style; } private static readonly Regex UriReplacer = new Regex("[^0-9A-Za-z_\\-;?@=$~\\\\\\)\\]/:&+,\\.\\*\\(\\[!]", RegexOptions.Compiled | RegexOptions.Singleline); private static readonly string[] newLineSeparators = new string[3] { "\r\n", "\r", "\n" }; private readonly TextWriter output; private readonly bool outputUsesUnicodeEncoding; private readonly int maxSimpleKeyLength; private readonly bool isCanonical; private readonly bool skipAnchorName; private readonly int bestIndent; private readonly int bestWidth; private EmitterState state; private readonly Stack states = new Stack(); private readonly Queue events = new Queue(); private readonly Stack indents = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private int indent; private int flowLevel; private bool isMappingContext; private bool isSimpleKeyContext; private int column; private bool isWhitespace; private bool isIndentation; private readonly bool forceIndentLess; private readonly string newLine; private bool isDocumentEndWritten; private readonly AnchorData anchorData = new AnchorData(); private readonly TagData tagData = new TagData(); private readonly ScalarData scalarData = new ScalarData(); public Emitter(TextWriter output) : this(output, EmitterSettings.Default) { } public Emitter(TextWriter output, int bestIndent) : this(output, bestIndent, int.MaxValue) { } public Emitter(TextWriter output, int bestIndent, int bestWidth) : this(output, bestIndent, bestWidth, isCanonical: false) { } public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : this(output, new EmitterSettings(bestIndent, bestWidth, isCanonical, 1024)) { } public Emitter(TextWriter output, EmitterSettings settings) { bestIndent = settings.BestIndent; bestWidth = settings.BestWidth; isCanonical = settings.IsCanonical; maxSimpleKeyLength = settings.MaxSimpleKeyLength; skipAnchorName = settings.SkipAnchorName; forceIndentLess = !settings.IndentSequences; newLine = settings.NewLine; this.output = output; outputUsesUnicodeEncoding = IsUnicode(output.Encoding); } public void Emit(ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { ParsingEvent evt = events.Peek(); try { AnalyzeEvent(evt); StateMachine(evt); } finally { events.Dequeue(); } } } private bool NeedMoreEvents() { if (events.Count == 0) { return true; } int num; switch (events.Peek().Type) { case EventType.DocumentStart: num = 1; break; case EventType.SequenceStart: num = 2; break; case EventType.MappingStart: num = 3; break; default: return false; } if (events.Count > num) { return false; } int num2 = 0; using (Queue.Enumerator enumerator = events.GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current.Type) { case EventType.DocumentStart: case EventType.SequenceStart: case EventType.MappingStart: num2++; break; case EventType.DocumentEnd: case EventType.SequenceEnd: case EventType.MappingEnd: num2--; break; } if (num2 == 0) { return false; } } } return true; } private void AnalyzeEvent(ParsingEvent evt) { anchorData.Anchor = AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { AnalyzeAnchor(anchorAlias.Value, isAlias: true); } else if (evt is NodeEvent nodeEvent) { if (evt is YamlDotNet.Core.Events.Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(nodeEvent.Anchor, isAlias: false); if (!nodeEvent.Tag.IsEmpty && (isCanonical || nodeEvent.IsCanonical)) { AnalyzeTag(nodeEvent.Tag); } } } private void AnalyzeAnchor(AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(YamlDotNet.Core.Events.Scalar scalar) { string value = scalar.Value; scalarData.Value = value; if (value.Length == 0) { if (scalar.Tag == "tag:yaml.org,2002:null") { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = false; scalarData.IsBlockAllowed = false; } else { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = false; } return; } bool flag = false; bool flag2 = false; if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) { flag = true; flag2 = true; } CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); bool flag3 = true; bool flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; bool flag10 = false; bool flag11 = false; bool flag12 = false; bool flag13 = false; bool flag14 = false; bool flag15 = false; bool flag16 = !ValueIsRepresentableInOutputEncoding(value); bool flag17 = false; bool flag18 = false; bool flag19 = true; while (!characterAnalyzer.EndOfInput) { if (flag19) { if (characterAnalyzer.Check("#,[]{}&*!|>\\\"%@`'")) { flag = true; flag2 = true; flag9 = characterAnalyzer.Check('\''); flag17 |= characterAnalyzer.Check('\''); } if (characterAnalyzer.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (characterAnalyzer.Check(",?[]{}")) { flag = true; } if (characterAnalyzer.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= characterAnalyzer.Check('\''); } if (!flag16 && !characterAnalyzer.IsPrintable()) { flag16 = true; } if (characterAnalyzer.IsBreak()) { flag15 = true; } if (characterAnalyzer.IsSpace()) { if (flag19) { flag5 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (characterAnalyzer.IsBreak()) { if (flag19) { flag6 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag8 = true; } if (flag12) { flag11 = true; } if (flag14) { flag18 = true; } flag12 = false; flag13 = true; } else { flag12 = false; flag13 = false; flag14 = false; } flag3 = characterAnalyzer.IsWhiteBreakOrZero(); characterAnalyzer.Skip(1); if (!characterAnalyzer.EndOfInput) { flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); } flag19 = false; } scalarData.IsFlowPlainAllowed = true; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = true; if (flag5 || flag6 || flag7 || flag8 || flag9) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag7) { scalarData.IsBlockAllowed = false; } if (flag10) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag11 || flag16) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag18) { scalarData.IsBlockAllowed = false; } scalarData.IsMultiline = flag15; if (flag15) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag) { scalarData.IsFlowPlainAllowed = false; } if (flag2) { scalarData.IsBlockPlainAllowed = false; } scalarData.HasSingleQuotes = flag17; } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); return output.Encoding.GetString(bytes, 0, bytes.Length).Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private bool IsUnicode(Encoding encoding) { if (!(encoding is UTF8Encoding) && !(encoding is UnicodeEncoding)) { return encoding is UTF7Encoding; } return true; } private void AnalyzeTag(TagName tag) { tagData.Handle = tag.Value; foreach (TagDirective tagDirective in tagDirectives) { if (tag.Value.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) { tagData.Handle = tagDirective.Handle; tagData.Suffix = tag.Value.Substring(tagDirective.Prefix.Length); break; } } } private void StateMachine(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.Comment comment) { EmitComment(comment); return; } switch (state) { case EmitterState.StreamStart: EmitStreamStart(evt); break; case EmitterState.FirstDocumentStart: EmitDocumentStart(evt, isFirst: true); break; case EmitterState.DocumentStart: EmitDocumentStart(evt, isFirst: false); break; case EmitterState.DocumentContent: EmitDocumentContent(evt); break; case EmitterState.DocumentEnd: EmitDocumentEnd(evt); break; case EmitterState.FlowSequenceFirstItem: EmitFlowSequenceItem(evt, isFirst: true); break; case EmitterState.FlowSequenceItem: EmitFlowSequenceItem(evt, isFirst: false); break; case EmitterState.FlowMappingFirstKey: EmitFlowMappingKey(evt, isFirst: true); break; case EmitterState.FlowMappingKey: EmitFlowMappingKey(evt, isFirst: false); break; case EmitterState.FlowMappingSimpleValue: EmitFlowMappingValue(evt, isSimple: true); break; case EmitterState.FlowMappingValue: EmitFlowMappingValue(evt, isSimple: false); break; case EmitterState.BlockSequenceFirstItem: EmitBlockSequenceItem(evt, isFirst: true); break; case EmitterState.BlockSequenceItem: EmitBlockSequenceItem(evt, isFirst: false); break; case EmitterState.BlockMappingFirstKey: EmitBlockMappingKey(evt, isFirst: true); break; case EmitterState.BlockMappingKey: EmitBlockMappingKey(evt, isFirst: false); break; case EmitterState.BlockMappingSimpleValue: EmitBlockMappingValue(evt, isSimple: true); break; case EmitterState.BlockMappingValue: EmitBlockMappingValue(evt, isSimple: false); break; case EmitterState.StreamEnd: throw new YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(YamlDotNet.Core.Events.Comment comment) { if (flowLevel > 0 || state == EmitterState.FlowMappingFirstKey || state == EmitterState.FlowSequenceFirstItem) { return; } string[] array = comment.Value.Split(newLineSeparators, StringSplitOptions.None); if (comment.IsInline) { Write(" # "); Write(string.Join(" ", array)); } else { bool flag = state == EmitterState.BlockMappingFirstKey; if (flag) { IncreaseIndent(isFlow: false, isIndentless: false); } string[] array2 = array; foreach (string value in array2) { WriteIndent(); Write("# "); Write(value); WriteBreak(); } if (flag) { indent = indents.Pop(); } } isIndentation = true; } private void EmitStreamStart(ParsingEvent evt) { if (!(evt is YamlDotNet.Core.Events.StreamStart)) { throw new ArgumentException("Expected STREAM-START.", "evt"); } indent = -1; column = 0; isWhitespace = true; isIndentation = true; state = EmitterState.FirstDocumentStart; } private void EmitDocumentStart(ParsingEvent evt, bool isFirst) { if (evt is YamlDotNet.Core.Events.DocumentStart documentStart) { bool flag = documentStart.IsImplicit && isFirst && !isCanonical; TagDirectiveCollection tagDirectiveCollection = NonDefaultTagsAmong(documentStart.Tags); if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || tagDirectiveCollection.Count > 0)) { isDocumentEndWritten = false; WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } if (documentStart.Version != null) { AnalyzeVersionDirective(documentStart.Version); Version version = documentStart.Version.Version; flag = false; WriteIndicator("%YAML", needWhitespace: true, whitespace: false, indentation: false); WriteIndicator(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor), needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } foreach (TagDirective item in tagDirectiveCollection) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectiveCollection); } foreach (TagDirective item2 in tagDirectiveCollection) { WriteIndicator("%TAG", needWhitespace: true, whitespace: false, indentation: false); WriteTagHandle(item2.Handle); WriteTagContent(item2.Prefix, needsWhitespace: true); WriteIndent(); } } if (CheckEmptyDocument()) { flag = false; } if (!flag) { WriteIndent(); WriteIndicator("---", needWhitespace: true, whitespace: false, indentation: false); if (isCanonical) { WriteIndent(); } } state = EmitterState.DocumentContent; } else { if (!(evt is YamlDotNet.Core.Events.StreamEnd)) { throw new YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private TagDirectiveCollection NonDefaultTagsAmong([Nullable(new byte[] { 2, 1 })] IEnumerable tagCollection) { TagDirectiveCollection tagDirectiveCollection = new TagDirectiveCollection(); if (tagCollection == null) { return tagDirectiveCollection; } foreach (TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, tagDirectiveCollection); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective item in defaultTagDirectives) { tagDirectiveCollection.Remove(item); } return tagDirectiveCollection; } private void AnalyzeVersionDirective(VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(ParsingEvent evt, bool isMapping, bool isSimpleKey) { isMappingContext = isMapping; isSimpleKeyContext = isSimpleKey; switch (evt.Type) { case EventType.Alias: EmitAlias(); break; case EventType.Scalar: EmitScalar(evt); break; case EventType.SequenceStart: EmitSequenceStart(evt); break; case EventType.MappingStart: EmitMappingStart(evt); break; default: throw new YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(ParsingEvent evt) { YamlDotNet.Core.Events.Scalar scalar = (YamlDotNet.Core.Events.Scalar)evt; ScalarStyle scalarStyle = scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) { throw new YamlException("Neither tag nor isImplicit flags are specified."); } if (scalarStyle == ScalarStyle.Any) { scalarStyle = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { scalarStyle = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { scalarStyle = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.SingleQuoted; } if (flag && !scalar.IsPlainImplicit) { scalarStyle = ScalarStyle.SingleQuoted; } } if (scalarStyle == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { scalarStyle = ScalarStyle.DoubleQuoted; } if ((scalarStyle == ScalarStyle.Literal || scalarStyle == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.DoubleQuoted; } scalarData.Style = scalarStyle; } private void ProcessScalar() { switch (scalarData.Style) { case ScalarStyle.Plain: WritePlainScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.SingleQuoted: WriteSingleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.DoubleQuoted: WriteDoubleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.Literal: WriteLiteralScalar(scalarData.Value); break; case ScalarStyle.Folded: WriteFoldedScalar(scalarData.Value); break; default: throw new InvalidOperationException(); } } private void WritePlainScalar(string value, bool allowBreaks) { if (!isWhitespace) { Write(' '); } bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsSpace(c)) { if (allowBreaks && !flag && column > bestWidth && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } Write(c); isIndentation = false; flag = false; flag2 = false; } isWhitespace = false; isIndentation = false; } private void WriteSingleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("'", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == ' ') { if (allowBreaks && !flag && column > bestWidth && i != 0 && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } if (c == '\'') { Write(c); } Write(c); isIndentation = false; flag = false; flag2 = false; } WriteIndicator("'", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteDoubleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("\"", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsPrintable(c) && !IsBreak(c, out var _)) { switch (c) { case '"': case '\\': break; case ' ': if (allowBreaks && !flag && column > bestWidth && i > 0 && i + 1 < value.Length) { WriteIndent(); if (value[i + 1] == ' ') { Write('\\'); } } else { Write(c); } flag = true; continue; default: Write(c); flag = false; continue; } } Write('\\'); switch (c) { case '\0': Write('0'); break; case '\a': Write('a'); break; case '\b': Write('b'); break; case '\t': Write('t'); break; case '\n': Write('n'); break; case '\v': Write('v'); break; case '\f': Write('f'); break; case '\r': Write('r'); break; case '\u001b': Write('e'); break; case '"': Write('"'); break; case '\\': Write('\\'); break; case '\u0085': Write('N'); break; case '\u00a0': Write('_'); break; case '\u2028': Write('L'); break; case '\u2029': Write('P'); break; default: { ushort num = c; if (num <= 255) { Write('x'); Write(num.ToString("X02", CultureInfo.InvariantCulture)); } else if (IsHighSurrogate(c)) { if (i + 1 >= value.Length || !IsLowSurrogate(value[i + 1])) { throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); } Write('U'); Write(char.ConvertToUtf32(c, value[i + 1]).ToString("X08", CultureInfo.InvariantCulture)); i++; } else { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); } break; } } flag = false; } WriteIndicator("\"", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteLiteralScalar(string value) { bool flag = true; WriteIndicator("|", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (IsBreak(c, out var breakChar)) { WriteBreak(breakChar); isIndentation = true; flag = true; continue; } if (flag) { WriteIndent(); } Write(c); isIndentation = false; flag = false; } } private void WriteFoldedScalar(string value) { bool flag = true; bool flag2 = true; WriteIndicator(">", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsBreak(c, out var breakChar)) { if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (!flag && !flag2 && breakChar == '\n') { int j; char breakChar2; for (j = 0; i + j < value.Length && IsBreak(value[i + j], out breakChar2); j++) { } if (i + j < value.Length && !IsBlank(value[i + j]) && !IsBreak(value[i + j], out breakChar2)) { WriteBreak(); } } WriteBreak(breakChar); isIndentation = true; flag = true; } else { if (flag) { WriteIndent(); flag2 = IsBlank(c); } if (!flag && c == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) { WriteIndent(); } else { Write(c); } isIndentation = false; flag = false; } } } private static bool IsSpace(char character) { return character == ' '; } private static bool IsBreak(char character, out char breakChar) { switch (character) { case '\n': case '\r': case '\u0085': breakChar = '\n'; return true; case '\u2028': case '\u2029': breakChar = character; return true; default: breakChar = '\0'; return false; } } private static bool IsBlank(char character) { if (character != ' ') { return character == '\t'; } return true; } private static bool IsPrintable(char character) { switch (character) { default: if (character != '\u0085' && (character < '\u00a0' || character > '\ud7ff')) { if (character >= '\ue000') { return character <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } private static bool IsHighSurrogate(char c) { if ('\ud800' <= c) { return c <= '\udbff'; } return false; } private static bool IsLowSurrogate(char c) { if ('\udc00' <= c) { return c <= '\udfff'; } return false; } private void EmitSequenceStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) { state = EmitterState.FlowMappingFirstKey; } else { state = EmitterState.BlockMappingFirstKey; } } private void ProcessAnchor() { if (!anchorData.Anchor.IsEmpty && !skipAnchorName) { WriteIndicator(anchorData.IsAlias ? "*" : "&", needWhitespace: true, whitespace: false, indentation: false); WriteAnchor(anchorData.Anchor); } } private void ProcessTag() { if (tagData.Handle == null && tagData.Suffix == null) { return; } if (tagData.Handle != null) { WriteTagHandle(tagData.Handle); if (tagData.Suffix != null) { WriteTagContent(tagData.Suffix, needsWhitespace: false); } } else { WriteIndicator("!<", needWhitespace: true, whitespace: false, indentation: false); WriteTagContent(tagData.Suffix, needsWhitespace: false); WriteIndicator(">", needWhitespace: false, whitespace: false, indentation: false); } } private void EmitDocumentEnd(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.DocumentEnd documentEnd) { WriteIndent(); if (!documentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is SequenceEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("]", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); } else { if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } states.Push(EmitterState.FlowSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } } private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is MappingEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("}", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); return; } if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } if (!isCanonical && CheckSimpleKey()) { states.Push(EmitterState.FlowMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: false); states.Push(EmitterState.FlowMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { if (isCanonical || column > bestWidth) { WriteIndent(); } WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: false); } states.Push(EmitterState.FlowMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is SequenceEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); WriteIndicator("-", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is MappingEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); if (CheckSimpleKey()) { states.Push(EmitterState.BlockMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { WriteIndent(); WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: true); } states.Push(EmitterState.BlockMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void IncreaseIndent(bool isFlow, bool isIndentless) { indents.Push(indent); if (indent < 0) { indent = (isFlow ? bestIndent : 0); } else if (!isIndentless || !forceIndentLess) { indent += bestIndent; } } private bool CheckEmptyDocument() { int num = 0; foreach (ParsingEvent @event in events) { num++; if (num == 2) { if (@event is YamlDotNet.Core.Events.Scalar scalar) { return string.IsNullOrEmpty(scalar.Value); } break; } } return false; } private bool CheckSimpleKey() { if (events.Count < 1) { return false; } int num; switch (events.Peek().Type) { case EventType.Alias: num = AnchorNameLength(anchorData.Anchor); break; case EventType.Scalar: if (scalarData.IsMultiline) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix) + SafeStringLength(scalarData.Value); break; case EventType.SequenceStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; case EventType.MappingStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; default: return false; } return num <= maxSimpleKeyLength; } private int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } [NullableContext(2)] private int SafeStringLength(string value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } [NullableContext(0)] private bool CheckEmptyStructure() where TStart : NodeEvent where TEnd : ParsingEvent { if (events.Count < 2) { return false; } using Queue.Enumerator enumerator = events.GetEnumerator(); return enumerator.MoveNext() && enumerator.Current is TStart && enumerator.MoveNext() && enumerator.Current is TEnd; } private void WriteBlockScalarHints(string value) { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); if (characterAnalyzer.IsSpace() || characterAnalyzer.IsBreak()) { int num = bestIndent; string indicator = num.ToString(CultureInfo.InvariantCulture); WriteIndicator(indicator, needWhitespace: false, whitespace: false, indentation: false); } string text = null; if (value.Length == 0 || !characterAnalyzer.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && characterAnalyzer.IsBreak(value.Length - 2)) { text = "+"; } if (text != null) { WriteIndicator(text, needWhitespace: false, whitespace: false, indentation: false); } } private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) { if (needWhitespace && !isWhitespace) { Write(' '); } Write(indicator); isWhitespace = whitespace; isIndentation &= indentation; } private void WriteIndent() { int num = Math.Max(indent, 0); if (!isIndentation || column > num || (column == num && !isWhitespace)) { WriteBreak(); } while (column < num) { Write(' '); } isWhitespace = true; isIndentation = true; } private void WriteAnchor(AnchorName value) { Write(value.Value); isWhitespace = false; isIndentation = false; } private void WriteTagHandle(string value) { if (!isWhitespace) { Write(' '); } Write(value); isWhitespace = false; isIndentation = false; } private void WriteTagContent(string value, bool needsWhitespace) { if (needsWhitespace && !isWhitespace) { Write(' '); } Write(UrlEncode(value)); isWhitespace = false; isIndentation = false; } private static string UrlEncode(string text) { return UriReplacer.Replace(text, [NullableContext(0)] ([Nullable(1)] Match match) => { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { builder.AppendFormat("%{0:X02}", b); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } }); } private void Write(char value) { output.Write(value); column++; } private void Write(string value) { output.Write(value); column += value.Length; } private void WriteBreak(char breakCharacter = '\n') { if (breakCharacter == '\n') { output.Write(newLine); } else { output.Write(breakCharacter); } column = 0; } } [NullableContext(1)] [Nullable(0)] internal sealed class EmitterSettings { public static readonly EmitterSettings Default = new EmitterSettings(); public int BestIndent { get; } = 2; public int BestWidth { get; } = int.MaxValue; public string NewLine { get; } = Environment.NewLine; public bool IsCanonical { get; } public bool SkipAnchorName { get; private set; } public int MaxSimpleKeyLength { get; } = 1024; public bool IndentSequences { get; } public EmitterSettings() { } [NullableContext(2)] public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = false, string newLine = null) { if (bestIndent < 2 || bestIndent > 9) { throw new ArgumentOutOfRangeException("bestIndent", "BestIndent must be between 2 and 9, inclusive"); } if (bestWidth <= bestIndent * 2) { throw new ArgumentOutOfRangeException("bestWidth", "BestWidth must be greater than BestIndent x 2."); } if (maxSimpleKeyLength < 0) { throw new ArgumentOutOfRangeException("maxSimpleKeyLength", "MaxSimpleKeyLength must be >= 0"); } BestIndent = bestIndent; BestWidth = bestWidth; IsCanonical = isCanonical; MaxSimpleKeyLength = maxSimpleKeyLength; SkipAnchorName = skipAnchorName; IndentSequences = indentSequences; NewLine = newLine ?? Environment.NewLine; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithNewLine(string newLine) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine); } public EmitterSettings Canonical() { return new EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithoutAnchorName() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true, IndentSequences, NewLine); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine); } } internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } [NullableContext(1)] [Nullable(0)] internal sealed class ForwardAnchorNotSupportedException : YamlException { public ForwardAnchorNotSupportedException(string message) : base(message) { } public ForwardAnchorNotSupportedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public ForwardAnchorNotSupportedException(string message, Exception inner) : base(message, inner) { } } [NullableContext(2)] [Nullable(0)] internal static class HashCode { public static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } public static int CombineHashCodes(int h1, object o2) { return CombineHashCodes(h1, GetHashCode(o2)); } private static int GetHashCode(object obj) { return obj?.GetHashCode() ?? 0; } } [NullableContext(1)] internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } [Nullable(0)] [NullableContext(1)] internal sealed class InsertionQueue<[Nullable(2)] T> : IEnumerable, IEnumerable { private const int DefaultInitialCapacity = 128; private T[] items; private int readPtr; private int writePtr; private int mask; private int count; public int Count => count; public int Capacity => items.Length; public InsertionQueue(int initialCapacity = 128) { if (initialCapacity <= 0) { throw new ArgumentOutOfRangeException("initialCapacity", "The initial capacity must be a positive number."); } if (!initialCapacity.IsPowerOfTwo()) { throw new ArgumentException("The initial capacity must be a power of 2.", "initialCapacity"); } items = new T[initialCapacity]; readPtr = initialCapacity / 2; writePtr = initialCapacity / 2; mask = initialCapacity - 1; } public void Enqueue(T item) { ResizeIfNeeded(); items[writePtr] = item; writePtr = (writePtr - 1) & mask; count++; } public T Dequeue() { if (count == 0) { throw new InvalidOperationException("The queue is empty"); } T result = items[readPtr]; readPtr = (readPtr - 1) & mask; count--; return result; } public void Insert(int index, T item) { if (index > count) { throw new InvalidOperationException("Cannot insert outside of the bounds of the queue"); } ResizeIfNeeded(); CalculateInsertionParameters(mask, count, index, ref readPtr, ref writePtr, out var insertPtr, out var copyIndex, out var copyOffset, out var copyLength); if (copyLength != 0) { Array.Copy(items, copyIndex, items, copyIndex + copyOffset, copyLength); } items[insertPtr] = item; count++; } private void ResizeIfNeeded() { int num = items.Length; if (count == num) { T[] destinationArray = new T[num * 2]; int num2 = readPtr + 1; if (num2 > 0) { Array.Copy(items, 0, destinationArray, 0, num2); } writePtr += num; int num3 = num - num2; if (num3 > 0) { Array.Copy(items, readPtr + 1, destinationArray, writePtr + 1, num3); } items = destinationArray; mask = mask * 2 + 1; } } internal static void CalculateInsertionParameters(int mask, int count, int index, ref int readPtr, ref int writePtr, out int insertPtr, out int copyIndex, out int copyOffset, out int copyLength) { int num = (readPtr + 1) & mask; if (index == 0) { insertPtr = (readPtr = num); copyIndex = 0; copyOffset = 0; copyLength = 0; return; } insertPtr = (readPtr - index) & mask; if (index == count) { writePtr = (writePtr - 1) & mask; copyIndex = 0; copyOffset = 0; copyLength = 0; return; } int num2 = ((num >= insertPtr) ? (readPtr - insertPtr) : int.MaxValue); int num3 = ((writePtr <= insertPtr) ? (insertPtr - writePtr) : int.MaxValue); if (num2 <= num3) { insertPtr++; readPtr++; copyIndex = insertPtr; copyOffset = 1; copyLength = num2; } else { copyIndex = writePtr + 1; copyOffset = -1; copyLength = num3; writePtr = (writePtr - 1) & mask; } } public IEnumerator GetEnumerator() { int ptr = readPtr; for (int i = 0; i < Count; i++) { yield return items[ptr]; ptr = (ptr - 1) & mask; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NullableContext(2)] internal interface IParser { ParsingEvent Current { get; } bool MoveNext(); } [NullableContext(2)] internal interface IScanner { Mark CurrentPosition { get; } Token Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [NullableContext(1)] [DebuggerStepThrough] [Nullable(0)] internal sealed class LookAheadBuffer : ILookAheadBuffer { private readonly TextReader input; private readonly char[] buffer; private readonly int blockSize; private readonly int mask; private int firstIndex; private int writeOffset; private int count; private bool endOfInput; public bool EndOfInput { get { if (endOfInput) { return count == 0; } return false; } } public LookAheadBuffer(TextReader input, int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); } if (!capacity.IsPowerOfTwo()) { throw new ArgumentException("The capacity must be a power of 2.", "capacity"); } this.input = input ?? throw new ArgumentNullException("input"); blockSize = capacity; buffer = new char[capacity * 2]; mask = capacity * 2 - 1; } private int GetIndexForOffset(int offset) { return (firstIndex + offset) & mask; } public char Peek(int offset) { if (offset >= count) { FillBuffer(); } if (offset < count) { return buffer[(firstIndex + offset) & mask]; } return '\0'; } public void Cache(int length) { if (length >= count) { FillBuffer(); } } private void FillBuffer() { if (endOfInput) { return; } int num = blockSize; do { int num2 = input.Read(buffer, writeOffset, num); if (num2 == 0) { endOfInput = true; return; } num -= num2; writeOffset += num2; count += num2; } while (num > 0); if (writeOffset == buffer.Length) { writeOffset = 0; } } public void Skip(int length) { if (length < 1 || length > blockSize) { throw new ArgumentOutOfRangeException("length", "The length must be between 1 and the number of characters in the buffer. Use the Peek() and / or Cache() methods to fill the buffer."); } firstIndex = GetIndexForOffset(length); count -= length; } } internal readonly struct Mark : IEquatable, IComparable, IComparable { public static readonly Mark Empty = new Mark(0, 1, 1); public int Index { get; } public int Line { get; } public int Column { get; } public Mark(int index, int line, int column) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); } if (line < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); } if (column < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("column", "Column must be greater than or equal to 1."); } Index = index; Line = line; Column = column; } [NullableContext(1)] public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } [NullableContext(2)] public override bool Equals(object obj) { return Equals((Mark)(obj ?? ((object)Empty))); } public bool Equals(Mark other) { if (Index == other.Index && Line == other.Line) { return Column == other.Column; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Index.GetHashCode(), HashCode.CombineHashCodes(Line.GetHashCode(), Column.GetHashCode())); } [NullableContext(2)] public int CompareTo(object obj) { return CompareTo((Mark)(obj ?? ((object)Empty))); } public int CompareTo(Mark other) { int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } } [NullableContext(1)] [Nullable(0)] internal sealed class MaximumRecursionLevelReachedException : YamlException { public MaximumRecursionLevelReachedException(string message) : base(message) { } public MaximumRecursionLevelReachedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public MaximumRecursionLevelReachedException(string message, Exception inner) : base(message, inner) { } } [NullableContext(1)] [Nullable(0)] internal sealed class MergingParser : IParser { [Nullable(0)] private sealed class ParsingEventCollection : IEnumerable>, IEnumerable { private readonly LinkedList events; private readonly HashSet> deleted; private readonly Dictionary> references; public ParsingEventCollection() { events = new LinkedList(); deleted = new HashSet>(); references = new Dictionary>(); } public void AddAfter(LinkedListNode node, IEnumerable items) { foreach (ParsingEvent item in items) { node = events.AddAfter(node, item); } } public void Add(ParsingEvent item) { LinkedListNode node = events.AddLast(item); AddReference(item, node); } public void MarkDeleted(LinkedListNode node) { deleted.Add(node); } public void CleanMarked() { foreach (LinkedListNode item in deleted) { events.Remove(item); } } public IEnumerable> FromAnchor(AnchorName anchor) { LinkedListNode next = references[anchor].Next; return Enumerate(next); } public IEnumerator> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerable> Enumerate([Nullable(new byte[] { 2, 1 })] LinkedListNode node) { while (node != null) { yield return node; node = node.Next; } } private void AddReference(ParsingEvent item, LinkedListNode node) { if (item is MappingStart { Anchor: { IsEmpty: false } anchor }) { references[anchor] = node; } } } [Nullable(0)] private sealed class ParsingEventCloner : IParsingEventVisitor { [Nullable(2)] private ParsingEvent clonedEvent; public ParsingEvent Clone(ParsingEvent e) { e.Accept(this); if (clonedEvent == null) { throw new InvalidOperationException($"Could not clone event of type '{e.Type}'"); } return clonedEvent; } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.AnchorAlias e) { clonedEvent = new YamlDotNet.Core.Events.AnchorAlias(e.Value, e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Scalar e) { clonedEvent = new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceStart e) { clonedEvent = new SequenceStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceEnd e) { clonedEvent = new SequenceEnd(e.Start, e.End); } void IParsingEventVisitor.Visit(MappingStart e) { clonedEvent = new MappingStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(MappingEnd e) { clonedEvent = new MappingEnd(e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Comment e) { throw new NotSupportedException(); } } private readonly ParsingEventCollection events; private readonly IParser innerParser; private IEnumerator> iterator; private bool merged; [Nullable(2)] public ParsingEvent Current { [NullableContext(2)] get { return iterator.Current?.Value; } } public MergingParser(IParser innerParser) { events = new ParsingEventCollection(); merged = false; iterator = events.GetEnumerator(); this.innerParser = innerParser; } public bool MoveNext() { if (!merged) { Merge(); events.CleanMarked(); iterator = events.GetEnumerator(); merged = true; } return iterator.MoveNext(); } private void Merge() { while (innerParser.MoveNext()) { events.Add(innerParser.Current); } foreach (LinkedListNode @event in events) { if (IsMergeToken(@event)) { events.MarkDeleted(@event); if (!HandleMerge(@event.Next)) { throw new SemanticErrorException(@event.Value.Start, @event.Value.End, "Unrecognized merge key pattern"); } } } } private bool HandleMerge([Nullable(new byte[] { 2, 1 })] LinkedListNode node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(node, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool HandleMergeSequence(LinkedListNode sequenceStart, [Nullable(new byte[] { 2, 1 })] LinkedListNode node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(sequenceStart, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool IsMergeToken(LinkedListNode node) { if (node.Value is YamlDotNet.Core.Events.Scalar scalar) { return scalar.Value == "<<"; } return false; } private bool HandleAnchorAlias(LinkedListNode node, LinkedListNode anchorNode, YamlDotNet.Core.Events.AnchorAlias anchorAlias) { IEnumerable mappingEvents = GetMappingEvents(anchorAlias.Value); events.AddAfter(node, mappingEvents); events.MarkDeleted(anchorNode); return true; } private bool HandleSequence(LinkedListNode node) { events.MarkDeleted(node); LinkedListNode linkedListNode = node; while (linkedListNode != null) { if (linkedListNode.Value is SequenceEnd && linkedListNode.Value.Start.Line >= node.Value.Start.Line) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable GetMappingEvents(AnchorName anchor) { ParsingEventCloner cloner = new ParsingEventCloner(); int nesting = 0; return from e in (from e in events.FromAnchor(anchor) select e.Value).TakeWhile([NullableContext(0)] (ParsingEvent e) => (nesting += e.NestingIncrease) >= 0) select cloner.Clone(e); } } [Nullable(0)] [NullableContext(1)] internal class Parser : IParser { [Nullable(0)] private class EventQueue { private readonly Queue highPriorityEvents = new Queue(); private readonly Queue normalPriorityEvents = new Queue(); public int Count => highPriorityEvents.Count + normalPriorityEvents.Count; public void Enqueue(ParsingEvent @event) { EventType type = @event.Type; if (type == EventType.StreamStart || type == EventType.DocumentStart) { highPriorityEvents.Enqueue(@event); } else { normalPriorityEvents.Enqueue(@event); } } public ParsingEvent Dequeue() { if (highPriorityEvents.Count <= 0) { return normalPriorityEvents.Dequeue(); } return highPriorityEvents.Dequeue(); } } private readonly Stack states = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly IScanner scanner; [Nullable(2)] private Token currentToken; [Nullable(2)] private VersionDirective version; private readonly EventQueue pendingEvents = new EventQueue(); [Nullable(2)] [field: Nullable(2)] public ParsingEvent Current { [NullableContext(2)] get; [NullableContext(2)] private set; } [NullableContext(2)] private Token GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (!(currentToken is YamlDotNet.Core.Tokens.Comment comment)) { break; } pendingEvents.Enqueue(new YamlDotNet.Core.Events.Comment(comment.Value, comment.IsInline, comment.Start, comment.End)); scanner.ConsumeCurrent(); } } return currentToken; } public Parser(TextReader input) : this(new Scanner(input)) { } public Parser(IScanner scanner) { this.scanner = scanner; } public bool MoveNext() { if (state == ParserState.StreamEnd) { Current = null; return false; } if (pendingEvents.Count == 0) { pendingEvents.Enqueue(StateMachine()); } Current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { return state switch { ParserState.StreamStart => ParseStreamStart(), ParserState.ImplicitDocumentStart => ParseDocumentStart(isImplicit: true), ParserState.DocumentStart => ParseDocumentStart(isImplicit: false), ParserState.DocumentContent => ParseDocumentContent(), ParserState.DocumentEnd => ParseDocumentEnd(), ParserState.BlockNode => ParseNode(isBlock: true, isIndentlessSequence: false), ParserState.BlockNodeOrIndentlessSequence => ParseNode(isBlock: true, isIndentlessSequence: true), ParserState.FlowNode => ParseNode(isBlock: false, isIndentlessSequence: false), ParserState.BlockSequenceFirstEntry => ParseBlockSequenceEntry(isFirst: true), ParserState.BlockSequenceEntry => ParseBlockSequenceEntry(isFirst: false), ParserState.IndentlessSequenceEntry => ParseIndentlessSequenceEntry(), ParserState.BlockMappingFirstKey => ParseBlockMappingKey(isFirst: true), ParserState.BlockMappingKey => ParseBlockMappingKey(isFirst: false), ParserState.BlockMappingValue => ParseBlockMappingValue(), ParserState.FlowSequenceFirstEntry => ParseFlowSequenceEntry(isFirst: true), ParserState.FlowSequenceEntry => ParseFlowSequenceEntry(isFirst: false), ParserState.FlowSequenceEntryMappingKey => ParseFlowSequenceEntryMappingKey(), ParserState.FlowSequenceEntryMappingValue => ParseFlowSequenceEntryMappingValue(), ParserState.FlowSequenceEntryMappingEnd => ParseFlowSequenceEntryMappingEnd(), ParserState.FlowMappingFirstKey => ParseFlowMappingKey(isFirst: true), ParserState.FlowMappingKey => ParseFlowMappingKey(isFirst: false), ParserState.FlowMappingValue => ParseFlowMappingValue(isEmpty: false), ParserState.FlowMappingEmptyValue => ParseFlowMappingValue(isEmpty: true), _ => throw new InvalidOperationException(), }; } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } private ParsingEvent ParseStreamStart() { Token token = GetCurrentToken(); if (!(token is YamlDotNet.Core.Tokens.StreamStart streamStart)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "Did not find expected ."); } Skip(); state = ParserState.ImplicitDocumentStart; return new YamlDotNet.Core.Events.StreamStart(streamStart.Start, streamStart.End); } private ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is VersionDirective) { throw new SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token token = GetCurrentToken(); if (!isImplicit) { while (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); token = GetCurrentToken(); } } if (token == null) { throw new SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (token is YamlDotNet.Core.Tokens.Scalar && (state == ParserState.ImplicitDocumentStart || state == ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(token is VersionDirective) && !(token is TagDirective) && !(token is YamlDotNet.Core.Tokens.DocumentStart) && !(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) || token is BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new YamlDotNet.Core.Events.DocumentStart(null, tags, isImplicit: true, token.Start, token.End); } if (!(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark start = token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); VersionDirective versionDirective = ProcessDirectives(tags2); token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(token is YamlDotNet.Core.Tokens.DocumentStart)) { throw new SemanticErrorException(token.Start, token.End, "Did not find expected ."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; Mark end = token.End; Skip(); return new YamlDotNet.Core.Events.DocumentStart(versionDirective, tags2, isImplicit: false, start, end); } if (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); } state = ParserState.StreamEnd; token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); YamlDotNet.Core.Events.StreamEnd result = new YamlDotNet.Core.Events.StreamEnd(token.Start, token.End); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } [return: Nullable(2)] private VersionDirective ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; VersionDirective result = null; while (true) { if (GetCurrentToken() is VersionDirective versionDirective) { if (version != null) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found duplicate %YAML directive."); } if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found incompatible YAML document."); } result = (version = versionDirective); flag = true; } else { if (!(GetCurrentToken() is TagDirective tagDirective)) { break; } if (tags.Contains(tagDirective.Handle)) { throw new SemanticErrorException(tagDirective.Start, tagDirective.End, "Found duplicate %TAG directive."); } tags.Add(tagDirective); flag = true; } Skip(); } if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && version == null) { version = new VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) { foreach (TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentEnd || GetCurrentToken() is YamlDotNet.Core.Tokens.StreamEnd) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static ParsingEvent ProcessEmptyScalar(in Mark position) { return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, string.Empty, ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false, position, position); } private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { if (GetCurrentToken() is Error { Start: var start } error) { throw new SemanticErrorException(in start, error.End, error.Value); } Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { state = states.Pop(); YamlDotNet.Core.Events.AnchorAlias result = new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); Skip(); return result; } Mark start2 = token.Start; AnchorName anchor = AnchorName.Empty; TagName tag = TagName.Empty; Anchor anchor2 = null; Tag tag2 = null; while (true) { if (anchor.IsEmpty && token is Anchor anchor3) { anchor2 = anchor3; anchor = anchor3.Value; Skip(); } else { if (!tag.IsEmpty || !(token is Tag tag3)) { if (token is Anchor { Start: var start3 } anchor4) { throw new SemanticErrorException(in start3, anchor4.End, "While parsing a node, found more than one anchor."); } if (token is YamlDotNet.Core.Tokens.AnchorAlias { Start: var start4 } anchorAlias2) { throw new SemanticErrorException(in start4, anchorAlias2.End, "While parsing a node, did not find expected token."); } if (!(token is Error error2)) { break; } if (tag2 != null && anchor2 != null && !anchor.IsEmpty) { return new YamlDotNet.Core.Events.Scalar(anchor, default(TagName), string.Empty, ScalarStyle.Any, isPlainImplicit: false, isQuotedImplicit: false, anchor2.Start, anchor2.End); } throw new SemanticErrorException(error2.Start, error2.End, error2.Value); } tag2 = tag3; if (string.IsNullOrEmpty(tag3.Handle)) { tag = new TagName(tag3.Suffix); } else { if (!tagDirectives.Contains(tag3.Handle)) { throw new SemanticErrorException(tag3.Start, tag3.End, "While parsing a node, found undefined tag handle."); } tag = new TagName(tagDirectives[tag3.Handle].Prefix + tag3.Suffix); } Skip(); } token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); } bool isEmpty = tag.IsEmpty; if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, token.End); } if (token is YamlDotNet.Core.Tokens.Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tag.IsEmpty) || tag.IsNonSpecific) { isPlainImplicit = true; } else if (tag.IsEmpty) { isQuotedImplicit = true; } state = states.Pop(); Skip(); YamlDotNet.Core.Events.Scalar result2 = new YamlDotNet.Core.Events.Scalar(anchor, tag, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start2, scalar.End, scalar.IsKey); if (!anchor.IsEmpty && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken is Error) { Error error3 = currentToken as Error; throw new SemanticErrorException(error3.Start, error3.End, error3.Value); } } if (state == ParserState.FlowMappingKey && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { throw new SemanticErrorException(currentToken.Start, currentToken.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (token is FlowSequenceStart flowSequenceStart) { state = ParserState.FlowSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Flow, start2, flowSequenceStart.End); } if (token is FlowMappingStart flowMappingStart) { state = ParserState.FlowMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start2, flowMappingStart.End); } if (isBlock) { if (token is BlockSequenceStart blockSequenceStart) { state = ParserState.BlockSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, blockSequenceStart.End); } if (token is BlockMappingStart blockMappingStart) { state = ParserState.BlockMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start2, blockMappingStart.End); } } if (!anchor.IsEmpty || !tag.IsEmpty) { state = states.Pop(); return new YamlDotNet.Core.Events.Scalar(anchor, tag, string.Empty, ScalarStyle.Plain, isEmpty, isQuotedImplicit: false, start2, token.End); } throw new SemanticErrorException(token.Start, token.End, "While parsing a node, did not find expected node content."); } private ParsingEvent ParseDocumentEnd() { Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; Mark start = token.Start; Mark end = start; if (token is YamlDotNet.Core.Tokens.DocumentEnd) { end = token.End; Skip(); isImplicit = false; } else if (!(currentToken is YamlDotNet.Core.Tokens.StreamEnd) && !(currentToken is YamlDotNet.Core.Tokens.DocumentStart) && !(currentToken is FlowSequenceEnd) && !(currentToken is VersionDirective) && (!(Current is YamlDotNet.Core.Events.Scalar) || !(currentToken is Error))) { throw new SemanticErrorException(in start, in end, "Did not find expected ."); } if (version != null && version.Version.Major == 1 && version.Version.Minor > 1) { version = null; } state = ParserState.DocumentStart; return new YamlDotNet.Core.Events.DocumentEnd(isImplicit, start, end); } private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is BlockEntry { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(in position); } if (token is BlockEnd blockEnd) { state = states.Pop(); SequenceEnd result = new SequenceEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a block collection, did not find expected '-' indicator."); } private ParsingEvent ParseIndentlessSequenceEntry() { Token token = GetCurrentToken(); if (token is BlockEntry { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(in position); } state = states.Pop(); return new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is Key { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingValue; return ProcessEmptyScalar(in position); } if (token is Value value) { Skip(); return ProcessEmptyScalar(value.End); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { Skip(); return new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); } if (token is BlockEnd blockEnd) { state = states.Pop(); MappingEnd result = new MappingEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } if (GetCurrentToken() is Error { Start: var start } error) { throw new SyntaxErrorException(in start, error.End, error.Value); } throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a block mapping, did not find expected key."); } private ParsingEvent ParseBlockMappingValue() { Token token = GetCurrentToken(); if (token is Value { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(in position); } if (token is Error { Start: var start } error) { throw new SemanticErrorException(in start, error.End, error.Value); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (!(token is FlowSequenceEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); token = GetCurrentToken(); } if (token is Key) { state = ParserState.FlowSequenceEntryMappingKey; MappingStart result = new MappingStart(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); SequenceEnd result2 = new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); Skip(); return result2; } private ParsingEvent ParseFlowSequenceEntryMappingKey() { Token token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } Mark position = token?.End ?? Mark.Empty; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingValue() { Token token = GetCurrentToken(); if (token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; Token token = GetCurrentToken(); return new MappingEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (!(token is FlowMappingEnd)) { if (!isFirst) { if (token is FlowEntry) { Skip(); token = GetCurrentToken(); } else if (!(token is YamlDotNet.Core.Tokens.Scalar)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (token is Key) { Skip(); token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } state = ParserState.FlowMappingValue; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } if (token is YamlDotNet.Core.Tokens.Scalar) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } if (!(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); Skip(); return new MappingEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseFlowMappingValue(bool isEmpty) { Token token = GetCurrentToken(); if (!isEmpty && token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowMappingKey; if (!isEmpty && token is YamlDotNet.Core.Tokens.Scalar scalar) { Skip(); return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, scalar.Value, scalar.Style, isPlainImplicit: false, isQuotedImplicit: false, token.Start, scalar.End); } return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } } [Nullable(0)] [NullableContext(1)] internal static class ParserExtensions { public static T Consume<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume<[Nullable(0)] T>(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Accept(out @event)) { parser.MoveNext(); return true; } return false; } public static T Require<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { ParsingEvent current = parser.Current; if (current == null) { throw new YamlException("Expected '" + typeof(T).Name + "', got nothing."); } throw new YamlException(current.Start, current.End, $"Expected '{typeof(T).Name}', got '{current.GetType().Name}' (at {current.Start})."); } return @event; } public static bool Accept<[Nullable(0)] T>(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Current == null && !parser.MoveNext()) { throw new EndOfStreamException(); } if (parser.Current is T val) { @event = val; return true; } @event = null; return false; } public static void SkipThisAndNestedEvents(this IParser parser) { int num = 0; do { ParsingEvent parsingEvent = parser.Consume(); num += parsingEvent.NestingIncrease; } while (num > 0); } [Obsolete("Please use Consume() instead")] public static T Expect<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: Nullable(2)] [return: MaybeNull] public static T Allow<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { if (!parser.TryConsume(out var @event)) { return null; } return @event; } [Obsolete("Please use Accept(out var evt) instead")] [return: Nullable(2)] [return: MaybeNull] public static T Peek<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { return null; } return @event; } [Obsolete("Please use TryConsume(out var evt) or Accept(out var evt) instead")] public static bool Accept<[Nullable(0)] T>(this IParser parser) where T : ParsingEvent { T @event; return parser.Accept(out @event); } public static bool TryFindMappingEntry(this IParser parser, Func selector, [Nullable(2)][MaybeNullWhen(false)] out YamlDotNet.Core.Events.Scalar key, [Nullable(2)][MaybeNullWhen(false)] out ParsingEvent value) { if (parser.TryConsume(out var _)) { while (parser.Current != null) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (current is MappingStart || current is SequenceStart) { parser.SkipThisAndNestedEvents(); } else { parser.MoveNext(); } continue; } bool num = selector(scalar); parser.MoveNext(); if (num) { value = parser.Current; key = scalar; return true; } parser.SkipThisAndNestedEvents(); } } key = null; value = null; return false; } } internal enum ParserState { StreamStart, StreamEnd, ImplicitDocumentStart, DocumentStart, DocumentContent, DocumentEnd, BlockNode, BlockNodeOrIndentlessSequence, FlowNode, BlockSequenceFirstEntry, BlockSequenceEntry, IndentlessSequenceEntry, BlockMappingFirstKey, BlockMappingKey, BlockMappingValue, FlowSequenceFirstEntry, FlowSequenceEntry, FlowSequenceEntryMappingKey, FlowSequenceEntryMappingValue, FlowSequenceEntryMappingEnd, FlowMappingFirstKey, FlowMappingKey, FlowMappingValue, FlowMappingEmptyValue } internal sealed class RecursionLevel { private int current; public int Maximum { get; } public RecursionLevel(int maximum) { Maximum = maximum; } public void Increment() { if (!TryIncrement()) { throw new MaximumRecursionLevelReachedException("Maximum level of recursion reached"); } } public bool TryIncrement() { if (current < Maximum) { current++; return true; } return false; } public void Decrement() { if (current == 0) { throw new InvalidOperationException("Attempted to decrement RecursionLevel to a negative value"); } current--; } } internal enum ScalarStyle { Any, Plain, SingleQuoted, DoubleQuoted, Literal, Folded } [NullableContext(1)] [Nullable(0)] internal class Scanner : IScanner { private const int MaxVersionNumberLength = 9; private static readonly SortedDictionary SimpleEscapeCodes = new SortedDictionary { { '0', '\0' }, { 'a', '\a' }, { 'b', '\b' }, { 't', '\t' }, { '\t', '\t' }, { 'n', '\n' }, { 'v', '\v' }, { 'f', '\f' }, { 'r', '\r' }, { 'e', '\u001b' }, { ' ', ' ' }, { '"', '"' }, { '\\', '\\' }, { '/', '/' }, { 'N', '\u0085' }, { '_', '\u00a0' }, { 'L', '\u2028' }, { 'P', '\u2029' } }; private readonly Stack indents = new Stack(); private readonly InsertionQueue tokens = new InsertionQueue(); private readonly Stack simpleKeys = new Stack(); private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private int flowSequenceStartLine; private bool flowCollectionFetched; private bool startFlowCollectionFetched; private int indent = -1; private bool flowScalarFetched; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; [Nullable(2)] private Token previous; [Nullable(2)] private Anchor previousAnchor; [Nullable(2)] private YamlDotNet.Core.Tokens.Scalar lastScalar; private static readonly byte[] EmptyBytes = new byte[0]; public bool SkipComments { get; private set; } [Nullable(2)] [field: Nullable(2)] public Token Current { [NullableContext(2)] get; [NullableContext(2)] private set; } public Mark CurrentPosition => cursor.Mark(); private bool IsDocumentStart() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('.') && analyzer.Check('.', 1) && analyzer.Check('.', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentIndicator() { if (!IsDocumentStart()) { return IsDocumentEnd(); } return true; } public Scanner(TextReader input, bool skipComments = true) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; } public bool MoveNext() { if (Current != null) { ConsumeCurrent(); } return MoveNextWithoutConsuming(); } public bool MoveNextWithoutConsuming() { if (!tokenAvailable && !streamEndProduced) { FetchMoreTokens(); } if (tokens.Count > 0) { Current = tokens.Dequeue(); tokenAvailable = false; return true; } Current = null; return false; } public void ConsumeCurrent() { tokensParsed++; tokenAvailable = false; previous = Current; Current = null; } private char ReadCurrentCharacter() { char result = analyzer.Peek(0); Skip(); return result; } private char ReadLine() { if (analyzer.Check("\r\n\u0085")) { SkipLine(); return '\n'; } char result = analyzer.Peek(0); SkipLine(); return result; } private void FetchMoreTokens() { while (true) { bool flag = false; if (tokens.Count == 0) { flag = true; } else { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) { flag = true; break; } } } if (!flag) { break; } FetchNextToken(); } tokenAvailable = true; } private static bool StartsWith(StringBuilder what, char start) { if (what.Length > 0) { return what[0] == start; } return false; } private void StaleSimpleKeys() { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + 1024 < cursor.Index)) { if (simpleKey.IsRequired) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a simple key, could not find expected ':'.", mark, mark)); } simpleKey.MarkAsImpossible(); } } } private void FetchNextToken() { if (!streamStartProduced) { FetchStreamStart(); return; } ScanToNextToken(); StaleSimpleKeys(); UnrollIndent(cursor.LineOffset); analyzer.Buffer.Cache(4); if (analyzer.Buffer.EndOfInput) { lastScalar = null; FetchStreamEnd(); } if (cursor.LineOffset == 0 && analyzer.Check('%')) { lastScalar = null; FetchDirective(); return; } if (IsDocumentStart()) { lastScalar = null; FetchDocumentIndicator(isStartToken: true); return; } if (IsDocumentEnd()) { lastScalar = null; FetchDocumentIndicator(isStartToken: false); return; } if (analyzer.Check('[')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: true); return; } if (analyzer.Check('{')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: false); return; } if (analyzer.Check(']')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: true); return; } if (analyzer.Check('}')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: false); return; } if (analyzer.Check(',')) { lastScalar = null; FetchFlowEntry(); return; } if (analyzer.Check('-')) { if (analyzer.IsWhiteBreakOrZero(1)) { FetchBlockEntry(); return; } if (flowLevel > 0 && analyzer.Check(",[]{}", 1)) { tokens.Enqueue(new Error("Invalid key indicator format.", cursor.Mark(), cursor.Mark())); } } if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && analyzer.IsWhiteBreakOrZero(1)) { FetchKey(); } else if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && (!simpleKeyAllowed || flowLevel <= 0) && (!flowScalarFetched || !analyzer.Check(':', 1)) && (analyzer.IsWhiteBreakOrZero(1) || analyzer.Check(',', 1) || flowScalarFetched || flowCollectionFetched || startFlowCollectionFetched)) { if (lastScalar != null) { lastScalar.IsKey = true; lastScalar = null; } FetchValue(); } else if (analyzer.Check('*')) { FetchAnchor(isAlias: true); } else if (analyzer.Check('&')) { FetchAnchor(isAlias: false); } else if (analyzer.Check('!')) { FetchTag(); } else if (analyzer.Check('|') && flowLevel == 0) { FetchBlockScalar(isLiteral: true); } else if (analyzer.Check('>') && flowLevel == 0) { FetchBlockScalar(isLiteral: false); } else if (analyzer.Check('\'')) { FetchFlowScalar(isSingleQuoted: true); } else if (analyzer.Check('"')) { FetchFlowScalar(isSingleQuoted: false); } else if ((!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("-?:,[]{}#&*!|>'\"%@`")) || (analyzer.Check('-') && !analyzer.IsWhite(1)) || (analyzer.Check("?:") && !analyzer.IsWhiteBreakOrZero(1)) || (simpleKeyAllowed && flowLevel > 0)) { if (plainScalarFollowedByComment) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning plain scalar, found a comment between adjacent scalars.", mark, mark)); } if ((flowScalarFetched || (flowCollectionFetched && !startFlowCollectionFetched)) && analyzer.Check(':')) { Skip(); } flowScalarFetched = false; flowCollectionFetched = false; startFlowCollectionFetched = false; plainScalarFollowedByComment = false; FetchPlainScalar(); } else { if (simpleKeyAllowed && indent >= cursor.LineOffset && analyzer.IsTab()) { throw new SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark start = cursor.Mark(); Skip(); throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning for the next token, found character that cannot start any token."); } Skip(); } } private bool CheckWhiteSpace() { if (!analyzer.Check(' ')) { if (flowLevel > 0 || !simpleKeyAllowed) { return analyzer.Check('\t'); } return false; } return true; } private void Skip() { cursor.Skip(); analyzer.Buffer.Skip(1); } private void SkipLine() { if (analyzer.IsCrLf()) { cursor.SkipLineByOffset(2); analyzer.Buffer.Skip(2); } else if (analyzer.IsBreak()) { cursor.SkipLineByOffset(1); analyzer.Buffer.Skip(1); } else if (!analyzer.IsZero()) { throw new InvalidOperationException("Not at a break."); } } private void ScanToNextToken() { while (true) { if (CheckWhiteSpace()) { Skip(); continue; } ProcessComment(); if (analyzer.IsBreak()) { SkipLine(); if (flowLevel == 0) { simpleKeyAllowed = true; } continue; } break; } } private void ProcessComment() { if (!analyzer.Check('#')) { return; } Mark start = cursor.Mark(); Skip(); while (analyzer.IsSpace()) { Skip(); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } if (!SkipComments) { bool isInline = previous != null && previous.End.Line == start.Line && previous.End.Column != 1 && !(previous is YamlDotNet.Core.Tokens.StreamStart); tokens.Enqueue(new YamlDotNet.Core.Tokens.Comment(builder.ToString(), isInline, start, cursor.Mark())); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchStreamStart() { simpleKeys.Push(new SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamStart(in start, in start)); } private void UnrollIndent(int column) { if (flowLevel == 0) { while (indent > column) { Mark start = cursor.Mark(); tokens.Enqueue(new BlockEnd(in start, in start)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } [NullableContext(2)] private Token ScanDirective() { Mark start = cursor.Mark(); Skip(); string text = ScanDirectiveName(in start); Token result; if (!(text == "YAML")) { if (!(text == "TAG")) { while (!analyzer.EndOfInput && !analyzer.Check('#') && !analyzer.IsBreak()) { Skip(); } return null; } result = ScanTagDirectiveValue(in start); } else { if (!(previous is YamlDotNet.Core.Tokens.DocumentStart) && !(previous is YamlDotNet.Core.Tokens.StreamStart) && !(previous is YamlDotNet.Core.Tokens.DocumentEnd)) { throw new SemanticErrorException(in start, cursor.Mark(), "While scanning a version directive, did not find preceding ."); } result = ScanVersionDirectiveValue(in start); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); } return result; } private void FetchDocumentIndicator(bool isStartToken) { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentStart(in start, cursor.Mark())); return; } Token token = null; while (!analyzer.EndOfInput && !analyzer.IsBreak() && !analyzer.Check('#')) { if (!analyzer.IsWhite()) { token = new Error("While scanning a document end, found invalid content after '...' marker.", start, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentEnd(in start, in start)); if (token != null) { tokens.Enqueue(token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Token token; if (isSequenceToken) { token = new FlowSequenceStart(in start, in start); flowSequenceStartLine = token.Start.Line; } else { token = new FlowMappingStart(in start, in start); } tokens.Enqueue(token); startFlowCollectionFetched = true; } private void IncreaseFlowLevel() { simpleKeys.Push(new SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Token token = null; Token item; if (isSequenceToken) { if (analyzer.Check('#')) { token = new Error("While scanning a flow sequence end, found invalid comment after ']'.", start, start); } item = new FlowSequenceEnd(in start, in start); } else { item = new FlowMappingEnd(in start, in start); } tokens.Enqueue(item); if (token != null) { tokens.Enqueue(token); } flowCollectionFetched = true; } private void DecreaseFlowLevel() { if (flowLevel > 0) { flowLevel--; simpleKeys.Pop(); } } private void FetchFlowEntry() { RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); if (analyzer.Check('#')) { tokens.Enqueue(new Error("While scanning a flow entry, found invalid comment after comma.", start, end)); } else { tokens.Enqueue(new FlowEntry(in start, in end)); } } private void FetchBlockEntry() { if (flowLevel == 0) { if (!simpleKeyAllowed) { if (previousAnchor != null && previousAnchor.End.Line == cursor.Line) { throw new SemanticErrorException(previousAnchor.Start, previousAnchor.End, "Anchor before sequence entry on same line is not allowed."); } Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Block sequence entries are not allowed in this context.", mark, mark)); } RollIndent(cursor.LineOffset, -1, isSequence: true, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new BlockEntry(in start, cursor.Mark())); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { Mark start = cursor.Mark(); throw new SyntaxErrorException(in start, in start, "Mapping keys are not allowed in this context."); } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = flowLevel == 0; Mark start2 = cursor.Mark(); Skip(); tokens.Enqueue(new Key(in start2, cursor.Mark())); } private void FetchValue() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible) { tokens.Insert(simpleKey.TokenNumber - tokensParsed, new Key(simpleKey.Mark, simpleKey.Mark)); RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, isSequence: false, simpleKey.Mark); simpleKey.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Mapping values are not allowed in this context.", mark, mark)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0 && simpleKey.LineOffset == 0) { tokens.Insert(tokens.Count, new Key(simpleKey.Mark, simpleKey.Mark)); flag = false; } } simpleKeyAllowed = flag; } Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new Value(in start, cursor.Mark())); } private void RollIndent(int column, int number, bool isSequence, Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new BlockMappingStart(in position, in position)) : ((Token)new BlockSequenceStart(in position, in position))); if (number == -1) { tokens.Enqueue(item); } else { tokens.Insert(number - tokensParsed, item); } } } private void FetchAnchor(bool isAlias) { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanAnchor(isAlias)); } private Token ScanAnchor(bool isAlias) { Mark start = cursor.Mark(); Skip(); bool flag = false; if (isAlias) { SimpleKey simpleKey = simpleKeys.Peek(); flag = simpleKey.IsRequired && simpleKey.IsPossible; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("[]{},") && (!flag || !analyzer.Check(':') || !analyzer.IsWhiteBreakOrZero(1))) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0 || (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("?:,]}%@`"))) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning an anchor or alias, found value containing disallowed: []{},"); } AnchorName value = new AnchorName(builder.ToString()); if (isAlias) { return new YamlDotNet.Core.Tokens.AnchorAlias(value, start, cursor.Mark()); } return previousAnchor = new Anchor(value, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchTag() { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanTag()); } private Token ScanTag() { Mark start = cursor.Mark(); string text; string text2; if (analyzer.Check('<', 1)) { text = string.Empty; Skip(); Skip(); text2 = ScanTagUri(null, start); if (!analyzer.Check('>')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find the expected '>'."); } Skip(); } else { string text3 = ScanTagHandle(isDirective: false, start); if (text3.Length > 1 && text3[0] == '!' && text3[text3.Length - 1] == '!') { text = text3; text2 = ScanTagUri(null, start); } else { text2 = ScanTagUri(text3, start); text = "!"; if (text2.Length == 0) { text2 = text; text = string.Empty; } } } if (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check(',')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find expected whitespace, comma or line break."); } return new Tag(text, text2, start, cursor.Mark()); } private void FetchBlockScalar(bool isLiteral) { SaveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private Token ScanBlockScalar(bool isLiteral) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; int num = 0; int num2 = 0; int currentIndent = 0; bool flag = false; bool? isFirstLine = null; Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); } } else if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); } } if (analyzer.Check('#')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found a comment without whtespace after '>' indicator."); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); if (!isFirstLine.HasValue) { isFirstLine = true; } else if (isFirstLine == true) { isFirstLine = false; } } Mark end = cursor.Mark(); if (num2 != 0) { currentIndent = ((indent >= 0) ? (indent + num2) : num2); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end, ref isFirstLine); isFirstLine = false; while (cursor.LineOffset == currentIndent && !analyzer.IsZero() && !IsDocumentEnd()) { bool flag2 = analyzer.IsWhite(); if (!isLiteral && StartsWith(builder2, '\n') && !flag && !flag2) { if (builder3.Length == 0) { builder.Append(' '); } builder2.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } builder.Append(builder3.ToString()); builder3.Length = 0; flag = analyzer.IsWhite(); while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } char c = ReadLine(); if (c != 0) { builder2.Append(c); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end, ref isFirstLine); } if (num != -1) { builder.Append((object?)builder2); } if (num == 1) { builder.Append((object?)builder3); } ScalarStyle style = (isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), style, start, end); } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { int num = 0; int num2 = -1; end = cursor.Mark(); while (true) { if ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) { Skip(); continue; } if (cursor.LineOffset > num) { num = cursor.LineOffset; } if (!analyzer.IsBreak()) { break; } if (isFirstLine == true) { isFirstLine = false; num2 = cursor.LineOffset; } breaks.Append(ReadLine()); end = cursor.Mark(); } if (isLiteral && isFirstLine == true) { int num3 = cursor.LineOffset; int num4 = 0; while (!analyzer.IsBreak(num4) && analyzer.IsSpace(num4)) { num4++; num3++; } if (analyzer.IsBreak(num4) && num3 > cursor.LineOffset) { isFirstLine = false; num2 = num3; } } if (isLiteral && num2 > 1 && currentIndent < num2 - 1) { throw new SemanticErrorException(in end, cursor.Mark(), "While scanning a literal block scalar, found extra spaces in first line."); } if (!isLiteral && num > cursor.LineOffset && num2 > -1) { throw new SemanticErrorException(in end, cursor.Mark(), "While scanning a literal block scalar, found more spaces in lines above first content line."); } if (currentIndent == 0 && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1)); } return currentIndent; } private void FetchFlowScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; flowScalarFetched = true; tokens.Enqueue(ScanFlowScalar(isSingleQuoted)); if (!isSingleQuoted && analyzer.Check('#')) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", mark, mark)); } } private Token ScanFlowScalar(bool isSingleQuoted) { Mark start = cursor.Mark(); Skip(); StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; while (true) { if (IsDocumentIndicator()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a multi-line double-quoted scalar, found wrong indentation."); } flag = false; while (!analyzer.IsWhiteBreakOrZero()) { if (isSingleQuoted && analyzer.Check('\'') && analyzer.Check('\'', 1)) { builder.Append('\''); Skip(); Skip(); continue; } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } if (!isSingleQuoted && analyzer.Check('\\') && analyzer.IsBreak(1)) { Skip(); SkipLine(); flag = true; break; } if (!isSingleQuoted && analyzer.Check('\\')) { int num = 0; char c = analyzer.Peek(1); switch (c) { case 'x': num = 2; break; case 'u': num = 4; break; case 'U': num = 8; break; default: { if (SimpleEscapeCodes.TryGetValue(c, out var value)) { builder.Append(value); break; } throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unknown escape character."); } } Skip(); Skip(); if (num <= 0) { continue; } int num2 = 0; for (int i = 0; i < num; i++) { if (!analyzer.IsHex(i)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, did not find expected hexadecimal number."); } num2 = (num2 << 4) + analyzer.AsHex(i); } if ((num2 >= 55296 && num2 <= 57343) || num2 > 1114111) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode character escape code."); } builder.Append(char.ConvertFromUtf32(num2)); for (int j = 0; j < num; j++) { Skip(); } } else { builder.Append(ReadCurrentCharacter()); } } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append(builder4.ToString()); } } else { builder.Append(builder3.ToString()); builder.Append(builder4.ToString()); } builder3.Length = 0; builder4.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } } Skip(); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper4/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchPlainScalar() { SaveSimpleKey(); simpleKeyAllowed = false; bool isMultiline = false; YamlDotNet.Core.Tokens.Scalar item = (lastScalar = ScanPlainScalar(ref isMultiline)); if (isMultiline && analyzer.Check(':') && flowLevel == 0 && indent < cursor.LineOffset) { tokens.Enqueue(new Error("While scanning a multiline plain scalar, found invalid mapping.", cursor.Mark(), cursor.Mark())); } tokens.Enqueue(item); } private YamlDotNet.Core.Tokens.Scalar ScanPlainScalar(ref bool isMultiline) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; int num = indent + 1; Mark start = cursor.Mark(); Mark end = start; SimpleKey simpleKey = simpleKeys.Peek(); while (!IsDocumentIndicator()) { if (analyzer.Check('#')) { if (indent < 0 && flowLevel == 0) { plainScalarFollowedByComment = true; } break; } bool flag2 = analyzer.Check('*') && (!simpleKey.IsPossible || !simpleKey.IsRequired); while (!analyzer.IsWhiteBreakOrZero()) { if ((analyzer.Check(':') && !flag2 && (analyzer.IsWhiteBreakOrZero(1) || (flowLevel > 0 && analyzer.Check(',', 1)))) || (flowLevel > 0 && analyzer.Check(",[]{}"))) { if (flowLevel == 0 && !simpleKey.IsPossible) { tokens.Enqueue(new Error("While scanning a plain scalar value, found invalid mapping.", cursor.Mark(), cursor.Mark())); } break; } if (flag || builder2.Length > 0) { if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; flag = false; } else { builder.Append((object?)builder2); builder2.Length = 0; } } if (flowLevel > 0 && cursor.LineOffset < num) { throw new Exception(); } builder.Append(ReadCurrentCharacter()); end = cursor.Mark(); } if (!analyzer.IsWhite() && !analyzer.IsBreak()) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (flag && cursor.LineOffset < num && analyzer.IsTab()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a plain scalar, found a tab character that violate indentation."); } if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else { isMultiline = true; if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } } if (flowLevel == 0 && cursor.LineOffset < num) { break; } } if (flag) { simpleKeyAllowed = true; } return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), ScalarStyle.Plain, start, end); } finally { ((IDisposable)builderWrapper4/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void RemoveSimpleKey() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible && simpleKey.IsRequired) { throw new SyntaxErrorException(simpleKey.Mark, simpleKey.Mark, "While scanning a simple key, could not find expected ':'."); } simpleKey.MarkAsImpossible(); } private string ScanDirectiveName(in Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, could not find expected directive name."); } if (analyzer.EndOfInput) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, found unexpected end of stream."); } if (!analyzer.IsWhiteBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, found unexpected non-alphabetical character."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void SkipWhitespaces() { while (analyzer.IsWhite()) { Skip(); } } private Token ScanVersionDirectiveValue(in Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(in start); if (!analyzer.Check('.')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, did not find expected digit or '.' character."); } Skip(); int minor = ScanVersionDirectiveNumber(in start); return new VersionDirective(new Version(major, minor), start, start); } private Token ScanTagDirectiveValue(in Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace."); } SkipWhitespaces(); string prefix = ScanTagUri(null, start); if (!analyzer.IsWhiteBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace or line break."); } return new TagDirective(handle, prefix, start, start); } private string ScanTagUri([Nullable(2)] string head, Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; if (head != null && head.Length > 1) { builder.Append(head.Substring(1)); } while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$.!~*'()[]%") || (analyzer.Check(',') && !analyzer.IsBreak(1))) { if (analyzer.Check('%')) { builder.Append(ScanUriEscapes(in start)); } else if (analyzer.Check('+')) { builder.Append(' '); Skip(); } else { builder.Append(ReadCurrentCharacter()); } } if (builder.Length == 0) { return string.Empty; } string text = builder.ToString(); if (text.EndsWith(",")) { throw new SyntaxErrorException(cursor.Mark(), cursor.Mark(), "Unexpected comma at end of tag"); } return text; } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private string ScanUriEscapes(in Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find URI escaped octet."); } int num2 = (analyzer.AsHex(1) << 4) + analyzer.AsHex(2); if (num == 0) { num = (((num2 & 0x80) == 0) ? 1 : (((num2 & 0xE0) == 192) ? 2 : (((num2 & 0xF0) == 224) ? 3 : (((num2 & 0xF8) == 240) ? 4 : 0)))); if (num == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect leading UTF-8 octet."); } array = new byte[num]; } else if ((num2 & 0xC0) != 128) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect trailing UTF-8 octet."); } array[count++] = (byte)num2; Skip(); Skip(); Skip(); } while (--num > 0); string text = Encoding.UTF8.GetString(array, 0, count); if (text.Length == 0 || text.Length > 2) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect UTF-8 sequence."); } return text; } private string ScanTagHandle(bool isDirective, Mark start) { if (!analyzer.Check('!')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find expected '!'."); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append(ReadCurrentCharacter()); while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (analyzer.Check('!')) { builder.Append(ReadCurrentCharacter()); } else if (isDirective && (builder.Length != 1 || builder[0] != '!')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag directive, did not find expected '!'."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private int ScanVersionDirectiveNumber(in Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, found extremely long version number."); } num = num * 10 + analyzer.AsDigit(); Skip(); } if (num2 == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, did not find expected version number."); } return num; } private void SaveSimpleKey() { bool isRequired = flowLevel == 0 && indent == cursor.LineOffset; if (simpleKeyAllowed) { SimpleKey item = new SimpleKey(isRequired, tokensParsed + tokens.Count, cursor); RemoveSimpleKey(); simpleKeys.Pop(); simpleKeys.Push(item); } } } [NullableContext(1)] [Nullable(0)] internal class SemanticErrorException : YamlException { public SemanticErrorException(string message) : base(message) { } public SemanticErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SemanticErrorException(string message, Exception inner) : base(message, inner) { } } [Nullable(0)] [NullableContext(1)] internal sealed class SimpleKey { private readonly Cursor cursor; public bool IsPossible { get; private set; } public bool IsRequired { get; } public int TokenNumber { get; } public int Index => cursor.Index; public int Line => cursor.Line; public int LineOffset => cursor.LineOffset; public Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public SimpleKey() { cursor = new Cursor(); } public SimpleKey(bool isRequired, int tokenNumber, Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new Cursor(cursor); } } internal sealed class StringLookAheadBuffer : ILookAheadBuffer { [Nullable(1)] private readonly string value; public int Position { get; private set; } public int Length => value.Length; public bool EndOfInput => IsOutside(Position); [NullableContext(1)] public StringLookAheadBuffer(string value) { this.value = value; } public char Peek(int offset) { int index = Position + offset; if (!IsOutside(index)) { return value[index]; } return '\0'; } private bool IsOutside(int index) { return index >= value.Length; } public void Skip(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } Position += length; } } [Nullable(0)] [NullableContext(1)] internal sealed class SyntaxErrorException : YamlException { public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SyntaxErrorException(string message, Exception inner) : base(message, inner) { } } [Nullable(new byte[] { 0, 1, 1 })] [NullableContext(1)] internal sealed class TagDirectiveCollection : KeyedCollection { public TagDirectiveCollection() { } public TagDirectiveCollection(IEnumerable tagDirectives) { foreach (TagDirective tagDirective in tagDirectives) { Add(tagDirective); } } protected override string GetKeyForItem(TagDirective item) { return item.Handle; } public new bool Contains(TagDirective directive) { return Contains(GetKeyForItem(directive)); } } [Nullable(0)] [NullableContext(1)] internal readonly struct TagName : IEquatable { public static readonly TagName Empty; [Nullable(2)] private readonly string value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of a non-specific tag"); public bool IsEmpty => value == null; public bool IsNonSpecific { get { if (!IsEmpty) { if (!(value == "!")) { return value == "?"; } return true; } return false; } } public bool IsLocal { get { if (!IsEmpty) { return Value[0] == '!'; } return false; } } public bool IsGlobal { get { if (!IsEmpty) { return !IsLocal; } return false; } } public TagName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (value.Length == 0) { throw new ArgumentException("Tag value must not be empty.", "value"); } if (IsGlobal && !Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)) { throw new ArgumentException("Global tags must be valid URIs.", "value"); } } public override string ToString() { return value ?? "?"; } public bool Equals(TagName other) { return object.Equals(value, other.value); } [NullableContext(2)] public override bool Equals(object obj) { if (obj is TagName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(TagName left, TagName right) { return left.Equals(right); } public static bool operator !=(TagName left, TagName right) { return !(left == right); } public static bool operator ==(TagName left, string right) { return object.Equals(left.value, right); } public static bool operator !=(TagName left, string right) { return !(left == right); } [NullableContext(2)] public static implicit operator TagName(string value) { if (value != null) { return new TagName(value); } return Empty; } } internal sealed class Version { public int Major { get; } public int Minor { get; } public Version(int major, int minor) { if (major < 0) { throw new ArgumentOutOfRangeException("major", $"{major} should be >= 0"); } Major = major; if (minor < 0) { throw new ArgumentOutOfRangeException("minor", $"{minor} should be >= 0"); } Minor = minor; } [NullableContext(2)] public override bool Equals(object obj) { if (obj is Version version && Major == version.Major) { return Minor == version.Minor; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Major.GetHashCode(), Minor.GetHashCode()); } } [Nullable(0)] [NullableContext(1)] internal class YamlException : Exception { public Mark Start { get; } public Mark End { get; } public YamlException(string message) : this(in Mark.Empty, in Mark.Empty, message) { } public YamlException(in Mark start, in Mark end, string message) : this(in start, in end, message, null) { } public YamlException(in Mark start, in Mark end, string message, [Nullable(2)] Exception innerException) : base(message, innerException) { Start = start; End = end; } public YamlException(string message, Exception inner) : this(in Mark.Empty, in Mark.Empty, message, inner) { } public override string ToString() { return $"({Start}) - ({End}): {Message}"; } } } namespace YamlDotNet.Core.Tokens { internal class Anchor : Token { public AnchorName Value { get; } public Anchor(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public Anchor(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class AnchorAlias : Token { public AnchorName Value { get; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class BlockEnd : Token { public BlockEnd() : this(in Mark.Empty, in Mark.Empty) { } public BlockEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockEntry : Token { public BlockEntry() : this(in Mark.Empty, in Mark.Empty) { } public BlockEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockMappingStart : Token { public BlockMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockSequenceStart : Token { public BlockSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } [NullableContext(1)] [Nullable(0)] internal sealed class Comment : Token { public string Value { get; } public bool IsInline { get; } public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class DocumentEnd : Token { public DocumentEnd() : this(in Mark.Empty, in Mark.Empty) { } public DocumentEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class DocumentStart : Token { public DocumentStart() : this(in Mark.Empty, in Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : base(in start, in end) { } } [NullableContext(1)] [Nullable(0)] internal class Error : Token { public string Value { get; } public Error(string value, Mark start, Mark end) : base(in start, in end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(in Mark.Empty, in Mark.Empty) { } public FlowEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingStart : Token { public FlowMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceEnd : Token { public FlowSequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceStart : Token { public FlowSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Key : Token { public Key() : this(in Mark.Empty, in Mark.Empty) { } public Key(in Mark start, in Mark end) : base(in start, in end) { } } [NullableContext(1)] [Nullable(0)] internal sealed class Scalar : Token { public bool IsKey { get; set; } public string Value { get; } public ScalarStyle Style { get; } public Scalar(string value) : this(value, ScalarStyle.Any) { } public Scalar(string value, ScalarStyle style) : this(value, style, Mark.Empty, Mark.Empty) { } public Scalar(string value, ScalarStyle style, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class StreamEnd : Token { public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } } [Nullable(0)] [NullableContext(1)] internal sealed class Tag : Token { public string Handle { get; } public string Suffix { get; } public Tag(string handle, string suffix) : this(handle, suffix, Mark.Empty, Mark.Empty) { } public Tag(string handle, string suffix, Mark start, Mark end) : base(in start, in end) { Handle = handle ?? throw new ArgumentNullException("handle"); Suffix = suffix ?? throw new ArgumentNullException("suffix"); } } [Nullable(0)] [NullableContext(1)] internal class TagDirective : Token { private static readonly Regex TagHandlePattern = new Regex("^!([0-9A-Za-z_\\-]*!)?$", RegexOptions.Compiled); public string Handle { get; } public string Prefix { get; } public TagDirective(string handle, string prefix) : this(handle, prefix, Mark.Empty, Mark.Empty) { } public TagDirective(string handle, string prefix, Mark start, Mark end) : base(in start, in end) { if (string.IsNullOrEmpty(handle)) { throw new ArgumentNullException("handle", "Tag handle must not be empty."); } if (!TagHandlePattern.IsMatch(handle)) { throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); } Handle = handle; if (string.IsNullOrEmpty(prefix)) { throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); } Prefix = prefix; } [NullableContext(2)] public override bool Equals(object obj) { if (obj is TagDirective tagDirective && Handle.Equals(tagDirective.Handle)) { return Prefix.Equals(tagDirective.Prefix); } return false; } public override int GetHashCode() { return Handle.GetHashCode() ^ Prefix.GetHashCode(); } public override string ToString() { return Handle + " => " + Prefix; } } internal abstract class Token { public Mark Start { get; } public Mark End { get; } protected Token(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Value : Token { public Value() : this(in Mark.Empty, in Mark.Empty) { } public Value(in Mark start, in Mark end) : base(in start, in end) { } } [Nullable(0)] [NullableContext(1)] internal sealed class VersionDirective : Token { public Version Version { get; } public VersionDirective(Version version) : this(version, Mark.Empty, Mark.Empty) { } public VersionDirective(Version version, Mark start, Mark end) : base(in start, in end) { Version = version; } [NullableContext(2)] public override bool Equals(object obj) { if (obj is VersionDirective versionDirective) { return Version.Equals(versionDirective.Version); } return false; } public override int GetHashCode() { return Version.GetHashCode(); } } } namespace YamlDotNet.Core.Events { [NullableContext(1)] [Nullable(0)] internal sealed class AnchorAlias : ParsingEvent { internal override EventType Type => EventType.Alias; public AnchorName Value { get; } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new YamlException(in start, in end, "Anchor value must not be empty."); } Value = value; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Alias [value = {Value}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(1)] [Nullable(0)] internal sealed class Comment : ParsingEvent { public string Value { get; } public bool IsInline { get; } internal override EventType Type => EventType.Comment; public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value; IsInline = isInline; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } public override string ToString() { return (IsInline ? "Inline" : "Block") + " Comment [" + Value + "]"; } } [NullableContext(1)] [Nullable(0)] internal sealed class DocumentEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.DocumentEnd; public bool IsImplicit { get; } public DocumentEnd(bool isImplicit, Mark start, Mark end) : base(in start, in end) { IsImplicit = isImplicit; } public DocumentEnd(bool isImplicit) : this(isImplicit, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document end [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(2)] [Nullable(0)] internal sealed class DocumentStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.DocumentStart; public TagDirectiveCollection Tags { get; } public VersionDirective Version { get; } public bool IsImplicit { get; } public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit, Mark start, Mark end) : base(in start, in end) { Version = version; Tags = tags; IsImplicit = isImplicit; } public DocumentStart(VersionDirective version, TagDirectiveCollection tags, bool isImplicit) : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : this(null, null, isImplicit: true, start, end) { } public DocumentStart() : this(null, null, isImplicit: true, Mark.Empty, Mark.Empty) { } [NullableContext(1)] public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } [NullableContext(1)] public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } [NullableContext(1)] internal interface IParsingEventVisitor { void Visit(AnchorAlias e); void Visit(StreamStart e); void Visit(StreamEnd e); void Visit(DocumentStart e); void Visit(DocumentEnd e); void Visit(Scalar e); void Visit(SequenceStart e); void Visit(SequenceEnd e); void Visit(MappingStart e); void Visit(MappingEnd e); void Visit(Comment e); } [NullableContext(1)] [Nullable(0)] internal class MappingEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.MappingEnd; public MappingEnd(in Mark start, in Mark end) : base(in start, in end) { } public MappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Mapping end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(1)] [Nullable(0)] internal sealed class MappingStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.MappingStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public MappingStyle Style { get; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public MappingStart() : this(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Any, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Mapping start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum MappingStyle { Any, Block, Flow } internal abstract class NodeEvent : ParsingEvent { public AnchorName Anchor { get; } public TagName Tag { get; } public abstract bool IsCanonical { get; } protected NodeEvent(AnchorName anchor, TagName tag, Mark start, Mark end) : base(in start, in end) { Anchor = anchor; Tag = tag; } protected NodeEvent(AnchorName anchor, TagName tag) : this(anchor, tag, Mark.Empty, Mark.Empty) { } } internal abstract class ParsingEvent { public virtual int NestingIncrease => 0; internal abstract EventType Type { get; } public Mark Start { get; } public Mark End { get; } [NullableContext(1)] public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } [NullableContext(1)] [Nullable(0)] internal sealed class Scalar : NodeEvent { internal override EventType Type => EventType.Scalar; public string Value { get; } public ScalarStyle Style { get; } public bool IsPlainImplicit { get; } public bool IsQuotedImplicit { get; } public override bool IsCanonical { get { if (!IsPlainImplicit) { return !IsQuotedImplicit; } return false; } } public bool IsKey { get; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end, bool isKey = false) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; IsKey = isKey; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, Mark.Empty, Mark.Empty) { } public Scalar(string value) : this(AnchorName.Empty, TagName.Empty, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(TagName tag, string value) : this(AnchorName.Empty, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(AnchorName anchor, TagName tag, string value) : this(anchor, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Scalar [anchor = {base.Anchor}, tag = {base.Tag}, value = {Value}, style = {Style}, isPlainImplicit = {IsPlainImplicit}, isQuotedImplicit = {IsQuotedImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(1)] [Nullable(0)] internal sealed class SequenceEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.SequenceEnd; public SequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } public SequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Sequence end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(1)] [Nullable(0)] internal sealed class SequenceStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.SequenceStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public SequenceStyle Style { get; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Sequence start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum SequenceStyle { Any, Block, Flow } [NullableContext(1)] [Nullable(0)] internal sealed class StreamEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.StreamEnd; public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Stream end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } [NullableContext(1)] [Nullable(0)] internal sealed class StreamStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.StreamStart; public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } public override string ToString() { return "Stream start"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { [NullableContext(1)] public static void Deconstruct<[Nullable(2)] TKey, [Nullable(2)] TValue>([Nullable(new byte[] { 0, 1, 1 })] this KeyValuePair pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] internal sealed class AllowNullAttribute : Attribute { } [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DoesNotReturnAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [NullableContext(1)] [Nullable(0)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [NullableContext(1)] [Nullable(0)] [DebuggerNonUserCode] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [Nullable(0)] [NullableContext(1)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } [CompilerGenerated] internal sealed class <5ca54969-8537-4ec9-9411-94048fd5665f> { internal static uint ComputeStringHash(string s) { uint num = default(uint); if (s != null) { num = 2166136261u; for (int i = 0; i < s.Length; i++) { num = (s[i] ^ num) * 16777619; } } return num; } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [CompilerGenerated] [Embedded] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ItemManager { [PublicAPI] internal enum CraftingTable { Disabled, Inventory, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("piece_MeadCauldron")] MeadCauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("piece_preptable")] PrepTable, [InternalName("blackforge")] BlackForge, Custom } [PublicAPI] internal enum ConversionPiece { Disabled, [InternalName("smelter")] Smelter, [InternalName("charcoal_kiln")] CharcoalKiln, [InternalName("blastfurnace")] BlastFurnace, [InternalName("windmill")] Windmill, [InternalName("piece_spinningwheel")] SpinningWheel, [InternalName("eitrrefinery")] EitrRefinery, Custom } internal class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [PublicAPI] internal class RequiredResourceList { public readonly List Requirements = new List(); public bool Free; public void Add(string itemName, int amount, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amount = amount, quality = quality }); } public void Add(string itemName, ConfigEntry amountConfig, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amountConfig = amountConfig, quality = quality }); } } [PublicAPI] internal class CraftingStationList { public readonly List Stations = new List(); public void Add(CraftingTable table, int level) { Stations.Add(new CraftingStationConfig { Table = table, level = level }); } public void Add(string customTable, int level) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, level = level, custom = customTable }); } } [PublicAPI] internal class ItemRecipe { public readonly RequiredResourceList RequiredItems = new RequiredResourceList(); public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList(); public readonly CraftingStationList Crafting = new CraftingStationList(); public int CraftAmount = 1; public bool RequireOnlyOneIngredient; public float QualityResultAmountMultiplier = 1f; public ConfigEntryBase? RecipeIsActive; } [PublicAPI] internal class Trade { public Trader Trader; public uint Price; public uint Stack = 1u; public string? RequiredGlobalKey; } [PublicAPI] [Flags] internal enum Trader { None = 0, Haldor = 1, Hildir = 2 } internal struct Requirement { public string itemName; public int amount; public ConfigEntry? amountConfig; [Description("Set to a non-zero value to apply the requirement only for a specific quality")] public int quality; } internal struct CraftingStationConfig { public CraftingTable Table; public int level; public string? custom; } [Flags] internal enum Configurability { Disabled = 0, Recipe = 1, Stats = 2, Drop = 4, Trader = 8, Full = 0xF } [PublicAPI] internal class DropTargets { public readonly List Drops = new List(); public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true) { Drops.Add(new DropTarget { creature = creatureName, chance = chance, min = min, max = (max ?? min), levelMultiplier = levelMultiplier }); } } internal struct DropTarget { public string creature; public int min; public int max; public float chance; public bool levelMultiplier; } internal enum Toggle { On = 1, Off = 0 } [PublicAPI] internal class Item { private class ItemConfig { public ConfigEntry? craft; public ConfigEntry? upgrade; public ConfigEntry table; public ConfigEntry tableLevel; public ConfigEntry customTable; public ConfigEntry? maximumTableLevel; public ConfigEntry requireOneIngredient; public ConfigEntry qualityResultAmountMultiplier; } private class TraderConfig { public ConfigEntry trader; public ConfigEntry price; public ConfigEntry stack; public ConfigEntry requiredGlobalKey; } private class RequirementQuality { public int quality; } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action? CustomDrawer; public Func? browsability; } [PublicAPI] public enum DamageModifier { Normal, Resistant, Weak, Immune, Ignore, VeryResistant, VeryWeak, None } private delegate void setDmgFunc(ref DamageTypes dmg, float value); private class SerializedRequirements { public readonly List Reqs; public SerializedRequirements(List reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) : this(reqs.Split(new char[1] { ',' }).Select(delegate(string r) { string[] array = r.Split(new char[1] { ':' }); int result; int result2; return new Requirement { itemName = array[0], amount = ((array.Length <= 1 || !int.TryParse(array[1], out result)) ? 1 : result), quality = ((array.Length > 2 && int.TryParse(array[2], out result2)) ? result2 : 0) }; }).ToList()) { } public override string ToString() { return string.Join(",", Reqs.Select((Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : ""))); } public static ItemDrop? fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if ((Object)(object)obj == (Object)null) { Debug.LogWarning((object)("The required item '" + name + "' does not exist.")); } return obj; } public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_0194: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown Dictionary dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func)((Requirement r) => r.itemName), (Func)delegate(Requirement r) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown ItemDrop val6 = ResItem(r); return (val6 != null) ? new Requirement { m_amount = (r.amountConfig?.Value ?? r.amount), m_resItem = val6, m_amountPerLevel = 0 } : ((Requirement)null); }); List list = dictionary.Values.Where((Requirement v) => v != null).ToList(); foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != "")) { if (item.quality > 0) { ItemDrop val = ResItem(item); if (val != null) { Requirement val2 = new Requirement { m_resItem = val, m_amountPerLevel = (item.amountConfig?.Value ?? item.amount), m_amount = 0 }; list.Add(val2); requirementQuality.Add(val2, new RequirementQuality { quality = item.quality }); } continue; } if (!dictionary.TryGetValue(item.itemName, out var value) || value == null) { ItemDrop val3 = ResItem(item); if (val3 != null) { string itemName = item.itemName; Requirement val4 = new Requirement { m_resItem = val3, m_amount = 0 }; Requirement val5 = val4; dictionary[itemName] = val4; value = val5; list.Add(value); } } if (value != null) { value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount; } } return list.ToArray(); ItemDrop? ResItem(Requirement r) { return fetchByName(objectDB, r.itemName); } } } private class SerializedDrop { public readonly List Drops; public SerializedDrop(List drops) { Drops = drops; } public SerializedDrop(string drops) { Drops = ((drops == "") ? ((IEnumerable)Array.Empty()) : ((IEnumerable)drops.Split(new char[1] { ',' }))).Select(delegate(string r) { string[] array = r.Split(new char[1] { ':' }); if (array.Length <= 2 || !int.TryParse(array[2], out var result)) { result = 1; } if (array.Length <= 3 || !int.TryParse(array[3], out var result2)) { result2 = result; } bool levelMultiplier = array.Length <= 4 || array[4] != "0"; float result3; return new DropTarget { creature = array[0], chance = ((array.Length > 1 && float.TryParse(array[1], out result3)) ? result3 : 1f), min = result, max = result2, levelMultiplier = levelMultiplier }; }).ToList(); } public override string ToString() { return string.Join(",", Drops.Select((DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0"))); } private static Character? fetchByName(ZNetScene netScene, string name) { GameObject prefab = netScene.GetPrefab(name); Character obj = ((prefab != null) ? prefab.GetComponent() : null); if ((Object)(object)obj == (Object)null) { Debug.LogWarning((object)("The drop target character '" + name + "' does not exist.")); } return obj; } public Dictionary toCharacterDrops(ZNetScene netScene, GameObject item) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown Dictionary dictionary = new Dictionary(); foreach (DropTarget drop in Drops) { Character val = fetchByName(netScene, drop.creature); if (val != null) { dictionary[val] = new Drop { m_prefab = item, m_amountMin = drop.min, m_amountMax = drop.max, m_chance = drop.chance, m_levelMultiplier = drop.levelMultiplier }; } } return dictionary; } } private static readonly List registeredItems = new List(); private static readonly Dictionary itemDropMap = new Dictionary(); private static Dictionary>> activeRecipes = new Dictionary>>(); private static Dictionary hiddenCraftRecipes = new Dictionary(); private static Dictionary hiddenUpgradeRecipes = new Dictionary(); private static Dictionary> itemCraftConfigs = new Dictionary>(); private static Dictionary> itemDropConfigs = new Dictionary>(); private Dictionary characterDrops = new Dictionary(); private readonly Dictionary statsConfigs = new Dictionary(); private static readonly ConditionalWeakTable requirementQuality = new ConditionalWeakTable(); public static Configurability DefaultConfigurability = Configurability.Full; public Configurability? Configurable; private Configurability configurationVisible = Configurability.Full; private TraderConfig? traderConfig; public readonly GameObject Prefab; [Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")] public int MaximumRequiredStationLevel = int.MaxValue; [Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")] public readonly DropTargets DropsFrom = new DropTargets(); [Description("Configures whether the item can be bought at the trader.\nDon't forget to set cost to something above 0 or the item will be sold for free.")] public readonly Trade Trade = new Trade(); internal List Conversions = new List(); internal List conversions = new List(); public Dictionary Recipes = new Dictionary(); private LocalizeKey? _name; private LocalizeKey? _description; private static object? configManager; private static Localization? _english; private static BaseUnityPlugin? _plugin; private static bool hasConfigSync = true; private static object? _configSync; private Configurability configurability => Configurable ?? DefaultConfigurability; [Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")] public RequiredResourceList RequiredItems => this[""].RequiredItems; [Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")] public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems; [Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")] public CraftingStationList Crafting => this[""].Crafting; [Description("Specifies a config entry which toggles whether a recipe is active.")] public ConfigEntryBase? RecipeIsActive { get { return this[""].RecipeIsActive; } set { this[""].RecipeIsActive = value; } } [Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")] public int CraftAmount { get { return this[""].CraftAmount; } set { this[""].CraftAmount = value; } } public bool RequireOnlyOneIngredient { get { return this[""].RequireOnlyOneIngredient; } set { this[""].RequireOnlyOneIngredient = value; } } public float QualityResultAmountMultiplier { get { return this[""].QualityResultAmountMultiplier; } set { this[""].QualityResultAmountMultiplier = value; } } public ItemRecipe this[string name] { get { if (Recipes.TryGetValue(name, out ItemRecipe value)) { return value; } return Recipes[name] = new ItemRecipe(); } } public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } SharedData shared = Prefab.GetComponent().m_itemData.m_shared; if (shared.m_name.StartsWith("$")) { _name = new LocalizeKey(shared.m_name); } else { string text = "$item_" + ((Object)Prefab).name.Replace(" ", "_"); _name = new LocalizeKey(text).English(shared.m_name); shared.m_name = text; } return _name; } } public LocalizeKey Description { get { LocalizeKey description = _description; if (description != null) { return description; } SharedData shared = Prefab.GetComponent().m_itemData.m_shared; if (shared.m_description.StartsWith("$")) { _description = new LocalizeKey(shared.m_description); } else { string text = "$itemdesc_" + ((Object)Prefab).name.Replace(" ", "_"); _description = new LocalizeKey(text).English(shared.m_description); shared.m_description = text; } return _description; } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } private static object? configSync { get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public Item(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public Item(AssetBundle bundle, string prefabName) : this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true) { } public Item(GameObject prefab, bool skipRegistering = false) { if (!skipRegistering) { PrefabManager.RegisterPrefab(prefab, addToObjectDb: true); } Prefab = prefab; registeredItems.Add(this); itemDropMap[Prefab.GetComponent()] = this; Prefab.GetComponent().m_itemData.m_dropPrefab = Prefab; } public void ToggleConfigurationVisibility(Configurability visible) { configurationVisible = visible; if (itemDropConfigs.TryGetValue(this, out ConfigEntry value)) { Toggle((ConfigEntryBase)(object)value, Configurability.Drop); } if (itemCraftConfigs.TryGetValue(this, out Dictionary value2)) { foreach (ItemConfig value4 in value2.Values) { ToggleObj(value4, Configurability.Recipe); } } foreach (Conversion conversion in Conversions) { if (conversion.config != null) { ToggleObj(conversion.config, Configurability.Recipe); } } foreach (KeyValuePair statsConfig in statsConfigs) { Toggle(statsConfig.Key, Configurability.Stats); if ((visible & Configurability.Stats) != Configurability.Disabled) { statsConfig.Value(); } } reloadConfigDisplay(); void Toggle(ConfigEntryBase cfg, Configurability check) { object[] tags = cfg.Description.Tags; for (int i = 0; i < tags.Length; i++) { if (tags[i] is ConfigurationManagerAttributes configurationManagerAttributes) { configurationManagerAttributes.Browsable = (visible & check) != Configurability.Disabled && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability()); } } } void ToggleObj(object obj, Configurability check) { FieldInfo[] fields = obj.GetType().GetFields(); for (int i = 0; i < fields.Length; i++) { object? value3 = fields[i].GetValue(obj); ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null); if (val != null) { Toggle(val, check); } } } } internal static void reloadConfigDisplay() { object obj = configManager?.GetType().GetProperty("DisplayingWindow").GetValue(configManager); if (obj is bool && (bool)obj) { configManager.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty()); } } private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue) { if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out List value)) { value.First().m_enabled = table != CraftingTable.Disabled; if ((uint)table <= 1u) { value.First().m_craftingStation = null; } else if (table == CraftingTable.Custom) { Recipe obj = value.First(); GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue); obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent() : null); } else { value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent(); } } } private void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements) { if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List value)) { return; } foreach (Recipe item in value) { item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements); } } internal static void Patch_FejdStartup() { //IL_0e99: Unknown result type (might be due to invalid IL or missing references) //IL_0e9e: Unknown result type (might be due to invalid IL or missing references) //IL_2164: Unknown result type (might be due to invalid IL or missing references) //IL_216e: Expected O, but got Unknown //IL_0f62: Unknown result type (might be due to invalid IL or missing references) //IL_0f65: Unknown result type (might be due to invalid IL or missing references) //IL_0fbb: Expected I4, but got Unknown //IL_0b88: Unknown result type (might be due to invalid IL or missing references) //IL_0b92: Expected O, but got Unknown //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Expected O, but got Unknown //IL_10ef: Unknown result type (might be due to invalid IL or missing references) //IL_10f2: Unknown result type (might be due to invalid IL or missing references) //IL_10f4: Invalid comparison between Unknown and I4 //IL_10f6: Unknown result type (might be due to invalid IL or missing references) //IL_10fa: Invalid comparison between Unknown and I4 //IL_0cab: Unknown result type (might be due to invalid IL or missing references) //IL_0cb5: Expected O, but got Unknown //IL_0d56: Unknown result type (might be due to invalid IL or missing references) //IL_0d60: Expected O, but got Unknown //IL_10fc: Unknown result type (might be due to invalid IL or missing references) //IL_1100: Invalid comparison between Unknown and I4 //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Expected O, but got Unknown //IL_0e0a: Unknown result type (might be due to invalid IL or missing references) //IL_0e14: Expected O, but got Unknown //IL_12fb: Unknown result type (might be due to invalid IL or missing references) //IL_12fe: Unknown result type (might be due to invalid IL or missing references) //IL_1300: Invalid comparison between Unknown and I4 //IL_1302: Unknown result type (might be due to invalid IL or missing references) //IL_1306: Unknown result type (might be due to invalid IL or missing references) //IL_1308: Invalid comparison between Unknown and I4 //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_0543: Expected O, but got Unknown //IL_130a: Unknown result type (might be due to invalid IL or missing references) //IL_130e: Invalid comparison between Unknown and I4 //IL_13e3: Unknown result type (might be due to invalid IL or missing references) //IL_13e8: Unknown result type (might be due to invalid IL or missing references) //IL_13ea: Unknown result type (might be due to invalid IL or missing references) //IL_13ed: Invalid comparison between Unknown and I4 //IL_13ef: Unknown result type (might be due to invalid IL or missing references) //IL_13f3: Invalid comparison between Unknown and I4 //IL_06f0: Unknown result type (might be due to invalid IL or missing references) //IL_06fa: Expected O, but got Unknown //IL_0651: Unknown result type (might be due to invalid IL or missing references) //IL_065b: Expected O, but got Unknown //IL_1462: Unknown result type (might be due to invalid IL or missing references) //IL_1465: Unknown result type (might be due to invalid IL or missing references) //IL_1467: Invalid comparison between Unknown and I4 //IL_07fa: Unknown result type (might be due to invalid IL or missing references) //IL_0804: Expected O, but got Unknown //IL_1469: Unknown result type (might be due to invalid IL or missing references) //IL_146d: Unknown result type (might be due to invalid IL or missing references) //IL_146f: Invalid comparison between Unknown and I4 //IL_1471: Unknown result type (might be due to invalid IL or missing references) //IL_1475: Invalid comparison between Unknown and I4 //IL_15b2: Unknown result type (might be due to invalid IL or missing references) //IL_15b5: Invalid comparison between Unknown and I4 //IL_17b2: Unknown result type (might be due to invalid IL or missing references) //IL_17b9: Invalid comparison between Unknown and I4 //IL_1882: Unknown result type (might be due to invalid IL or missing references) //IL_1887: Unknown result type (might be due to invalid IL or missing references) //IL_1889: Unknown result type (might be due to invalid IL or missing references) //IL_188d: Unknown result type (might be due to invalid IL or missing references) //IL_188f: Invalid comparison between Unknown and I4 //IL_18fe: Unknown result type (might be due to invalid IL or missing references) //IL_1901: Unknown result type (might be due to invalid IL or missing references) //IL_1903: Invalid comparison between Unknown and I4 //IL_1528: Unknown result type (might be due to invalid IL or missing references) //IL_152d: Unknown result type (might be due to invalid IL or missing references) //IL_1905: Unknown result type (might be due to invalid IL or missing references) //IL_1909: Invalid comparison between Unknown and I4 //IL_190b: Unknown result type (might be due to invalid IL or missing references) //IL_190f: Invalid comparison between Unknown and I4 //IL_1d7c: Unknown result type (might be due to invalid IL or missing references) //IL_1d7f: Invalid comparison between Unknown and I4 Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); if (DefaultConfigurability != Configurability.Disabled) { bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (Item item3 in registeredItems.Where((Item i) => i.configurability != Configurability.Disabled)) { Item item = item3; string name = item.Prefab.GetComponent().m_itemData.m_shared.m_name; string englishName = new Regex("[=\\n\\t\\\\\"\\'\\[\\]]*").Replace(english.Localize(name), "").Trim(); string localizedName = Localization.instance.Localize(name).Trim(); int order = 0; if ((item.configurability & Configurability.Recipe) != Configurability.Disabled) { itemCraftConfigs[item] = new Dictionary(); foreach (string item4 in item.Recipes.Keys.DefaultIfEmpty("")) { string configKey = item4; string text = ((configKey == "") ? "" : (" (" + configKey + ")")); if (!item.Recipes.ContainsKey(configKey) || item.Recipes[configKey].Crafting.Stations.Count <= 0) { continue; } ItemConfig itemConfig = (itemCraftConfigs[item][configKey] = new ItemConfig()); ItemConfig cfg = itemConfig; List hideWhenNoneAttributes = new List(); cfg.table = config(englishName, "Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName } })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = CustomTableBrowsability, Browsable = (CustomTableBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.customTable = config(englishName, "Custom Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes); cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes })); cfg.tableLevel.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { value.First().m_minStationLevel = cfg.tableLevel.Value; } }; if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1) { cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item.MaximumRequiredStationLevel == int.MaxValue) ? (item.Recipes[configKey].Crafting.Stations.First().level + item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality - 1) : item.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes })); } cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Category = localizedName } })); ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = QualityResultBrowsability, Browsable = (QualityResultBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.requireOneIngredient.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item5 in value) { item5.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On; } } qualityResultAttributes.Browsable = QualityResultBrowsability(); reloadConfigDisplay(); }; cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes })); cfg.qualityResultAmountMultiplier.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item6 in value) { item6.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value; } } }; if ((!item.Recipes[configKey].RequiredItems.Free || item.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.craft = itemConfig3("Crafting Costs" + text, new SerializedRequirements(item.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false); } if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1 && (!item.Recipes[configKey].RequiredUpgradeItems.Free || item.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.upgrade = itemConfig3("Upgrading Costs" + text, new SerializedRequirements(item.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName, isUpgrade: true); } if (cfg.craft != null) { cfg.craft.SettingChanged += ConfigChanged; } if (cfg.upgrade != null) { cfg.upgrade.SettingChanged += ConfigChanged; } void ConfigChanged(object o, EventArgs e) { item.UpdateCraftConfig(configKey, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? "")); } bool CustomTableBrowsability() { return cfg.table.Value == CraftingTable.Custom; } bool ItemBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } bool QualityResultBrowsability() { return cfg.requireOneIngredient.Value == Toggle.On; } void TableConfigChanged(object o, EventArgs e) { item.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value); customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item7 in hideWhenNoneAttributes) { item7.Browsable = cfg.table.Value != CraftingTable.Disabled; } reloadConfigDisplay(); } bool TableLevelBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } ConfigEntry itemConfig3(string name2, string value, string desc, bool isUpgrade) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { CustomDrawer = drawRequirementsConfigTable(item, isUpgrade), Order = (order -= 1), browsability = ItemBrowsability, Browsable = (ItemBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes2); return config(englishName, name2, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 })); } } if ((item.configurability & Configurability.Drop) != Configurability.Disabled) { ConfigEntry val = (itemDropConfigs[item] = config(englishName, "Drops from", new SerializedDrop(item.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { CustomDrawer = drawDropsConfigTable, Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Drop) != 0) } }))); val.SettingChanged += delegate { item.UpdateCharacterDrop(); }; } for (int num = 0; num < item.Conversions.Count; num++) { string text2 = ((item.Conversions.Count > 1) ? $"{num + 1}. " : ""); Conversion conversion = item.Conversions[num]; conversion.config = new Conversion.ConversionConfig(); int index = num; conversion.config.input = config(englishName, text2 + "Conversion Input Item", conversion.Input, new ConfigDescription("Input item to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.input.SettingChanged += delegate { if (index < item.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop val3 = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); item.conversions[index].m_from = val3; UpdatePiece(); } } }; conversion.config.piece = config(englishName, text2 + "Conversion Piece", conversion.Piece, new ConfigDescription("Conversion piece used to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.piece.SettingChanged += delegate { UpdatePiece(); }; conversion.config.customPiece = config(englishName, text2 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Custom conversion piece to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.customPiece.SettingChanged += delegate { UpdatePiece(); }; void UpdatePiece() { if (index < item.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance)) { string text3 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value))); string activePiece = conversion.config.activePiece; if (conversion.config.activePiece != null) { int num4 = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent().m_conversion.IndexOf(item.conversions[index]); if (num4 >= 0) { Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val3 in array3) { if (Utils.GetPrefabName(((Component)val3).gameObject) == activePiece) { val3.m_conversion.RemoveAt(num4); } } } conversion.config.activePiece = null; } if (item.conversions[index].m_from != null && conversion.config.piece.Value != ConversionPiece.Disabled) { GameObject prefab = ZNetScene.instance.GetPrefab(text3); if (((prefab != null) ? prefab.GetComponent() : null) != null) { conversion.config.activePiece = text3; Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val4 in array3) { if (Utils.GetPrefabName(((Component)val4).gameObject) == text3) { val4.m_conversion.Add(item.conversions[index]); } } } } } } } } if ((item.configurability & Configurability.Stats) != Configurability.Disabled) { item.statsConfigs.Clear(); SharedData shared = item.Prefab.GetComponent().m_itemData.m_shared; ItemType itemType = shared.m_itemType; statcfg("Weight", "Weight of " + englishName + ".", (SharedData val3) => val3.m_weight, delegate(SharedData val3, float value) { val3.m_weight = value; }); statcfg("Trader Value", "Trader value of " + englishName + ".", (SharedData val3) => val3.m_value, delegate(SharedData val3, int value) { val3.m_value = value; }); bool flag; switch (itemType - 3) { case 0: case 1: case 2: case 3: case 4: case 8: case 9: case 11: case 14: case 16: case 19: flag = true; break; default: flag = false; break; } if (flag) { statcfg("Durability", "Durability of " + englishName + ".", (SharedData val3) => val3.m_maxDurability, delegate(SharedData val3, float value) { val3.m_maxDurability = value; }); statcfg("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData val3) => val3.m_durabilityPerLevel, delegate(SharedData val3, float value) { val3.m_durabilityPerLevel = value; }); statcfg("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData val3) => val3.m_movementModifier, delegate(SharedData val3, float value) { val3.m_movementModifier = value; }); } if ((itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Block Armor", "Block armor of " + englishName + ".", (SharedData val3) => val3.m_blockPower, delegate(SharedData val3, float value) { val3.m_blockPower = value; }); statcfg("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData val3) => val3.m_blockPowerPerLevel, delegate(SharedData val3, float value) { val3.m_blockPowerPerLevel = value; }); statcfg("Block Force", "Block force of " + englishName + ".", (SharedData val3) => val3.m_deflectionForce, delegate(SharedData val3, float value) { val3.m_deflectionForce = value; }); statcfg("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData val3) => val3.m_deflectionForcePerLevel, delegate(SharedData val3, float value) { val3.m_deflectionForcePerLevel = value; }); statcfg("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData val3) => val3.m_timedBlockBonus, delegate(SharedData val3, float value) { val3.m_timedBlockBonus = value; }); } else if ((itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { statcfg("Armor", "Armor of " + englishName + ".", (SharedData val3) => val3.m_armor, delegate(SharedData val3, float value) { val3.m_armor = value; }); statcfg("Armor per Level", "Armor per level for " + englishName + ".", (SharedData val3) => val3.m_armorPerLevel, delegate(SharedData val3, float value) { val3.m_armorPerLevel = value; }); } SkillType skillType = shared.m_skillType; if (((int)skillType == 7 || (int)skillType == 12) ? true : false) { statcfg("Tool tier", "Tool tier of " + englishName + ".", (SharedData val3) => val3.m_toolTier, delegate(SharedData val3, int value) { val3.m_toolTier = value; }); } if ((itemType - 5 <= 2 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { Dictionary modifiers = shared.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier); DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType)); DamageType[] array = new DamageType[5]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); foreach (DamageType damageType in first.Except((IEnumerable)(object)array)) { statcfg(((object)Unsafe.As(ref damageType)/*cast due to .constrained prefix*/).ToString() + " Resistance", ((object)Unsafe.As(ref damageType)/*cast due to .constrained prefix*/).ToString() + " resistance of " + englishName + ".", (SharedData _) => (!modifiers.TryGetValue(damageType, out var value)) ? DamageModifier.None : value, delegate(SharedData val4, DamageModifier value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) DamageModPair val3 = new DamageModPair { m_type = damageType, m_modifier = (DamageModifier)value }; for (int i = 0; i < val4.m_damageModifiers.Count; i++) { if (val4.m_damageModifiers[i].m_type == damageType) { if (value == DamageModifier.None) { val4.m_damageModifiers.RemoveAt(i); } else { val4.m_damageModifiers[i] = val3; } return; } } if (value != DamageModifier.None) { val4.m_damageModifiers.Add(val3); } }); } } if ((int)itemType == 2 && shared.m_food > 0f) { statcfg("Health", "Health value of " + englishName + ".", (SharedData val3) => val3.m_food, delegate(SharedData val3, float value) { val3.m_food = value; }); statcfg("Stamina", "Stamina value of " + englishName + ".", (SharedData val3) => val3.m_foodStamina, delegate(SharedData val3, float value) { val3.m_foodStamina = value; }); statcfg("Eitr", "Eitr value of " + englishName + ".", (SharedData val3) => val3.m_foodEitr, delegate(SharedData val3, float value) { val3.m_foodEitr = value; }); statcfg("Duration", "Duration of " + englishName + ".", (SharedData val3) => val3.m_foodBurnTime, delegate(SharedData val3, float value) { val3.m_foodBurnTime = value; }); statcfg("Health Regen", "Health regen value of " + englishName + ".", (SharedData val3) => val3.m_foodRegen, delegate(SharedData val3, float value) { val3.m_foodRegen = value; }); } if ((int)shared.m_skillType == 10) { statcfg("Health Cost", "Health cost of " + englishName + ".", (SharedData val3) => val3.m_attack.m_attackHealth, delegate(SharedData val3, float value) { val3.m_attack.m_attackHealth = value; }); statcfg("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData val3) => val3.m_attack.m_attackHealthPercentage, delegate(SharedData val3, float value) { val3.m_attack.m_attackHealthPercentage = value; }); } skillType = shared.m_skillType; if (skillType - 9 <= 1) { statcfg("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData val3) => val3.m_attack.m_attackEitr, delegate(SharedData val3, float value) { val3.m_attack.m_attackEitr = value; }); } if ((itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Knockback", "Knockback of " + englishName + ".", (SharedData val3) => val3.m_attackForce, delegate(SharedData val3, float value) { val3.m_attackForce = value; }); statcfg("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData val3) => val3.m_backstabBonus, delegate(SharedData val3, float value) { val3.m_backstabBonus = value; }); statcfg("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData val3) => val3.m_attack.m_attackStamina, delegate(SharedData val3, float value) { val3.m_attack.m_attackStamina = value; }); SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float damage) { dmg.m_damage = damage; }); SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float slash) { dmg.m_slash = slash; }); SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float pierce) { dmg.m_pierce = pierce; }); SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float blunt) { dmg.m_blunt = blunt; }); SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float chop) { dmg.m_chop = chop; }); SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float pickaxe) { dmg.m_pickaxe = pickaxe; }); SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float fire) { dmg.m_fire = fire; }); SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float poison) { dmg.m_poison = poison; }); SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float frost) { dmg.m_frost = frost; }); SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float lightning) { dmg.m_lightning = lightning; }); SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float spirit) { dmg.m_spirit = spirit; }); if ((int)itemType == 4) { statcfg("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData val3) => val3.m_attack.m_projectileBursts, delegate(SharedData val3, int value) { val3.m_attack.m_projectileBursts = value; }); statcfg("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData val3) => val3.m_attack.m_burstInterval, delegate(SharedData val3, float value) { val3.m_attack.m_burstInterval = value; }); statcfg("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData val3) => val3.m_attack.m_projectileAccuracyMin, delegate(SharedData val3, float value) { val3.m_attack.m_projectileAccuracyMin = value; }); statcfg("Accuracy", "Accuracy for " + englishName + ".", (SharedData val3) => val3.m_attack.m_projectileAccuracy, delegate(SharedData val3, float value) { val3.m_attack.m_projectileAccuracy = value; }); statcfg("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData val3) => val3.m_attack.m_projectileVelMin, delegate(SharedData val3, float value) { val3.m_attack.m_projectileVelMin = value; }); statcfg("Velocity", "Velocity for " + englishName + ".", (SharedData val3) => val3.m_attack.m_projectileVel, delegate(SharedData val3, float value) { val3.m_attack.m_projectileVel = value; }); statcfg("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData val3) => val3.m_attack.m_drawDurationMin, delegate(SharedData val3, float value) { val3.m_attack.m_drawDurationMin = value; }); statcfg("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData val3) => val3.m_attack.m_drawStaminaDrain, delegate(SharedData val3, float value) { val3.m_attack.m_drawStaminaDrain = value; }); } } } List traderAttributes; if ((item.configurability & Configurability.Trader) != Configurability.Disabled) { traderAttributes = new List(); item.traderConfig = new TraderConfig { trader = config(englishName, "Trader Selling", item.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Trader) != 0), Category = localizedName } })) }; item.traderConfig.trader.SettingChanged += delegate { item.ReloadTraderConfiguration(); foreach (ConfigurationManagerAttributes item8 in traderAttributes) { item8.Browsable = TraderBrowsability(); } reloadConfigDisplay(); }; item.traderConfig.price = traderConfig("Trader Price", item.Trade.Price, "Price of " + englishName + " at the trader."); item.traderConfig.stack = traderConfig("Trader Stack", item.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction."); item.traderConfig.requiredGlobalKey = traderConfig("Trader Required Global Key", item.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader."); if (item.traderConfig.trader.Value != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.traderConfig.trader.Value, item.traderConfig.price.Value, item.traderConfig.stack.Value, item.traderConfig.requiredGlobalKey.Value); } } else if (item.Trade.Trader != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.Trade.Trader, item.Trade.Price, item.Trade.Stack, item.Trade.RequiredGlobalKey); } void SetDmg(string dmgType, Func readDmg, setDmgFunc setDmg) { statcfg(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData val3) => readDmg(val3.m_damages), delegate(SharedData val3, float value) { setDmg(ref val3.m_damages, value); }); statcfg(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData val3) => readDmg(val3.m_damagesPerLevel), delegate(SharedData val3, float value) { setDmg(ref val3.m_damagesPerLevel, value); }); } bool TraderBrowsability() { return item.traderConfig.trader.Value != Trader.None; } void statcfg(string configName, string description, Func readDefault, Action setValue) where T : notnull { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown SharedData shared2 = item.Prefab.GetComponent().m_itemData.m_shared; ConfigEntry cfg2 = config(englishName, configName, readDefault(shared2), new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Stats) != 0) } })); if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { setValue(shared2, cfg2.Value); } item.statsConfigs.Add((ConfigEntryBase)(object)cfg2, ApplyConfig); cfg2.SettingChanged += delegate { if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { ApplyConfig(); } }; void ApplyConfig() { item.ApplyToAllInstances(delegate(ItemData val3) { setValue(val3.m_shared, cfg2.Value); }); } } ConfigEntry traderConfig(string name2, T value, string desc) where T : notnull { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TraderBrowsability, Browsable = (TraderBrowsability() && (item.configurationVisible & Configurability.Trader) != 0), Category = localizedName }; traderAttributes.Add(configurationManagerAttributes2); ConfigEntry obj = config(englishName, name2, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 })); obj.SettingChanged += delegate { item.ReloadTraderConfiguration(); }; return obj; } } if (saveOnConfigSet) { plugin.Config.SaveOnConfigSet = true; plugin.Config.Save(); } } configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type)); foreach (Item registeredItem in registeredItems) { Item item2 = registeredItem; foreach (KeyValuePair recipe in item2.Recipes) { KeyValuePair kv = recipe; RequiredResourceList[] array2 = new RequiredResourceList[2] { kv.Value.RequiredItems, kv.Value.RequiredUpgradeItems }; foreach (RequiredResourceList requiredResourceList in array2) { for (int num3 = 0; num3 < requiredResourceList.Requirements.Count; num3++) { ConfigEntry amountCfg; int resourceIndex; if ((item2.configurability & Configurability.Recipe) != Configurability.Disabled) { amountCfg = requiredResourceList.Requirements[num3].amountConfig; if (amountCfg != null) { resourceIndex = num3; amountCfg.SettingChanged += ConfigChanged2; } } void ConfigChanged2(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out List value)) { foreach (Recipe item9 in value) { item9.m_resources[resourceIndex].m_amount = amountCfg.Value; } } } } } } item2.InitializeNewRegisteredItem(); } } private void InitializeNewRegisteredItem() { foreach (KeyValuePair recipe in Recipes) { KeyValuePair kv = recipe; ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive; if (enabledCfg != null) { ((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged)); } void ConfigChanged(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out List value)) { foreach (Recipe item in value) { item.m_enabled = (int)enabledCfg.BoxedValue != 0; } } } } } public void ReloadCraftingConfiguration() { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name)) == null) { registerRecipesInObjectDB(ObjectDB.instance); ObjectDB.instance.m_items.Add(Prefab); ObjectDB.instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); ZNetScene.instance.m_prefabs.Add(Prefab); ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); } foreach (string item in Recipes.Keys.DefaultIfEmpty("")) { if (Recipes.TryGetValue(item, out ItemRecipe value) && value.Crafting.Stations.Count > 0) { UpdateItemTableConfig(item, value.Crafting.Stations.First().Table, value.Crafting.Stations.First().custom ?? ""); UpdateCraftConfig(item, new SerializedRequirements(value.RequiredItems.Requirements), new SerializedRequirements(value.RequiredUpgradeItems.Requirements)); } } } private void ReloadTraderConfiguration() { if (traderConfig.trader.Value == Trader.None) { PrefabManager.RemoveItemFromTrader(Prefab); } else { PrefabManager.AddItemToTrader(Prefab, traderConfig.trader.Value, traderConfig.price.Value, traderConfig.stack.Value, traderConfig.requiredGlobalKey.Value); } } public static void ApplyToAllInstances(GameObject prefab, Action callback) { callback(prefab.GetComponent().m_itemData); string name = prefab.GetComponent().m_itemData.m_shared.m_name; Inventory[] source = (from c in Player.s_players.Select((Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType() select c.GetInventory()) where c != null select c).ToArray(); foreach (ItemData item in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent()) select c).Concat(ItemDrop.s_instances) select i.m_itemData).Concat(source.SelectMany((Inventory i) => i.GetAllItems()))) { if (item.m_shared.m_name == name) { callback(item); } } } public void ApplyToAllInstances(Action callback) { ApplyToAllInstances(Prefab, callback); } private static string getInternalName(T value) where T : struct { return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName; } private void registerRecipesInObjectDB(ObjectDB objectDB) { //IL_044e: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_0486: Unknown result type (might be due to invalid IL or missing references) //IL_049c: Expected O, but got Unknown activeRecipes[this] = new Dictionary>(); itemCraftConfigs.TryGetValue(this, out Dictionary value); foreach (KeyValuePair recipe in Recipes) { List list = new List(); foreach (CraftingStationConfig station in recipe.Value.Crafting.Stations) { ItemConfig itemConfig = value?[recipe.Key]; Recipe val = ScriptableObject.CreateInstance(); string name = ((Object)Prefab).name; CraftingTable table = station.Table; ((Object)val).name = name + "_Recipe_" + table; val.m_amount = recipe.Value.CraftAmount; bool enabled; if (itemConfig != null) { enabled = itemConfig.table.Value != CraftingTable.Disabled; } else { ConfigEntryBase? recipeIsActive = recipe.Value.RecipeIsActive; enabled = (int)(((recipeIsActive != null) ? recipeIsActive.BoxedValue : null) ?? ((object)1)) != 0; } val.m_enabled = enabled; val.m_item = Prefab.GetComponent(); val.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value)); table = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value); if ((uint)table <= 1u) { val.m_craftingStation = null; } else if (((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value) == CraftingTable.Custom) { GameObject prefab = ZNetScene.instance.GetPrefab((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value); if (prefab != null) { val.m_craftingStation = prefab.GetComponent(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value) + "' does not exist")); } } else { val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent(); } val.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value); val.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On)); val.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe.Value.QualityResultAmountMultiplier; list.Add(val); RequiredResourceList requiredItems = recipe.Value.RequiredItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenCraftRecipes.Add(val, recipe.Value.RecipeIsActive); } } requiredItems = recipe.Value.RequiredUpgradeItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenUpgradeRecipes.Add(val, recipe.Value.RecipeIsActive); } } } activeRecipes[this].Add(recipe.Key, list); objectDB.m_recipes.AddRange(list); } conversions = new List(); for (int i = 0; i < Conversions.Count; i++) { Conversion conversion = Conversions[i]; conversions.Add(new ItemConversion { m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input), m_to = Prefab.GetComponent() }); ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece; string text = null; if (conversionPiece != ConversionPiece.Disabled && conversions[i].m_from != null) { text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece)); GameObject prefab2 = ZNetScene.instance.GetPrefab(text); Smelter val2 = ((prefab2 != null) ? prefab2.GetComponent() : null); if (val2 != null) { val2.m_conversion.Add(conversions[i]); } else { text = null; } } if (conversion.config != null) { conversion.config.activePiece = text; } } } [HarmonyPriority(0)] internal static void Patch_ObjectDBInit(ObjectDB __instance) { if ((Object)(object)__instance.GetItemPrefab("YagluthDrop") == (Object)null) { return; } hiddenCraftRecipes.Clear(); hiddenUpgradeRecipes.Clear(); foreach (Item registeredItem in registeredItems) { registeredItem.registerRecipesInObjectDB(__instance); } } internal static void Patch_TraderGetAvailableItems(Trader __instance, ref List __result) { string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject); Trader trader = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None)); Trader trader2 = trader; __result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values where (tuple.Item1 & trader2) != 0 select tuple.Item2 into tradeItem where string.IsNullOrEmpty(tradeItem.m_requiredGlobalKey) || ZoneSystem.instance.GetGlobalKey(tradeItem.m_requiredGlobalKey) select tradeItem); } internal static void Patch_OnAddSmelterInput(ItemData item, bool __result) { if (__result) { ((Humanoid)Player.m_localPlayer).UnequipItem(item, true); } } internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality) { if (!itemDropMap.TryGetValue(__instance.m_item, out Item value)) { return; } IEnumerable source; if (!itemCraftConfigs.TryGetValue(value, out Dictionary value2)) { source = Enumerable.Empty(); } else { CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation(); if (currentCraftingStation != null) { string stationName = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject); source = from c in value2.Where(delegate(KeyValuePair c) { switch (c.Value.table.Value) { case CraftingTable.Disabled: case CraftingTable.Inventory: return false; case CraftingTable.Custom: return c.Value.customTable.Value == stationName; default: return getInternalName(c.Value.table.Value) == stationName; } }) select c.Value; } else { source = value2.Values; } } __result = Mathf.Min(Mathf.Max(1, __instance.m_minStationLevel) + (quality - 1), (from cfg in source where cfg.maximumTableLevel != null select cfg.maximumTableLevel.Value).DefaultIfEmpty(value.MaximumRequiredStationLevel).Max()); } internal static void Patch_GetAvailableRecipesPrefix(ref Dictionary>? __state) { if (__state == null) { __state = new Dictionary>(); } Dictionary dictionary; if (InventoryGui.instance.InCraftTab()) { dictionary = hiddenCraftRecipes; } else { if (!InventoryGui.instance.InUpradeTab()) { return; } dictionary = hiddenUpgradeRecipes; } foreach (Recipe key in dictionary.Keys) { key.m_enabled = false; } __state[Assembly.GetExecutingAssembly()] = dictionary; } internal static void Patch_GetAvailableRecipesFinalizer(Dictionary> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out Dictionary value)) { return; } foreach (KeyValuePair item in value) { Recipe key = item.Key; ConfigEntryBase value2 = item.Value; key.m_enabled = (int)(((value2 != null) ? value2.BoxedValue : null) ?? ((object)1)) != 0; } } internal static IEnumerable Transpile_SetupRequirementList(IEnumerable instructionsEnumerable, ILGenerator ilg) { //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Expected O, but got Unknown //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Expected O, but got Unknown //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown List list = instructionsEnumerable.ToList(); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupRequirement", (Type[])null, (Type[])null); CodeInstruction val = null; CodeInstruction val2 = null; LocalBuilder localBuilder = ilg.DeclareLocal(typeof(int)); Dictionary dictionary = new Dictionary(); bool flag = false; int num = 0; int value = 0; Label? label = default(Label?); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo)) { val = list[i + 2]; val2 = list[i + 5]; flag = true; } if (flag) { if (CodeInstructionExtensions.Branches(list[i], ref label) && dictionary.TryGetValue(label.Value, out value)) { num = i; break; } continue; } foreach (Label label4 in list[i].labels) { dictionary[label4] = i; } } if (list[value - 3].opcode == OpCodes.Dup) { return list; } Label label2 = ilg.DefineLabel(); Label label3 = ilg.DefineLabel(); list[num + 1].labels.Add(label2); list.InsertRange(num + 1, (IEnumerable)(object)new CodeInstruction[11] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder), new CodeInstruction(OpCodes.Brfalse, (object)label2), val.Clone(), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.DeclaredField(typeof(InventoryGui), "m_recipeRequirementList")), new CodeInstruction(OpCodes.Ldlen, (object)null), new CodeInstruction(OpCodes.Bgt, (object)label2), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), val2.Clone(), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), new CodeInstruction(OpCodes.Br, (object)label3) }); list.InsertRange(value - 2, (IEnumerable)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Dup, (object)null) { labels = new List