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 AzuEPI; using AzuEPI.Core.Slots; using AzuExtendedPlayerInventory; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BiomeLockAPI; using HarmonyLib; using ItemManager; using JetBrains.Annotations; using LocalizationManager; using Microsoft.CodeAnalysis; using ServerSync; using Splatform; using TMPro; using UnityEngine; using UnityEngine.Audio; using UnityEngine.UI; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Callbacks; 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: Guid("E74EB49A-461D-48EA-85BC-F462D60C98C4")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyProduct("Companions")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] [assembly: AssemblyTitle("Companions")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: AssemblyFileVersion("1.0.5")] [assembly: AssemblyCompany("Radamanto")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.5.0")] [module: <6614e539-fad0-4684-8001-d01a4f520e3d>RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<99995f88-b594-49e7-8035-aef7df1fa491>Embedded] internal sealed class <99995f88-b594-49e7-8035-aef7df1fa491>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<99995f88-b594-49e7-8035-aef7df1fa491>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<99995f88-b594-49e7-8035-aef7df1fa491>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContextAttribute : Attribute { public readonly byte Flag; public <4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [<99995f88-b594-49e7-8035-aef7df1fa491>Embedded] [CompilerGenerated] internal sealed class <6614e539-fad0-4684-8001-d01a4f520e3d>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <6614e539-fad0-4684-8001-d01a4f520e3d>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Companions { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [PublicAPI] public static class MaterialReplacer { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] public enum ShaderType { PieceShader, VegetationShader, RockShader, RugShader, GrassShader, CustomCreature, UseUnityShader } private static readonly Dictionary ObjectToSwap; private static readonly Dictionary OriginalMaterials; private static readonly Dictionary ObjectsForShaderReplace; private static readonly HashSet CachedShaders; private static bool hasRun; static MaterialReplacer() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown CachedShaders = new HashSet(); hasRun = false; OriginalMaterials = new Dictionary(); ObjectToSwap = new Dictionary(); ObjectsForShaderReplace = new Dictionary(); CompanionsPlugin.H.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZoneSystem), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(MaterialReplacer), "ReplaceAllMaterialsWithOriginal", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static void RegisterGameObjectForShaderSwap(GameObject go, ShaderType type) { if (!ObjectsForShaderReplace.ContainsKey(go)) { ObjectsForShaderReplace.Add(go, type); } } public static void RegisterGameObjectForMatSwap(GameObject go, bool isJotunnMock = false) { if (!ObjectToSwap.ContainsKey(go)) { ObjectToSwap.Add(go, isJotunnMock); } } private static void GetAllMaterials() { Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material val in array) { OriginalMaterials[((Object)val).name] = val; } } [HarmonyPriority(700)] private static void ReplaceAllMaterialsWithOriginal() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)SystemInfo.graphicsDeviceType == 4 || hasRun) { return; } if (OriginalMaterials.Count == 0) { GetAllMaterials(); } foreach (KeyValuePair item in ObjectToSwap) { GameObject key = item.Key; bool value = item.Value; ProcessGameObjectMaterials(key, value); } AssetBundle[] array = Resources.FindObjectsOfTypeAll(); AssetBundle[] array2 = array; foreach (AssetBundle val in array2) { IEnumerable enumerable3; try { IEnumerable enumerable2; if (!val.isStreamedSceneAssetBundle) { IEnumerable enumerable = val.LoadAllAssets(); enumerable2 = enumerable; } else { enumerable2 = from shader in ((IEnumerable)val.GetAllAssetNames()).Select((Func)val.LoadAsset) where (Object)(object)shader != (Object)null select shader; } enumerable3 = enumerable2; } catch (Exception) { continue; } if (enumerable3 == null) { continue; } foreach (Shader item2 in enumerable3) { CachedShaders.Add(item2); } } foreach (KeyValuePair item3 in ObjectsForShaderReplace) { GameObject key2 = item3.Key; ShaderType value2 = item3.Value; ProcessGameObjectShaders(key2, value2); } hasRun = true; } private static void ProcessGameObjectMaterials(GameObject go, bool isJotunnMock) { Renderer[] componentsInChildren = go.GetComponentsInChildren(true); Renderer[] array = componentsInChildren; foreach (Renderer val in array) { Material[] sharedMaterials = val.sharedMaterials.Select([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Material material) => ReplaceMaterial(material, isJotunnMock)).ToArray(); val.sharedMaterials = sharedMaterials; } } private static Material ReplaceMaterial(Material originalMaterial, bool isJotunnMock) { string text = (isJotunnMock ? "JVLmock_" : "_REPLACE_"); if (!((Object)originalMaterial).name.StartsWith(text, StringComparison.Ordinal)) { return originalMaterial; } string key = ((Object)originalMaterial).name.Replace(" (Instance)", "").Replace(text, ""); if (OriginalMaterials.TryGetValue(key, out var value)) { return value; } return originalMaterial; } private static void ProcessGameObjectShaders(GameObject go, ShaderType shaderType) { Renderer[] componentsInChildren = go.GetComponentsInChildren(true); Renderer[] array = componentsInChildren; foreach (Renderer val in array) { Material[] sharedMaterials = val.sharedMaterials; foreach (Material val2 in sharedMaterials) { if ((Object)(object)val2 != (Object)null) { val2.shader = GetShaderForType(val2.shader, shaderType, ((Object)val2.shader).name); } } } } private static Shader GetShaderForType(Shader orig, ShaderType shaderType, string originalShaderName) { return (Shader)(shaderType switch { ShaderType.PieceShader => FindShaderWithName(orig, "Custom/Piece"), ShaderType.VegetationShader => FindShaderWithName(orig, "Custom/Vegetation"), ShaderType.RockShader => FindShaderWithName(orig, "Custom/StaticRock"), ShaderType.RugShader => FindShaderWithName(orig, "Custom/Rug"), ShaderType.GrassShader => FindShaderWithName(orig, "Custom/Grass"), ShaderType.CustomCreature => FindShaderWithName(orig, "Custom/Creature"), ShaderType.UseUnityShader => FindShaderWithName(orig, ((Object)(object)FindShaderWithName(orig, originalShaderName) != (Object)null) ? originalShaderName : "ToonDeferredShading2017"), _ => FindShaderWithName(orig, "Standard"), }); } public static Shader FindShaderWithName(Shader origShader, string name) { foreach (Shader cachedShader in CachedShaders) { if (((Object)cachedShader).name == name) { return cachedShader; } } return origShader; } } internal enum CompanionCollectionMode { MarkedItems, AllItems, None } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] public sealed class CompanionCollector : MonoBehaviour { internal const string SelectionKey = "radamanto.companions.collect"; private const float PickableScanInterval = 2f; private const float TrackInterval = 1f; private const float TargetApproachDistance = 3.2f; private const float TargetTimeout = 20f; private const float FailedRetryDelay = 15f; private const int PickablePurgeInterval = 256; private const int MaxOverlapBuffer = 8192; private static readonly HashSet Active = new HashSet(); private static readonly HashSet Pickables = new HashSet(); private static readonly List DeadPickables = new List(); private static readonly Dictionary Templates = new Dictionary(); private static Collider[] _overlapBuffer = (Collider[])(object)new Collider[256]; private static int _itemLayerMask = -1; private static int _pickableRegistrations; private static bool _pickablesSeeded; private readonly HashSet _selectedPrefabs = new HashSet(); private SphereCollider _sensor = null; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private ZNetView _view; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Inventory _inventory; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private CompanionIdentity _identity; private bool _started; private bool _active; private bool _collecting; private bool _scanPending; private float _pollAt = -1f; private float _trackAt = -1f; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private ItemDrop _targetDrop; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Pickable _targetPickable; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private GameObject _targetAnchor; private float _targetStarted; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private ItemDrop _failedDrop; private float _failedUntil; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Pickable _failedPickable; private float _failedPickableUntil; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Player _owner; private int _ownerFrame = -1; private int _selectedFrame = -1; private float _biomeCheckAt; private bool _biomeLocked; internal static bool AnyActive => Active.Count > 0; private static CompanionCollectionMode Mode => CompanionsPlugin.CollectionMode?.Value ?? CompanionCollectionMode.MarkedItems; private static CompanionCollectionMode PickableMode => CompanionsPlugin.PickableMode?.Value ?? CompanionCollectionMode.MarkedItems; private static bool AnyModeEnabled => Mode != CompanionCollectionMode.None || PickableMode != CompanionCollectionMode.None; private static float Radius => Mathf.Clamp(CompanionsPlugin.CollectionRadius?.Value ?? 6f, 1f, 30f); private static float DetectionRadius => Mathf.Clamp(CompanionsPlugin.CollectionDetectionRadius?.Value ?? 50f, 1f, 100f); private static float PickableDetectionRadius => Mathf.Clamp(CompanionsPlugin.PickableDetectionRadius?.Value ?? 20f, 1f, 100f); private static float MaxOwnerDistance => Mathf.Clamp(CompanionsPlugin.CollectionMaxOwnerDistance?.Value ?? 70f, 10f, 150f); private static int ItemLayerMask { get { if (_itemLayerMask == -1) { int mask = LayerMask.GetMask(new string[1] { "item" }); _itemLayerMask = ((mask != 0) ? mask : (-1)); } return _itemLayerMask; } } private bool IsFollowing => (Object)(object)_view != (Object)null && _view.IsValid() && !string.IsNullOrEmpty(_view.GetZDO().GetString(ZDOVars.s_follow, "")); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Player Owner { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] get { if (_ownerFrame != Time.frameCount) { _ownerFrame = Time.frameCount; _owner = (((Object)(object)_view != (Object)null && _view.IsValid()) ? CompanionsState.FindOwner(_view.GetZDO()) : null); } return _owner; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private Transform TargetTransform { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] get { return ((Object)(object)_targetDrop != (Object)null) ? ((Component)_targetDrop).transform : (((Object)(object)_targetPickable != (Object)null) ? ((Component)_targetPickable).transform : null); } } internal static void RegisterPickable(Pickable pickable) { if (_pickablesSeeded && !((Object)(object)pickable == (Object)null)) { Pickables.Add(pickable); if (++_pickableRegistrations % 256 == 0) { PurgeDeadPickables(); } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static void ApplyLayerFilter(Collider trigger) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)trigger == (Object)null)) { int itemLayerMask = ItemLayerMask; trigger.excludeLayers = LayerMask.op_Implicit((itemLayerMask != -1) ? (~itemLayerMask) : 0); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool IsSelected(ItemData item) { return item?.m_customData.ContainsKey("radamanto.companions.collect") ?? false; } internal static void RefreshSensors() { foreach (CompanionCollector item in Active) { item.RefreshSensor(); } } internal static void NotifyNearby(ItemDrop drop) { //IL_002b: 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_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_0061: 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) if ((Object)(object)drop == (Object)null) { return; } float num = Mathf.Max(Radius, DetectionRadius); float num2 = num * num; Vector3 position = ((Component)drop).transform.position; foreach (CompanionCollector item in Active) { if ((Object)(object)item != (Object)null) { Vector3 val = ((Component)item).transform.position - position; if (((Vector3)(ref val)).sqrMagnitude <= num2) { item.ScheduleScan(); } } } } internal static void ResetStatics() { Active.Clear(); ReleasePickables(); Templates.Clear(); } internal void ScheduleScan() { _scanPending = true; } internal void UpdateActive() { if (!_started) { return; } bool flag = (Object)(object)_view != (Object)null && _view.IsValid() && _view.IsOwner(); if (flag == _active) { if (flag) { ScheduleScan(); } return; } _active = flag; if (flag) { Active.Add(this); RefreshSensor(); ScheduleScan(); } else { Deactivate(); } } internal void CancelTarget() { _trackAt = -1f; _targetDrop = null; _targetPickable = null; SetCollecting(collecting: false); } internal bool RestoreTarget(Character character) { if (((Object)(object)_targetDrop == (Object)null && (Object)(object)_targetPickable == (Object)null) || (Object)(object)_targetAnchor == (Object)null) { return false; } if (!IsFollowing || IsOwnerTooFar() || !TargetStillValid()) { CancelTarget(); return false; } UpdateTargetPosition(); CompanionsFlight.FollowCollectionTarget(character, _targetAnchor); return true; } private static void PurgeDeadPickables() { foreach (Pickable pickable in Pickables) { if ((Object)(object)pickable == (Object)null) { DeadPickables.Add(pickable); } } for (int i = 0; i < DeadPickables.Count; i++) { Pickables.Remove(DeadPickables[i]); } DeadPickables.Clear(); } private static void SeedPickables() { if (!_pickablesSeeded) { _pickablesSeeded = true; Pickables.Clear(); Pickable[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (Pickable item in array) { Pickables.Add(item); } } } private static void ReleasePickables() { _pickablesSeeded = false; _pickableRegistrations = 0; Pickables.Clear(); DeadPickables.Clear(); } private static bool IsWardProtected(Vector3 point, long ownerId) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) List allAreas = PrivateArea.m_allAreas; if (allAreas == null) { return false; } foreach (PrivateArea item in allAreas) { if (!((Object)(object)item == (Object)null) && !(Utils.DistanceXZ(((Component)item).transform.position, point) >= item.m_radius)) { ZNetView nview = item.m_nview; Piece piece = item.m_piece; if ((Object)(object)nview != (Object)null && nview.IsValid() && nview.GetZDO().GetBool(ZDOVars.s_enabled, false) && (ownerId == 0L || (Object)(object)piece == (Object)null || piece.GetCreator() != ownerId)) { return true; } } } return false; } private static int OverlapItems(Vector3 position, float radius) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) int num; while (true) { num = Physics.OverlapSphereNonAlloc(position, radius, _overlapBuffer, ItemLayerMask, (QueryTriggerInteraction)2); if (num < _overlapBuffer.Length || _overlapBuffer.Length >= 8192) { break; } _overlapBuffer = (Collider[])(object)new Collider[_overlapBuffer.Length * 2]; } return num; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static ItemData GetTemplate(GameObject prefab) { if ((Object)(object)prefab == (Object)null) { return null; } if (Templates.TryGetValue(prefab, out var value)) { return value; } ItemData val = CreateItem(prefab, 1); if (val != null) { Templates[prefab] = val; } return val; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static ItemData CreateItem(GameObject prefab, int stack) { ItemDrop val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent() : null); if ((Object)(object)val == (Object)null || val.m_itemData == null) { return null; } ItemData val2 = val.m_itemData.Clone(); val2.m_dropPrefab = prefab; val2.m_stack = stack; val2.m_worldLevel = (byte)Game.m_worldLevel; return val2; } private static int HarvestAmount(Pickable pickable) { return pickable.m_dontScale ? pickable.m_amount : Mathf.Max(pickable.m_minAmountScaled, Game.instance.ScaleDrops(pickable.m_itemPrefab, pickable.m_amount)); } private void Start() { //IL_007d: 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_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) _sensor = ((Component)this).GetComponent(); ApplyLayerFilter((Collider)(object)_sensor); _view = ((Component)this).GetComponentInParent(); Container componentInParent = ((Component)this).GetComponentInParent(); _inventory = (((Object)(object)componentInParent != (Object)null) ? componentInParent.GetInventory() : null); if (!((Object)(object)_view == (Object)null) && _inventory != null && !((Object)(object)_sensor == (Object)null)) { Vector3 lossyScale = ((Component)this).transform.parent.lossyScale; ((Component)this).transform.localScale = new Vector3((Mathf.Abs(lossyScale.x) > 0.001f) ? (1f / Mathf.Abs(lossyScale.x)) : 1f, (Mathf.Abs(lossyScale.y) > 0.001f) ? (1f / Mathf.Abs(lossyScale.y)) : 1f, (Mathf.Abs(lossyScale.z) > 0.001f) ? (1f / Mathf.Abs(lossyScale.z)) : 1f); Inventory inventory = _inventory; inventory.m_onChanged = (Action)Delegate.Combine(inventory.m_onChanged, new Action(OnInventoryChanged)); ((Collider)_sensor).enabled = false; _started = true; UpdateActive(); } } private void Update() { if (!_active) { return; } float time = Time.time; if (time >= _biomeCheckAt) { _biomeCheckAt = time + 1f; bool flag = IsOwnerBiomeLocked(); if (flag != _biomeLocked) { _biomeLocked = flag; if (!flag) { ScheduleScan(); } } } if (_trackAt >= 0f && time >= _trackAt) { _trackAt = time + 1f; TrackTarget(); } if (_pollAt >= 0f && time >= _pollAt) { _pollAt = time + 2f; if ((Object)(object)_targetDrop == (Object)null && (Object)(object)_targetPickable == (Object)null) { ScanNearby(); } } if (_scanPending) { _scanPending = false; ScanNearby(); } } private void OnDestroy() { CancelTarget(); if ((Object)(object)_targetAnchor != (Object)null) { Object.Destroy((Object)(object)_targetAnchor); } _targetAnchor = null; if (_active) { _active = false; RemoveActive(); } if (_inventory != null) { Inventory inventory = _inventory; inventory.m_onChanged = (Action)Delegate.Remove(inventory.m_onChanged, new Action(OnInventoryChanged)); } } private void OnTriggerEnter(Collider other) { if (_active) { ItemDrop componentInParent = ((Component)other).GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { ScheduleScan(); } } } private void OnInventoryChanged() { _selectedFrame = -1; if (!_collecting) { ScheduleScan(); } } private void Deactivate() { RemoveActive(); CancelTarget(); _scanPending = false; _pollAt = -1f; if ((Object)(object)_sensor != (Object)null) { ((Collider)_sensor).enabled = false; } } private void RemoveActive() { Active.Remove(this); if (Active.Count == 0) { ReleasePickables(); } } private void RefreshSensor() { if ((Object)(object)_sensor == (Object)null) { return; } _sensor.radius = Mathf.Max(Radius, DetectionRadius); ((Collider)_sensor).enabled = _active && Mode != CompanionCollectionMode.None; _pollAt = ((_active && PickableMode != CompanionCollectionMode.None) ? (Time.time + Random.Range(0.5f, 2f)) : (-1f)); if ((!((Object)(object)_targetDrop != (Object)null) || Mode == CompanionCollectionMode.None) && (!((Object)(object)_targetPickable != (Object)null) || PickableMode == CompanionCollectionMode.None) && ((Object)(object)_targetDrop != (Object)null || (Object)(object)_targetPickable != (Object)null)) { CancelTarget(); if ((Object)(object)_view != (Object)null) { CompanionsFlight.RestoreFollow(((Component)_view).gameObject); } } if (AnyModeEnabled) { ScanNearby(); } } private bool IsOwnerTooFar() { //IL_0017: 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) Player owner = Owner; return (Object)(object)owner == (Object)null || Utils.DistanceXZ(((Component)owner).transform.position, ((Component)this).transform.position) > MaxOwnerDistance; } private bool IsBeyondOwnerRange(Vector3 point) { //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) Player owner = Owner; return owner == null || Utils.DistanceXZ(((Component)owner).transform.position, point) > MaxOwnerDistance; } private void ScanNearby() { if (!_collecting && CanCollect()) { if ((Object)(object)_targetDrop != (Object)null || (Object)(object)_targetPickable != (Object)null) { TrackTarget(); } else if (!IsOwnerTooFar() && !ScanDrops()) { ScanPickables(); } } } private bool ScanDrops() { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) if (Mode == CompanionCollectionMode.None) { return false; } float radius = Mathf.Max(Radius, DetectionRadius); ItemDrop val = null; float num = float.MaxValue; int num2 = OverlapItems(((Component)this).transform.position, radius); for (int i = 0; i < num2; i++) { Collider val2 = _overlapBuffer[i]; _overlapBuffer[i] = null; if ((Object)(object)val2 == (Object)null) { continue; } ItemDrop componentInParent = ((Component)val2).GetComponentInParent(); if (!((Object)(object)componentInParent == (Object)null) && (!((Object)(object)componentInParent == (Object)(object)_failedDrop) || !(Time.time < _failedUntil)) && CanTake(componentInParent, out var _)) { Vector3 val3 = ((Component)this).transform.position - ((Component)componentInParent).transform.position; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; if (sqrMagnitude < num) { val = componentInParent; num = sqrMagnitude; } } } if ((Object)(object)val == (Object)null) { return false; } if (num <= Radius * Radius && TryCollect(val)) { ScheduleScan(); return true; } StartTarget(val, null); return true; } private void ScanPickables() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) if (PickableMode == CompanionCollectionMode.None) { return; } SeedPickables(); if (Pickables.Count == 0) { return; } float num = Mathf.Max(Radius, PickableDetectionRadius); float num2 = num * num; Vector3 position = ((Component)this).transform.position; Pickable val = null; float num3 = float.MaxValue; foreach (Pickable pickable in Pickables) { if ((Object)(object)pickable == (Object)null) { DeadPickables.Add(pickable); continue; } Vector3 val2 = position - ((Component)pickable).transform.position; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (!(sqrMagnitude > num2) && !(sqrMagnitude >= num3) && (!((Object)(object)pickable == (Object)(object)_failedPickable) || !(Time.time < _failedPickableUntil)) && CanHarvest(pickable)) { val = pickable; num3 = sqrMagnitude; } } if (DeadPickables.Count > 0) { for (int i = 0; i < DeadPickables.Count; i++) { Pickables.Remove(DeadPickables[i]); } DeadPickables.Clear(); } if (!((Object)(object)val == (Object)null)) { if (num3 <= Radius * Radius && TryHarvest(val)) { ScheduleScan(); } else { StartTarget(null, val); } } } private bool CanCollect() { return _active && AnyModeEnabled && IsFollowing && (Object)(object)_view != (Object)null && _view.IsValid() && _view.IsOwner() && _inventory != null && !_view.GetZDO().GetBool(CompanionsFlight.DungeonWaitKey, false) && !IsOwnerBiomeLocked(); } private bool IsOwnerBiomeLocked() { Player owner = Owner; if ((Object)(object)owner == (Object)null || (Object)(object)owner != (Object)(object)Player.m_localPlayer) { return false; } return BiomeLockAPI.API.IsRestricted(); } private void SetCollecting(bool collecting) { if ((Object)(object)_identity == (Object)null && (Object)(object)_view != (Object)null) { _identity = ((Component)_view).GetComponent(); } if ((Object)(object)_identity != (Object)null) { _identity.Collecting = collecting; } } private bool TargetStillValid() { int capacity; if ((Object)(object)_targetDrop != (Object)null) { return CanTake(_targetDrop, out capacity); } if ((Object)(object)_targetPickable != (Object)null) { return CanHarvest(_targetPickable); } return false; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private void StartTarget(ItemDrop drop, Pickable pickable) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown if (!IsFollowing || IsOwnerTooFar() || (Object)(object)_view == (Object)null || ((Object)(object)drop == (Object)null && (Object)(object)pickable == (Object)null)) { return; } Character component = ((Component)_view).GetComponent(); if (!((Object)(object)component == (Object)null)) { CancelTarget(); _targetDrop = drop; _targetPickable = pickable; if ((Object)(object)_targetAnchor == (Object)null) { _targetAnchor = new GameObject("CompanionCollectionTarget"); } SetCollecting(collecting: true); _targetStarted = Time.time; UpdateTargetPosition(); CompanionsFlight.FollowCollectionTarget(component, _targetAnchor); _trackAt = Time.time + 1f; } } private void UpdateTargetPosition() { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: 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) Transform targetTransform = TargetTransform; if (!((Object)(object)targetTransform == (Object)null) && !((Object)(object)_targetAnchor == (Object)null) && !((Object)(object)_view == (Object)null)) { Vector3 val = targetTransform.position + Vector3.up * CompanionsFlight.Height; Vector3 val2 = targetTransform.position - ((Component)_view).transform.position; val2.y = 0f; if (((Vector3)(ref val2)).sqrMagnitude > 0.01f) { val += ((Vector3)(ref val2)).normalized * Mathf.Max(0f, 3.2f - Radius); } _targetAnchor.transform.position = val; } } private void TrackTarget() { //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) Transform targetTransform = TargetTransform; if ((Object)(object)targetTransform == (Object)null || (Object)(object)_targetAnchor == (Object)null || !IsFollowing || IsOwnerTooFar() || !TargetStillValid()) { FinishTarget(); } else if (Time.time - _targetStarted > 20f) { if ((Object)(object)_targetDrop != (Object)null) { _failedDrop = _targetDrop; _failedUntil = Time.time + 15f; } else { _failedPickable = _targetPickable; _failedPickableUntil = Time.time + 15f; } FinishTarget(); } else { Vector3 val = ((Component)_view).transform.position - targetTransform.position; if (((Vector3)(ref val)).sqrMagnitude <= Radius * Radius && (((Object)(object)_targetDrop != (Object)null) ? TryCollect(_targetDrop) : TryHarvest(_targetPickable))) { FinishTarget(); } else { UpdateTargetPosition(); } } } private void FinishTarget() { CancelTarget(); ScanNearby(); if ((Object)(object)_targetDrop == (Object)null && (Object)(object)_targetPickable == (Object)null && (Object)(object)_view != (Object)null) { CompanionsFlight.RestoreFollow(((Component)_view).gameObject, smooth: true); ScheduleScan(); } } private bool CanTake(ItemDrop drop, out int capacity) { //IL_005c: 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) capacity = 0; if (Mode == CompanionCollectionMode.None || !CanCollect() || (Object)(object)drop == (Object)null || IsWardProtected(((Component)drop).transform.position, _view.GetZDO().GetLong(CompanionsState.OwnerKey, 0L))) { return false; } if (IsBeyondOwnerRange(((Component)drop).transform.position)) { return false; } ZNetView nview = drop.m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid()) { return false; } drop.Load(); ItemData itemData = drop.m_itemData; if (itemData == null || (Object)(object)itemData.m_dropPrefab == (Object)null || itemData.m_stack <= 0 || !IsOwnDrop(nview.GetZDO(), itemData) || CompanionsContainer.IsBlocked(_inventory, itemData)) { return false; } CompanionCollectionMode mode = Mode; string prefabName = Utils.GetPrefabName(itemData.m_dropPrefab); if (mode == CompanionCollectionMode.MarkedItems && !IsPrefabSelected(prefabName)) { return false; } int num = 0; foreach (ItemData allItem in _inventory.GetAllItems()) { if (allItem.IsSameType(itemData)) { num += Mathf.Max(0, allItem.m_shared.m_maxStackSize - allItem.m_stack); } } int num2 = _inventory.GetEmptySlots() * itemData.m_shared.m_maxStackSize; capacity = num + num2; return (mode == CompanionCollectionMode.MarkedItems) ? (capacity > 0) : (capacity >= itemData.m_stack); } private bool IsOwnDrop(ZDO dropZdo, ItemData item) { //IL_004d: 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) if (!item.m_pickedUp) { return true; } long userID = ((ZDOID)(ref dropZdo.m_uid)).UserID; if (userID == ZDOID.NullUser || userID == ZDOID.UnknownFormerUser) { return true; } Player owner = Owner; int result; if ((Object)(object)owner != (Object)null) { ZDOID zDOID = ((Character)owner).GetZDOID(); result = ((userID == ((ZDOID)(ref zDOID)).UserID) ? 1 : 0); } else { result = 0; } return (byte)result != 0; } private bool IsPrefabSelected(string prefabName) { if (_selectedFrame != Time.frameCount) { _selectedFrame = Time.frameCount; _selectedPrefabs.Clear(); foreach (ItemData allItem in _inventory.GetAllItems()) { if (IsSelected(allItem) && (Object)(object)allItem.m_dropPrefab != (Object)null) { _selectedPrefabs.Add(Utils.GetPrefabName(allItem.m_dropPrefab)); } } } return _selectedPrefabs.Contains(prefabName); } private int FreeCapacity(ItemData item) { return _inventory.FindFreeStackSpace(item.m_shared.m_name, (float)Game.m_worldLevel) + _inventory.GetEmptySlots() * item.m_shared.m_maxStackSize; } private bool CanHarvest(Pickable pickable) { //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) if (PickableMode == CompanionCollectionMode.None || !CanCollect() || (Object)(object)pickable == (Object)null || (Object)(object)pickable.m_itemPrefab == (Object)null) { return false; } ZNetView nview = pickable.m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid() || pickable.GetPicked() || pickable.GetEnabled != 1 || IsControlledByOtherPeer(nview.GetZDO())) { return false; } if (pickable.m_tarPreventsPicking) { Floating component = ((Component)pickable).GetComponent(); if ((Object)(object)component != (Object)null && component.IsInTar()) { return false; } } CompanionCollectionMode pickableMode = PickableMode; if (pickableMode == CompanionCollectionMode.MarkedItems && !IsPrefabSelected(Utils.GetPrefabName(pickable.m_itemPrefab))) { return false; } ItemData template = GetTemplate(pickable.m_itemPrefab); if (template == null || CompanionsContainer.IsBlocked(_inventory, template)) { return false; } Vector3 position = ((Component)pickable).transform.position; if (IsWardProtected(position, _view.GetZDO().GetLong(CompanionsState.OwnerKey, 0L))) { return false; } if (IsBeyondOwnerRange(position)) { return false; } int num = FreeCapacity(template); return (pickableMode == CompanionCollectionMode.MarkedItems) ? (num > 0) : (num >= Mathf.Max(1, pickable.m_amount)); } private static bool IsControlledByOtherPeer(ZDO zdo) { long owner = zdo.GetOwner(); return owner != 0L && owner != ZDOMan.GetSessionID(); } private bool TryHarvest(Pickable pickable) { //IL_0018: 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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_0098: 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) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) if (!_collecting && CanHarvest(pickable)) { Vector3 val = ((Component)this).transform.position - ((Component)pickable).transform.position; if (!(((Vector3)(ref val)).sqrMagnitude > Radius * Radius) && !IsOwnerTooFar()) { ZNetView nview = pickable.m_nview; nview.ClaimOwnership(); if (!nview.IsOwner() || pickable.GetPicked()) { return false; } _collecting = true; try { Vector3 val2 = (pickable.m_pickEffectAtSpawnPoint ? (((Component)pickable).transform.position + pickable.GetSpawnOffset()) : ((Component)pickable).transform.position); pickable.m_pickEffector.Create(val2, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID)); StoreOrDrop(pickable, pickable.m_itemPrefab, HarvestAmount(pickable)); if (!pickable.m_extraDrops.IsEmpty()) { foreach (ItemData dropListItem in pickable.m_extraDrops.GetDropListItems()) { if (dropListItem != null && (Object)(object)dropListItem.m_dropPrefab != (Object)null) { StoreOrDrop(pickable, dropListItem.m_dropPrefab, dropListItem.m_stack); } } } if (pickable.m_aggravateRange > 0f) { BaseAI.AggravateAllInArea(((Component)pickable).transform.position, pickable.m_aggravateRange, (AggravatedReason)2); } nview.InvokeRPC(ZNetView.Everybody, "RPC_SetPicked", new object[1] { true }); return true; } finally { _collecting = false; } } } return false; } private void StoreOrDrop(Pickable pickable, GameObject prefab, int amount) { ItemData template = GetTemplate(prefab); if (template == null || amount <= 0) { return; } bool flag = CompanionsContainer.IsBlocked(_inventory, template); int num = amount; while (!flag && num > 0) { int num2 = Mathf.Min(new int[3] { num, template.m_shared.m_maxStackSize, FreeCapacity(template) }); if (num2 <= 0) { break; } ItemData val = CreateItem(prefab, num2); if (val == null || !_inventory.AddItem(val)) { break; } num -= num2; } int num3 = 0; while (num > 0) { int num4 = Mathf.Min(num, template.m_shared.m_maxStackSize); pickable.Drop(prefab, num3++, num4); num -= num4; } } private bool TryCollect(ItemDrop drop) { //IL_001a: 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_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) if (!_collecting && CanTake(drop, out var capacity)) { Vector3 val = ((Component)this).transform.position - ((Component)drop).transform.position; if (!(((Vector3)(ref val)).sqrMagnitude > Radius * Radius) && !IsOwnerTooFar()) { ZNetView nview = drop.m_nview; if (!drop.CanPickup(false)) { drop.RequestOwn(); return false; } _collecting = true; try { ItemData itemData = drop.m_itemData; ItemData val2 = itemData.Clone(); int num = (val2.m_stack = ((Mode == CompanionCollectionMode.MarkedItems) ? Mathf.Min(itemData.m_stack, capacity) : itemData.m_stack)); val2.m_customData.Remove("radamanto.companions.collect"); bool flag = _inventory.AddItem(val2); if (flag && nview.IsOwner()) { if (num == itemData.m_stack) { nview.Destroy(); } else { itemData.m_stack -= num; ItemDrop.SaveToZDO(itemData, nview.GetZDO(), -1); } } return flag; } finally { _collecting = false; } } } return false; } } [HarmonyPatch(typeof(ItemDrop), "DropItem", new Type[] { typeof(ItemData), typeof(int), typeof(Vector3), typeof(Quaternion) })] internal static class ItemDrop_DropItem_CompanionCollection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ItemDrop __result) { CompanionCollector.NotifyNearby(__result); } } [HarmonyPatch(typeof(Pickable), "Awake")] internal static class Pickable_Awake_CompanionCollection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Pickable __instance) { CompanionCollector.RegisterPickable(__instance); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsCollectionSelection { private const string OverlayName = "CompanionCollectionSelection"; private const string TooltipKeyColor = "#ADFF2F"; private const string TooltipTextColor = "#FFD700"; private static readonly Color SelectedColor = new Color(0.15f, 0.85f, 0.25f, 0.38f); private static readonly HashSet SelectedPrefabs = new HashSet(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Container _container; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Inventory _inventory; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static InventoryGrid _grid; private static bool _normalizing; internal static void Open(InventoryGui gui, Container container) { Close(); if ((Object)(object)gui == (Object)null || (Object)(object)container == (Object)null || !CompanionsContainer.IsCompanionContainer(container) || !CompanionsState.IsOwner((Humanoid)(object)Player.m_localPlayer, CompanionsContainer.GetView((Component)(object)container))) { return; } _container = container; _inventory = container.GetInventory(); _grid = gui.ContainerGrid; if (_inventory == null || (Object)(object)_grid == (Object)null) { Close(); return; } if (_grid.m_elements.Count == 0) { _grid.m_width = 0; _grid.m_height = 0; } NormalizeSelection(); Inventory inventory = _inventory; inventory.m_onChanged = (Action)Delegate.Combine(inventory.m_onChanged, new Action(Refresh)); Refresh(); } internal static void Close() { if (_inventory != null) { Inventory inventory = _inventory; inventory.m_onChanged = (Action)Delegate.Remove(inventory.m_onChanged, new Action(Refresh)); } if ((Object)(object)_grid != (Object)null) { InventoryElement[] componentsInChildren = ((Component)_grid.m_gridRoot).GetComponentsInChildren(true); foreach (InventoryElement element in componentsInChildren) { SetMark(element, selected: false); } } _container = null; _inventory = null; _grid = null; } internal static bool OnLeftDown(InventoryGrid grid, UIInputHandler handler) { //IL_0059: 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)_grid != (Object)(object)grid || (Object)(object)_container == (Object)null || _inventory == null || !CompanionsControls.IsSelectModifierHeld()) { return true; } InventoryElement componentInParent = ((Component)handler).GetComponentInParent(); if ((Object)(object)componentInParent == (Object)null) { return false; } ItemData itemAt = _inventory.GetItemAt(componentInParent.Position.x, componentInParent.Position.y); if (itemAt == null) { return false; } if (!_container.IsOwner()) { return false; } if (CompanionsContainer.IsBlocked(_inventory, itemAt)) { CompanionsContainer.Show("$companions_msg_blocked_item"); return false; } if ((Object)(object)itemAt.m_dropPrefab == (Object)null) { return false; } if (CompanionCollector.IsSelected(itemAt)) { itemAt.m_customData.Remove("radamanto.companions.collect"); } else { string prefabName = Utils.GetPrefabName(itemAt.m_dropPrefab); foreach (ItemData allItem in _inventory.GetAllItems()) { if ((Object)(object)allItem.m_dropPrefab != (Object)null && Utils.GetPrefabName(allItem.m_dropPrefab) == prefabName) { allItem.m_customData.Remove("radamanto.companions.collect"); } } itemAt.m_customData["radamanto.companions.collect"] = "1"; } _inventory.m_onChanged?.Invoke(); return false; } internal static void OnElementInitialized(InventoryElement element) { if ((Object)(object)_grid != (Object)null && (Object)(object)((Component)element).GetComponentInParent() == (Object)(object)_grid) { UpdateMark(element); } } internal static void AppendItemTooltip(InventoryGrid grid, ItemData item, UITooltip tooltip) { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)grid != (Object)(object)_grid) && _inventory != null && item != null && !((Object)(object)tooltip == (Object)null)) { string text = CompanionsLocalization.Localize("$companions_tooltip_click").Replace("{0}", CompanionsControls.SelectModifierLabel); string text2 = CompanionsLocalization.Localize(CompanionCollector.IsSelected(item) ? "$companions_tooltip_deselect_collection" : "$companions_tooltip_select_collection"); string text3 = "" + text2.Replace("{0}", "" + text + "") + ""; tooltip.Set(tooltip.m_topic, tooltip.m_text + "\n\n" + text3, grid.m_tooltipAnchor, default(Vector2)); } } private static bool NormalizeSelection() { if (_inventory == null || _normalizing) { return false; } SelectedPrefabs.Clear(); bool flag = false; foreach (ItemData allItem in _inventory.GetAllItems()) { if (CompanionCollector.IsSelected(allItem) && ((Object)(object)allItem.m_dropPrefab == (Object)null || !SelectedPrefabs.Add(Utils.GetPrefabName(allItem.m_dropPrefab)))) { allItem.m_customData.Remove("radamanto.companions.collect"); flag = true; } } if (!flag) { return false; } _normalizing = true; try { _inventory.m_onChanged?.Invoke(); } finally { _normalizing = false; } return true; } private static void Refresh() { if (!((Object)(object)_grid == (Object)null) && _inventory != null && !NormalizeSelection()) { InventoryElement[] componentsInChildren = ((Component)_grid.m_gridRoot).GetComponentsInChildren(true); foreach (InventoryElement element in componentsInChildren) { UpdateMark(element); } } } private static void UpdateMark(InventoryElement element) { //IL_000e: 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) Inventory inventory = _inventory; ItemData item = ((inventory != null) ? inventory.GetItemAt(element.Position.x, element.Position.y) : null); SetMark(element, CompanionCollector.IsSelected(item)); } private static void SetMark(InventoryElement element, bool selected) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) Transform val = ((Component)element).transform.Find("CompanionCollectionSelection"); if ((Object)(object)val == (Object)null && selected) { GameObject val2 = new GameObject("CompanionCollectionSelection", new Type[2] { typeof(RectTransform), typeof(Image) }); val2.transform.SetParent(((Component)element).transform, false); RectTransform val3 = (RectTransform)val2.transform; val3.anchorMin = Vector2.zero; val3.anchorMax = Vector2.one; val3.offsetMin = Vector2.zero; val3.offsetMax = Vector2.zero; Image component = val2.GetComponent(); ((Graphic)component).color = SelectedColor; ((Graphic)component).raycastTarget = false; val2.transform.SetAsFirstSibling(); val = val2.transform; } if ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(selected); } } } [HarmonyPatch(typeof(InventoryGui), "Show", new Type[] { typeof(Container), typeof(int) })] internal static class InventoryGui_Show_CompanionSelection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(InventoryGui __instance, Container container) { CompanionsCollectionSelection.Open(__instance, container); } } [HarmonyPatch(typeof(InventoryGui), "Hide")] internal static class InventoryGui_Hide_CompanionSelection_Patch { private static void Prefix() { CompanionsCollectionSelection.Close(); } } [HarmonyPatch(typeof(InventoryGui), "CloseContainer")] internal static class InventoryGui_CloseContainer_CompanionSelection_Patch { private static void Prefix() { CompanionsCollectionSelection.Close(); } } [HarmonyPatch(typeof(InventoryGrid), "OnLeftDown", new Type[] { typeof(UIInputHandler) })] internal static class InventoryGrid_OnLeftDown_CompanionSelection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(InventoryGrid __instance, UIInputHandler clickHandler) { return CompanionsCollectionSelection.OnLeftDown(__instance, clickHandler); } } [HarmonyPatch(typeof(InventoryElement), "Initialize", new Type[] { typeof(int), typeof(int) })] internal static class InventoryElement_Initialize_CompanionSelection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(InventoryElement __instance) { CompanionsCollectionSelection.OnElementInitialized(__instance); } } [HarmonyPatch(typeof(InventoryGrid), "CreateItemTooltip", new Type[] { typeof(ItemData), typeof(UITooltip) })] internal static class InventoryGrid_CreateItemTooltip_CompanionSelection_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(InventoryGrid __instance, ItemData item, UITooltip tooltip) { CompanionsCollectionSelection.AppendItemTooltip(__instance, item, tooltip); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsAudio { private static readonly HashSet Sources = new HashSet(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static AudioMixer _appliedMixer; internal static void Initialize(AssetBundle bundle) { if (Application.isBatchMode || (Object)(object)bundle == (Object)null) { return; } Sources.Clear(); GameObject[] array = bundle.LoadAllAssets(); foreach (GameObject val in array) { if ((Object)(object)val == (Object)null) { continue; } AudioSource[] componentsInChildren = val.GetComponentsInChildren(true); foreach (AudioSource val2 in componentsInChildren) { if ((Object)(object)val2 != (Object)null) { Sources.Add(val2); } } } Apply(AudioMan.instance); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static void Apply(AudioMan audioManager) { AudioMixer val = (((Object)(object)audioManager != (Object)null) ? audioManager.m_masterMixer : null); if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)_appliedMixer) { return; } AudioMixerGroup val2 = FindSfx(val); if ((Object)(object)val2 == (Object)null) { return; } foreach (AudioSource source in Sources) { if ((Object)(object)source != (Object)null) { source.outputAudioMixerGroup = val2; } } _appliedMixer = val; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static AudioMixerGroup FindSfx(AudioMixer mixer) { AudioMixerGroup[] array = mixer.FindMatchingGroups(string.Empty); foreach (AudioMixerGroup val in array) { if ((Object)(object)val != (Object)null && string.Equals(((Object)val).name, "SFX", StringComparison.OrdinalIgnoreCase)) { return val; } } return null; } } [HarmonyPatch(typeof(AudioMan), "Awake")] internal static class AudioMan_Awake_CompanionAudio_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(AudioMan __instance) { CompanionsAudio.Apply(__instance); } } internal static class CompanionsDefaults { internal const CompanionCollectionMode CollectionMode = CompanionCollectionMode.MarkedItems; internal const float PickupRadius = 6f; internal const float MinPickupRadius = 1f; internal const float MaxPickupRadius = 30f; internal const float DropDetectionRadius = 50f; internal const float PickableDetectionRadius = 20f; internal const float MinDetectionRadius = 1f; internal const float MaxDetectionRadius = 100f; internal const float MaxOwnerDistance = 70f; internal const float MinOwnerDistance = 10f; internal const float MaxMaxOwnerDistance = 150f; internal const bool TeleportCompanion = true; internal const bool WaitAtDungeonEntrance = false; internal const bool CatchUpTeleport = true; internal const float CatchUpDistance = 80f; internal const bool ShowMapIcon = true; internal const CompanionSelectModifier SelectModifier = CompanionSelectModifier.Alt; internal static readonly KeyboardShortcut CallKey = new KeyboardShortcut((KeyCode)104, Array.Empty()); internal static readonly KeyboardShortcut FollowStayKey = new KeyboardShortcut((KeyCode)101, Array.Empty()); internal static readonly KeyboardShortcut OpenChestKey = new KeyboardShortcut((KeyCode)101, (KeyCode[])(object)new KeyCode[1] { (KeyCode)304 }); } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionTokens { internal const string SlotName = "$companions_slot_name"; internal const string ChestName = "$companions_chest_name"; internal const string CargoName = "$companions_cargo_name"; internal const string HoverFollowStay = "$companions_hover_follow_stay"; internal const string HoverOpenChest = "$companions_hover_open_chest"; internal const string HoverCall = "$companions_hover_call"; internal const string TooltipClick = "$companions_tooltip_click"; internal const string TooltipSelectCollection = "$companions_tooltip_select_collection"; internal const string TooltipDeselectCollection = "$companions_tooltip_deselect_collection"; internal const string PopupTitle = "$companions_popup_title"; internal const string PopupDiscard = "$companions_popup_discard"; internal const string MsgPopupUnavailable = "$companions_msg_popup_unavailable"; internal const string MsgBlockedItem = "$companions_msg_blocked_item"; internal const string MsgOwnerOpen = "$companions_msg_owner_open"; internal const string MsgOwnerTakeAll = "$companions_msg_owner_take_all"; internal const string MsgUnequipFirst = "$companions_msg_unequip_first"; internal const string MsgWaitingAtEntrance = "$companions_msg_waiting_at_entrance"; internal const string MsgCalled = "$companions_msg_called"; internal const string MsgServerUnavailable = "$companions_msg_server_unavailable"; internal const string MsgServerNotResponding = "$companions_msg_server_not_responding"; } internal static class CompanionsLocalization { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static string Localize(string token) { if (Localization.instance == null) { return token; } string text = Localization.instance.Localize(token); return string.IsNullOrEmpty(text) ? token : text; } } [BepInPlugin("radamanto.Companions", "Companions", "1.0.5")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] public class CompanionsPlugin : BaseUnityPlugin { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private sealed class ConfigurationManagerAttributes { public bool? Browsable; } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public const string PluginId = "radamanto.Companions"; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public const string PluginName = "Companions"; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public const string PluginVersion = "1.0.5"; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] internal static readonly Harmony H = new Harmony("radamanto.Companions"); internal static ConfigEntry FlightHeight; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] internal static ConfigEntry BlockedItems; internal static ConfigEntry TeleportCompanion; internal static ConfigEntry WaitAtDungeonEntrance; internal static ConfigEntry CatchUpTeleport; internal static ConfigEntry CatchUpDistance; internal static ConfigEntry ShowMapIcon; internal static ConfigEntry CollectionMode; internal static ConfigEntry CollectionRadius; internal static ConfigEntry CollectionDetectionRadius; internal static ConfigEntry CollectionMaxOwnerDistance; internal static ConfigEntry PickableMode; internal static ConfigEntry PickableDetectionRadius; internal static ConfigEntry CallKey; internal static ConfigEntry FollowStayKey; internal static ConfigEntry OpenChestKey; internal static ConfigEntry SelectModifier; private static bool _bootstrapped; private bool _ownsBootstrap; private const float ConfigReloadDelay = 0.5f; internal static ConfigSync ConfigSync; private FileSystemWatcher _configWatcher; private bool _reloadInProgress; private float _reloadAt = -1f; private void Awake() { if (_bootstrapped) { return; } if (!CompanionsAssets.LoadBundle(out var error)) { ((BaseUnityPlugin)this).Logger.LogError((object)error); return; } Localizer.Load(); _ownsBootstrap = true; bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; try { SetupServerSync(); BindConfiguration(); CompanionsAssets.Register(); CompanionsAudio.Initialize(CompanionsAssets.Bundle); H.PatchAll(); CompanionsInvoker.Initialize(); _bootstrapped = true; } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } ((BaseUnityPlugin)this).Config.Save(); SetupConfigWatcher(); } private void OnDestroy() { if (_ownsBootstrap) { CompanionsInvoker.Unregister(); CompanionsNetwork.Unregister(); H.UnpatchSelf(); DisposeConfigWatcher(); ClearStaticState(); _bootstrapped = false; } } private static void ClearStaticState() { CompanionsInvoker.Reset(); CompanionsNetwork.Reset(); CompanionsTracker.Reset(); CompanionsCatchUp.Reset(); CompanionsTeleport.Reset(); CompanionsCollectionSelection.Close(); CompanionsMapIcons.Clear(); CompanionsControls.InvalidateLabels(); CompanionCollector.ResetStatics(); } private void BindConfiguration() { //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) FlightHeight = Cfg("02 - Flight", "02.01 - Flight Height", 1f, "Companion flight height in meters."); BlockedItems = Cfg("03 - Companion Container", "03.01 - Blocked Items", "BlackMetal, BlackMetalScrap, Bronze, BronzeScrap, CharredCogwheel, Copper, CopperOre, CopperScrap, DragonEgg, DvergrNeedle, Flametal, FlametalNew, FlametalOre, FlametalOreNew, Gold, GoldOre, Iron, IronOre, Ironpit, IronScrap, MechanicalSpring, Silver, SilverOre, Tin, TinOre", "Comma-separated prefab names, item tokens, or localized names that companions cannot carry. Vanilla ores are preconfigured."); BindContainerConfiguration(); TeleportCompanion = Cfg("04 - Teleport", "04.01 - Follow Through Portals", defaultValue: true, "If true, companions follow their owner through portals and other game teleports. Dungeon entrances are controlled only by 04.02."); WaitAtDungeonEntrance = Cfg("04 - Teleport", "04.02 - Wait At Dungeon Entrance", defaultValue: false, "If true, companions wait at the dungeon entrance while you are inside and rejoin you when you leave. While waiting they do nothing else. If false, they follow you inside. Independent of 04.01."); CatchUpTeleport = Cfg("04 - Teleport", "04.03 - Catch Up Teleport", defaultValue: true, "If true, a following companion that falls too far behind reappears next to its owner with its spawn effect. Companions left behind by a portal while 04.01 is off are not pulled; they resume following once you come back near them."); CatchUpDistance = Cfg("04 - Teleport", "04.04 - Catch Up Distance", 80f, "Distance in meters from the owner that triggers the catch-up teleport, from 20 to 300. Keep it above 07.02 Max Owner Distance so collecting companions are not pulled back.", (AcceptableValueBase)(object)new AcceptableValueRange(20f, 300f)); CollectionMode = Cfg("05 - Collection Dropped", "05.01 - Mode", CompanionCollectionMode.MarkedItems, "Collection of dropped items (items lying on the ground). MarkedItems collects every item type selected in the companion chest into matching stacks and empty chest slots. Select with the key in 07.06 + left-click; doing it on another stack of the same type moves the selection. AllItems collects any allowed ground item. None disables it. Items dropped by other players are never collected."); CollectionDetectionRadius = Cfg("05 - Collection Dropped", "05.02 - Detection Radius", 50f, "Radius in meters for finding dropped items while following, from 1 to 100.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 100f)); PickableMode = Cfg("06 - Collection Pickables", "06.01 - Mode", CompanionCollectionMode.MarkedItems, "Harvesting of pickables such as raspberries, blueberries, mushrooms, thistle, flint and branches. MarkedItems harvests only pickables whose item is selected in the companion chest (same selection used for dropped items). AllItems harvests any pickable whose item is allowed. None disables it. The yield goes straight into the chest; what is blocked or does not fit drops on the ground. Never inside other players' wards."); PickableDetectionRadius = Cfg("06 - Collection Pickables", "06.02 - Detection Radius", 20f, "Radius in meters for finding pickables while following, from 1 to 100. Usually smaller than 05.02, so the companion only harvests what is close to you.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 100f)); CollectionRadius = Cfg("07 - Companion Control", "07.01 - Pickup Radius", 6f, "Distance in meters at which the companion picks up dropped items and harvests pickables, from 1 to 30. A staying companion only collects within this radius.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 30f)); CollectionMaxOwnerDistance = Cfg("07 - Companion Control", "07.02 - Max Owner Distance", 70f, "A following companion stops collecting and returns to you beyond this distance in meters, from 10 to 150.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 150f)); CallKey = Cfg("07 - Companion Control", "07.03 - Call Key", CompanionsDefaults.CallKey, "Calls your loaded companions from any distance: whether following, staying or collecting, each one comes next to you and stays there. A companion waiting at a dungeon entrance is left as it is. Set to None to disable.", null, synced: false); FollowStayKey = Cfg("07 - Companion Control", "07.04 - Follow Stay Key", CompanionsDefaults.FollowStayKey, "Key pressed while looking at your companion up close to toggle follow / stay. Set to None to disable. Gamepads keep the game's interact button.", null, synced: false); OpenChestKey = Cfg("07 - Companion Control", "07.05 - Open Chest Key", CompanionsDefaults.OpenChestKey, "Key pressed while looking at your companion up close to open its chest. Set to None to disable. Gamepads keep the game's alternate interact.", null, synced: false); SelectModifier = Cfg("07 - Companion Control", "07.06 - Select For Collection Key", CompanionSelectModifier.Alt, "Hold this key and left-click an item in the companion chest to select or clear it for collection (dropped items and pickables).", null, synced: false); ShowMapIcon = Cfg("08 - Map", "08.01 - Show Map Icon", defaultValue: true, "If true, your companions are shown on the minimap and the large map, at any distance."); FlightHeight.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionsFlight.RefreshHeight(); }; CallKey.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionsControls.InvalidateLabels(); }; FollowStayKey.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionsControls.InvalidateLabels(); }; OpenChestKey.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionsControls.InvalidateLabels(); }; BlockedItems.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionsContainer.ReloadBlocklist(BlockedItems.Value); }; CollectionMode.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; CollectionRadius.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; CollectionDetectionRadius.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; CollectionMaxOwnerDistance.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; PickableMode.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; PickableDetectionRadius.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { CompanionCollector.RefreshSensors(); }; CompanionsContainer.ReloadBlocklist(BlockedItems.Value); } private void BindContainerConfiguration() { Dictionary english = LoadEnglishTexts(); CompanionDefinition[] all = CompanionsRegistry.All; foreach (CompanionDefinition definition in all) { string englishName = GetEnglishName(english, definition.CompanionNameToken, "Companion " + definition.Id); string section = "03." + definition.Id + " - " + englishName + " Container"; ConfigEntry width = Cfg(section, "01 - Width", definition.DefaultContainerWidth, "Container width for the " + englishName + ", from 1 to 8.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 8)); ConfigEntry height = Cfg(section, "02 - Height", definition.DefaultContainerHeight, "Container height for the " + englishName + ", from 1 to 8.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 8)); definition.ContainerWidth = width.Value; definition.ContainerHeight = height.Value; width.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { definition.ContainerWidth = width.Value; }; height.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { definition.ContainerHeight = height.Value; }; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private Dictionary LoadEnglishTexts() { try { byte[] array = Localizer.ReadEmbeddedFileBytes("translations.English.yml", typeof(CompanionsPlugin).Assembly); if (array == null) { return new Dictionary(); } string input = Encoding.UTF8.GetString(array).TrimStart(new char[1] { '\ufeff' }); return new DeserializerBuilder().Build().Deserialize>(input) ?? new Dictionary(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("English translations could not be read: " + ex.Message)); return new Dictionary(); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static string GetEnglishName(Dictionary english, string token, string fallback) { string key = (token.StartsWith("$") ? token.Substring(1) : token); if (!english.TryGetValue(key, out var value) || string.IsNullOrWhiteSpace(value)) { return fallback; } string text = Regex.Replace(value, "[=\\n\\t\\\\\"\\'\\[\\]]*", string.Empty).Trim(); return (text.Length > 0) ? text : fallback; } private void Update() { if (!(_reloadAt < 0f) && !(Time.realtimeSinceStartup < _reloadAt)) { _reloadAt = -1f; ReloadConfig(); } } private void SetupServerSync() { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown ConfigSync = new ConfigSync(((BaseUnityPlugin)this).Info.Metadata.GUID) { DisplayName = ((BaseUnityPlugin)this).Info.Metadata.Name, CurrentVersion = ((BaseUnityPlugin)this).Info.Metadata.Version.ToString(), MinimumRequiredVersion = ((BaseUnityPlugin)this).Info.Metadata.Version.ToString(), ModRequired = true }; ConfigEntry lockingConfig = ((BaseUnityPlugin)this).Config.Bind("01 - General", "Lock Configuration", true, new ConfigDescription("If true, the server locks synchronized configuration values.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Browsable = false } })); ConfigSync.AddLockingConfigEntry(lockingConfig); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private ConfigEntry Cfg<[<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] T>(string section, string key, T defaultValue, string description, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] AcceptableValueBase acceptableValues = null, bool synced = true) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected O, but got Unknown if (ConfigSync == null) { throw new InvalidOperationException("ServerSync has not been initialized."); } ConfigDescription val = new ConfigDescription(description + (synced ? " [Synced with Server]" : " [Not Synced with Server]"), acceptableValues, Array.Empty()); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(section, key, defaultValue, val); ConfigSync.AddConfigEntry(val2).SynchronizedConfig = synced; return val2; } private void SetupConfigWatcher() { try { _configWatcher?.Dispose(); _configWatcher = new FileSystemWatcher(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath)) { IncludeSubdirectories = false, NotifyFilter = (NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite), SynchronizingObject = ThreadingHelper.SynchronizingObject }; FileSystemEventHandler value = [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, FileSystemEventArgs _) => { ScheduleConfigReload(); }; _configWatcher.Changed += value; _configWatcher.Created += value; _configWatcher.Renamed += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, RenamedEventArgs _) => { ScheduleConfigReload(); }; _configWatcher.EnableRaisingEvents = true; } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Config file watcher disabled: " + ex.Message)); _configWatcher?.Dispose(); _configWatcher = null; } } private void ScheduleConfigReload() { if (!((Behaviour)this).isActiveAndEnabled) { ReloadConfig(); } else { _reloadAt = Time.realtimeSinceStartup + 0.5f; } } private void ReloadConfig() { if (_reloadInProgress) { return; } bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; try { _reloadInProgress = true; if (_configWatcher != null) { _configWatcher.EnableRaisingEvents = false; } ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; ((BaseUnityPlugin)this).Config.Reload(); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogError((object)("Failed to reload configuration: " + ex)); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; _reloadInProgress = false; if (_configWatcher != null) { _configWatcher.EnableRaisingEvents = true; } } } private void DisposeConfigWatcher() { _reloadAt = -1f; if (_configWatcher != null) { _configWatcher.EnableRaisingEvents = false; _configWatcher.Dispose(); _configWatcher = null; } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsContainer { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private sealed class InventoryMarker { } internal const string DefaultBlockedOres = "BlackMetal, BlackMetalScrap, Bronze, BronzeScrap, CharredCogwheel, Copper, CopperOre, CopperScrap, DragonEgg, DvergrNeedle, Flametal, FlametalNew, FlametalOre, FlametalOreNew, Gold, GoldOre, Iron, IronOre, Ironpit, IronScrap, MechanicalSpring, Silver, SilverOre, Tin, TinOre"; internal const string OpenResponseRpc = "RPC_OpenResponse"; internal const string TakeAllResponseRpc = "RPC_TakeAllResponse"; private const float MessageRepeatDelay = 1f; internal static readonly int CargoOwnerKey = StringExtensionMethods.GetStableHashCode("comp.cargoOwner"); internal static readonly int CargoOwnerPlatformKey = StringExtensionMethods.GetStableHashCode("comp.cargoOwnerPlatform"); private static readonly HashSet Blocked = new HashSet(StringComparer.OrdinalIgnoreCase); private static readonly ConditionalWeakTable Inventories = new ConditionalWeakTable(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static string _lastMessageToken; private static float _lastMessageTime = float.MinValue; private static int _loadingDepth; internal static void ReloadBlocklist(string value) { Blocked.Clear(); string[] array = (value ?? string.Empty).Split(new char[5] { ',', ';', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length > 0) { Blocked.Add(text); } } } internal static void BeginLoad() { _loadingDepth++; } internal static void EndLoad() { _loadingDepth--; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal static ZNetView GetView(Component component) { return ((Object)(object)component != (Object)null) ? (component.GetComponentInParent() ?? component.GetComponent()) : null; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal static Container FindContainer(Component component) { if ((Object)(object)component == (Object)null) { return null; } Container val = component.GetComponent(); if ((Object)(object)val == (Object)null) { val = component.GetComponentInParent(); } if ((Object)(object)val == (Object)null) { val = component.GetComponentInChildren(); } return val; } internal static bool IsCompanionContainer(Container container) { if ((Object)(object)container == (Object)null) { return false; } Character componentInParent = ((Component)container).GetComponentInParent(); return (Object)(object)componentInParent != (Object)null && CompanionsState.IsCompanion(((Component)componentInParent).gameObject); } internal static bool CanAccess(Humanoid character, Container container) { return IsCompanionContainer(container) ? CompanionsState.IsOwner(character, GetView((Component)(object)container)) : IsCargoOwner(character, container); } internal static bool AllowsRequest(Container container, long playerId) { ZNetView nview = container.m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid() || !nview.IsOwner()) { return true; } ZDO zDO = nview.GetZDO(); if (IsCompanionContainer(container)) { long num = zDO.GetLong(CompanionsState.OwnerKey, 0L); return num != 0L && num == playerId; } long num2 = zDO.GetLong(CargoOwnerKey, 0L); return num2 == 0L || num2 == playerId; } internal static void RefreshOwnerPlatform(Humanoid character, Container container) { Player val = (Player)(object)((character is Player) ? character : null); if (val != null) { ZNetView view = GetView((Component)(object)container); if (!((Object)(object)view == (Object)null) && view.IsValid()) { bool flag = IsCompanionContainer(container); CompanionsState.RefreshPlatform(view.GetZDO(), flag ? CompanionsState.OwnerKey : CargoOwnerKey, flag ? CompanionsState.OwnerPlatformKey : CargoOwnerPlatformKey, val.GetPlayerID(), CompanionsState.GetPlatformId(val)); } } } internal static void Register(Container container) { Inventory val = (((Object)(object)container != (Object)null) ? container.GetInventory() : null); if (val != null && !Inventories.TryGetValue(val, out var _)) { Inventories.Add(val, new InventoryMarker()); } } internal static void ApplySize(Container container, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] CompanionDefinition definition = null) { if ((Object)(object)container == (Object)null) { return; } ZDO val = null; if (definition == null) { GameObject gameObject = ((Component)((Component)container).transform.root).gameObject; CompanionIdentity companionIdentity = default(CompanionIdentity); if (!gameObject.TryGetComponent(ref companionIdentity)) { return; } definition = CompanionsRegistry.ForCompanion(Utils.GetPrefabName(gameObject)); ZNetView view = GetView((Component)(object)container); val = (((Object)(object)view != (Object)null) ? view.GetZDO() : null); } if (definition != null) { int width = definition.ContainerWidth; int height = definition.ContainerHeight; if (val != null) { FitStoredItems(val, ref width, ref height); } container.m_width = width; container.m_height = height; } } internal static void EnsureCapacity(Container container) { if ((Object)(object)container == (Object)null) { return; } Inventory inventory = container.m_inventory; ZNetView nview = container.m_nview; if (inventory == null || (Object)(object)nview == (Object)null || !nview.IsValid() || !Inventories.TryGetValue(inventory, out var _)) { return; } ZDO zDO = nview.GetZDO(); if (zDO.DataRevision != container.m_lastRevision && !container.m_inUse) { int width = inventory.m_width; int height = inventory.m_height; if (FitStoredItems(zDO, ref width, ref height)) { inventory.m_width = width; inventory.m_height = height; container.m_width = width; container.m_height = height; } } } internal static bool WouldSwap([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] ItemData itemAt, ItemData item, int amount) { return itemAt != null && itemAt != item && item.m_stack == amount && (itemAt.m_shared.m_name != item.m_shared.m_name || (item.m_shared.m_maxQuality > 1 && itemAt.m_quality != item.m_quality) || itemAt.m_shared.m_maxStackSize == 1); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool BlocksDrop(Inventory target, Inventory from, ItemData item, int amount, Vector2i position) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (target == null || from == null || item == null) { return false; } if (IsBlocked(target, item)) { return true; } ItemData itemAt = target.GetItemAt(position.x, position.y); return WouldSwap(itemAt, item, amount) && IsBlocked(from, itemAt); } internal static bool IsBlocked(Inventory inventory, ItemData item) { if (inventory == null || item == null || !Inventories.TryGetValue(inventory, out var _)) { return false; } if (CompanionsRegistry.ForInvoker(item) != null) { return true; } if (Blocked.Count == 0) { return false; } string text = (((Object)(object)item.m_dropPrefab != (Object)null) ? Utils.GetPrefabName(item.m_dropPrefab) : string.Empty); if (text.Length > 0 && Blocked.Contains(text)) { return true; } string text2 = ((item.m_shared != null) ? item.m_shared.m_name : string.Empty); if (text2.Length == 0) { return false; } if (Blocked.Contains(text2)) { return true; } if (text2[0] == '$' && Blocked.Contains(text2.Substring(1))) { return true; } if (Localization.instance == null) { return false; } string text3 = Localization.instance.Localize(text2); if (string.IsNullOrEmpty(text3)) { return false; } string item2 = text3.Replace("", string.Empty).Replace("", string.Empty).Replace("", string.Empty) .Replace("", string.Empty) .Trim(); return Blocked.Contains(text3) || Blocked.Contains(item2); } internal static bool AllowAdd(Inventory inventory, ItemData item, ref bool result) { if (_loadingDepth > 0 || !IsBlocked(inventory, item)) { return true; } result = false; Show("$companions_msg_blocked_item"); return false; } internal static void Show(string token) { if (!(token == _lastMessageToken) || !(Time.time - _lastMessageTime < 1f)) { MessageHud instance = MessageHud.instance; if (!((Object)(object)instance == (Object)null)) { _lastMessageToken = token; _lastMessageTime = Time.time; instance.ShowMessage((MessageType)2, CompanionsLocalization.Localize(token), 0, (Sprite)null, false, true); } } } private static bool IsCargoOwner(Humanoid character, Container container) { ZNetView view = GetView((Component)(object)container); if ((Object)(object)view == (Object)null || !view.IsValid()) { return true; } ZDO zDO = view.GetZDO(); if (zDO.GetLong(CargoOwnerKey, 0L) == 0) { return true; } Player val = (Player)(object)((character is Player) ? character : null); return val != null && CompanionsState.MatchesOwner(zDO, CargoOwnerKey, CargoOwnerPlatformKey, val.GetPlayerID(), CompanionsState.GetPlatformId(val)); } private static bool FitStoredItems(ZDO zdo, ref int width, ref int height) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown //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_0067: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray == null || byteArray.Length == 0) { return false; } Inventory val = new Inventory(true); try { val.Load(new ZPackage(byteArray)); } catch { return false; } bool result = false; List allItems = val.GetAllItems(); for (int i = 0; i < allItems.Count; i++) { Vector2i gridPos = allItems[i].m_gridPos; if (gridPos.x >= width) { width = gridPos.x + 1; result = true; } if (gridPos.y >= height) { height = gridPos.y + 1; result = true; } } return result; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [HarmonyPatch(typeof(Container), "Awake")] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class Container_Awake_CompanionRegistration_Patch { private static void Prefix(Container __instance) { CompanionsContainer.ApplySize(__instance); } private static void Postfix(Container __instance) { if (CompanionsContainer.IsCompanionContainer(__instance)) { CompanionsContainer.Register(__instance); } } } [HarmonyPatch(typeof(Container), "Load")] internal static class Container_Load_CompanionCapacity_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(Container __instance) { CompanionsContainer.EnsureCapacity(__instance); } } [HarmonyPatch(typeof(InventoryGrid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int), typeof(Vector2i) })] internal static class InventoryGrid_DropItem_Companion_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(InventoryGrid __instance, Inventory fromInventory, ItemData item, int amount, Vector2i pos, ref bool __result) { //IL_000c: 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) Inventory inventory = __instance.GetInventory(); string text = (CompanionsInvoker.BlocksDrop(inventory, fromInventory, item, amount, pos) ? "$companions_msg_unequip_first" : (CompanionsContainer.BlocksDrop(inventory, fromInventory, item, amount, pos) ? "$companions_msg_blocked_item" : null)); if (text == null) { return true; } __result = false; CompanionsContainer.Show(text); return false; } } [HarmonyPatch(typeof(Container), "Interact", new Type[] { typeof(Humanoid), typeof(bool), typeof(bool) })] internal static class Container_Interact_CompanionOwnership_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Container __instance, Humanoid character, ref bool __result) { if (CompanionsContainer.CanAccess(character, __instance)) { CompanionsContainer.RefreshOwnerPlatform(character, __instance); return true; } __result = false; CompanionsContainer.Show("$companions_msg_owner_open"); return false; } } [HarmonyPatch(typeof(Container), "TakeAll", new Type[] { typeof(Humanoid) })] internal static class Container_TakeAll_CompanionOwnership_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Container __instance, Humanoid character) { if (CompanionsContainer.CanAccess(character, __instance)) { return true; } CompanionsContainer.Show("$companions_msg_owner_take_all"); return false; } } [HarmonyPatch(typeof(Container), "RPC_RequestOpen", new Type[] { typeof(long), typeof(long) })] internal static class Container_RPC_RequestOpen_CompanionOwnership_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Container __instance, long uid, long playerID) { if (CompanionsContainer.AllowsRequest(__instance, playerID)) { return true; } __instance.m_nview.InvokeRPC(uid, "RPC_OpenResponse", new object[1] { false }); return false; } } [HarmonyPatch(typeof(Container), "RPC_RequestTakeAll", new Type[] { typeof(long), typeof(long) })] internal static class Container_RPC_RequestTakeAll_CompanionOwnership_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Container __instance, long uid, long playerID) { if (CompanionsContainer.AllowsRequest(__instance, playerID)) { return true; } __instance.m_nview.InvokeRPC(uid, "RPC_TakeAllResponse", new object[1] { false }); return false; } } [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage) })] internal static class Inventory_Load_CompanionBlocklist_Patch { private static void Prefix(out bool __state) { __state = true; CompanionsContainer.BeginLoad(); } private static void Finalizer(bool __state) { if (__state) { CompanionsContainer.EndLoad(); } } } [HarmonyPatch(typeof(Inventory), "Load", new Type[] { typeof(ZPackage), typeof(bool) })] internal static class Inventory_LoadVersioned_CompanionBlocklist_Patch { private static void Prefix(out bool __state) { __state = true; CompanionsContainer.BeginLoad(); } private static void Finalizer(bool __state) { if (__state) { CompanionsContainer.EndLoad(); } } } [HarmonyPatch(typeof(Inventory), "CanAddItem", new Type[] { typeof(ItemData), typeof(int) })] internal static class Inventory_CanAddItem_CompanionBlocklist_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { return CompanionsContainer.AllowAdd(__instance, item, ref __result); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData) })] internal static class Inventory_AddItem_CompanionBlocklist_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { return CompanionsContainer.AllowAdd(__instance, item, ref __result); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(Vector2i) })] internal static class Inventory_AddItemAtPosition_CompanionBlocklist_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { return CompanionsContainer.AllowAdd(__instance, item, ref __result); } } [HarmonyPatch(typeof(Inventory), "AddItem", new Type[] { typeof(ItemData), typeof(int), typeof(int), typeof(int), typeof(bool) })] internal static class Inventory_AddItemInternal_CompanionBlocklist_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Inventory __instance, ItemData item, ref bool __result) { return CompanionsContainer.AllowAdd(__instance, item, ref __result); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsDeathDrop { private static readonly List Loaded = new List(); internal static void DropLoaded(Player owner) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) CompanionsState.CollectLoaded(owner, null, Loaded); for (int i = 0; i < Loaded.Count; i++) { ZNetView val = Loaded[i]; if (!val.IsOwner()) { val.ClaimOwnership(); } Container val2 = CompanionsContainer.FindContainer((Component)(object)val); if ((Object)(object)val2 != (Object)null) { DropInventory(val2, ((Component)val).transform.position); } } Loaded.Clear(); } internal static void DropInventory(Container source, Vector3 position) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) Inventory inventory = source.GetInventory(); if (inventory == null || inventory.NrOfItems() == 0) { return; } GameObject val = FindDropPrefab(); if ((Object)(object)val == (Object)null) { return; } ZNetView view = CompanionsContainer.GetView((Component)(object)source); ZDO val2 = (((Object)(object)view != (Object)null && view.IsValid()) ? view.GetZDO() : null); long num = ((val2 != null) ? val2.GetLong(CompanionsState.OwnerKey, 0L) : 0); string platform = ((val2 != null) ? val2.GetString(CompanionsState.OwnerPlatformKey, string.Empty) : string.Empty); while (inventory.NrOfItems() > 0) { int num2 = inventory.NrOfItems(); GameObject val3 = Object.Instantiate(val, GetDropPosition(position), Random.rotation); Container componentInChildren = val3.GetComponentInChildren(); if ((Object)(object)componentInChildren == (Object)null) { DestroyDrop(val3); break; } ZNetView component = val3.GetComponent(); if (num != 0L && (Object)(object)component != (Object)null && component.IsValid()) { SetCargoOwner(component.GetZDO(), num, platform); CompanionsTracker.Observe(component.GetZDO()); } componentInChildren.GetInventory().MoveAll(inventory); if (inventory.NrOfItems() >= num2) { DestroyDrop(val3); break; } } } internal static void DropStoredInventory(ZDO zdo) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); GameObject val = FindDropPrefab(); Container val2 = (((Object)(object)val != (Object)null) ? val.GetComponentInChildren() : null); if (byteArray == null || byteArray.Length == 0 || (Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { return; } Inventory val3 = new Inventory(true); try { val3.Load(new ZPackage(byteArray)); } catch { return; } if (val3.NrOfItems() == 0) { return; } long owner = zdo.GetLong(CompanionsState.OwnerKey, 0L); string platform = zdo.GetString(CompanionsState.OwnerPlatformKey, string.Empty); Vector3 position = zdo.GetPosition(); while (val3.NrOfItems() > 0) { Inventory val4 = new Inventory(val2.m_name, val2.m_bkg, val2.m_width, val2.m_height); val4.MoveAll(val3); if (val4.NrOfItems() == 0) { break; } if (SpawnStoredCrate(val, GetDropPosition(position), val4, owner, platform)) { continue; } val3.MoveAll(val4); break; } ZPackage val5 = new ZPackage(); val3.Save(val5); zdo.Set(ZDOVars.s_items, val5.GetArray()); } private static bool SpawnStoredCrate(GameObject prefab, Vector3 position, Inventory cargo, long owner, string platform) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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) //IL_0043: Expected O, but got Unknown GameObject val = null; ZDO val2 = null; ZNetView.StartGhostInit(); try { val = Object.Instantiate(prefab, position, Random.rotation); ZNetView component = val.GetComponent(); val2 = (((Object)(object)component != (Object)null) ? component.GetZDO() : null); if (val2 != null) { ZPackage val3 = new ZPackage(); cargo.Save(val3); val2.Set(ZDOVars.s_items, val3.GetArray()); if (owner != 0) { SetCargoOwner(val2, owner, platform); } } } finally { ZNetView.FinishGhostInit(); if ((Object)(object)val != (Object)null) { Object.Destroy((Object)(object)val); } } if (val2 == null) { return false; } CompanionsTracker.Observe(val2); return true; } private static void SetCargoOwner(ZDO zdo, long owner, string platform) { zdo.Set(CompanionsContainer.CargoOwnerKey, owner); if (platform.Length > 0) { zdo.Set(CompanionsContainer.CargoOwnerPlatformKey, platform); } } private static Vector3 GetDropPosition(Vector3 position) { //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_0009: 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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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) Vector3 insideUnitSphere = Random.insideUnitSphere; insideUnitSphere.y = Mathf.Abs(insideUnitSphere.y); return position + insideUnitSphere; } private static void DestroyDrop(GameObject drop) { if ((Object)(object)ZNetScene.instance != (Object)null) { ZNetScene.instance.Destroy(drop); } else { Object.Destroy((Object)(object)drop); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static GameObject FindDropPrefab() { if ((Object)(object)ZNetScene.instance == (Object)null) { return null; } return CompanionsAssets.HasCargoCrate ? ZNetScene.instance.GetPrefab("RDC_CargoCrate") : null; } } [HarmonyPatch(typeof(Character), "OnDeath")] internal static class Character_OnDeath_CompanionDeathDrop_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(Character __instance) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null || !CompanionsState.IsCompanion(((Component)__instance).gameObject)) { return; } ZNetView component = ((Component)__instance).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsOwner()) { Container componentInChildren = ((Component)__instance).GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { CompanionsDeathDrop.DropInventory(componentInChildren, __instance.GetCenterPoint()); } } } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsCall { private const string CallRpc = "RDC_Companion_Call_v2"; private const float StayDistance = 2f; private static readonly List Callable = new List(); internal static void Register(ZNetView view) { if (!((Object)(object)view == (Object)null)) { view.Register("RDC_Companion_Call_v2", (Action)delegate(long sender, ZDOID characterId, long playerId, Vector3 reference) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) Receive(view, sender, characterId, playerId, reference); }); } } internal static void Update(Player player) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) if (!CompanionsControls.IsPressed(CompanionsControls.CallKey) || !((Character)player).TakeInput() || Hud.InRadial()) { return; } Callable.Clear(); List allCharacters = Character.GetAllCharacters(); CompanionIdentity companionIdentity = default(CompanionIdentity); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if (!((Object)(object)val == (Object)null) && ((Component)val).TryGetComponent(ref companionIdentity)) { ZNetView component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && CompanionsState.IsOwner((Humanoid)(object)player, component) && CanCall(component.GetZDO())) { Callable.Add(component); } } } for (int j = 0; j < Callable.Count; j++) { ZNetView val2 = Callable[j]; if (!val2.IsOwner()) { val2.ClaimOwnership(); } val2.InvokeRPC("RDC_Companion_Call_v2", new object[3] { ((Character)player).GetZDOID(), player.GetPlayerID(), ((Component)player).transform.position }); ((Character)player).Message((MessageType)2, GetName(val2) + " $companions_msg_called", 0, (Sprite)null, false); } Callable.Clear(); } private static string GetName(ZNetView view) { Tameable component = ((Component)view).GetComponent(); return ((Object)(object)component != (Object)null) ? component.GetHoverName() : ((Component)view).GetComponent().GetHoverName(); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static bool CanCall(ZDO zdo) { return zdo != null && !zdo.GetBool(CompanionsFlight.DungeonWaitKey, false); } private static bool IsCaller(ZDO zdo, long sender, ZDOID characterId, long playerId) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (playerId == 0L || ((ZDOID)(ref characterId)).IsNone() || ((ZDOID)(ref characterId)).UserID != sender || zdo.GetLong(CompanionsState.OwnerKey, 0L) != playerId) { return false; } ZDO val = CompanionsState.FindZdo(characterId); return val == null || val.GetLong(ZDOVars.s_playerID, 0L) == playerId; } private static void Receive(ZNetView view, long sender, ZDOID characterId, long playerId, Vector3 caller) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_0072: 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_0084: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)view == (Object)null || !view.IsValid() || !view.IsOwner()) { return; } ZDO zDO = view.GetZDO(); if (IsCaller(zDO, sender, characterId, playerId) && CanCall(zDO)) { Character component = ((Component)view).GetComponent(); if (!((Object)(object)component == (Object)null)) { Vector3 val = ((Component)component).transform.position - caller; val.y = 0f; Vector3 reference = caller + ((((Vector3)(ref val)).sqrMagnitude > 0.01f) ? ((Vector3)(ref val)).normalized : Vector3.back) * 2f; reference.y = caller.y; CompanionsFlight.Stay(component, reference); } } } } internal enum CompanionSelectModifier { Alt, Ctrl, Shift } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsControls { internal const string LimeColor = "#ADFF2F"; private const float HoverCacheSeconds = 0.25f; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static string _callLabel; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static string _followStayLabel; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static string _openChestLabel; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Tameable _hoverTameable; private static bool _hoverGamepad; private static float _hoverUntil; private static string _hoverText = string.Empty; internal static KeyboardShortcut CallKey => CompanionsPlugin.CallKey?.Value ?? CompanionsDefaults.CallKey; private static KeyboardShortcut FollowStayKey => CompanionsPlugin.FollowStayKey?.Value ?? CompanionsDefaults.FollowStayKey; private static KeyboardShortcut OpenChestKey => CompanionsPlugin.OpenChestKey?.Value ?? CompanionsDefaults.OpenChestKey; private static CompanionSelectModifier SelectModifier => CompanionsPlugin.SelectModifier?.Value ?? CompanionSelectModifier.Alt; internal static string CallLabel => _callLabel ?? (_callLabel = Label(CallKey)); internal static string FollowStayLabel => _followStayLabel ?? (_followStayLabel = Label(FollowStayKey)); internal static string OpenChestLabel => _openChestLabel ?? (_openChestLabel = Label(OpenChestKey)); internal static string SelectModifierLabel { get { CompanionSelectModifier selectModifier = SelectModifier; if (1 == 0) { } string result = selectModifier switch { CompanionSelectModifier.Ctrl => "Ctrl", CompanionSelectModifier.Shift => "Shift", _ => "Alt", }; if (1 == 0) { } return result; } } internal static void InvalidateLabels() { _callLabel = null; _followStayLabel = null; _openChestLabel = null; _hoverTameable = null; _hoverText = string.Empty; } internal static bool IsSelectModifierHeld() { CompanionSelectModifier selectModifier = SelectModifier; if (1 == 0) { } bool result = selectModifier switch { CompanionSelectModifier.Ctrl => ZInput.GetKey((KeyCode)306, false) || ZInput.GetKey((KeyCode)305, false), CompanionSelectModifier.Shift => ZInput.GetKey((KeyCode)304, false) || ZInput.GetKey((KeyCode)303, false), _ => ZInput.GetKey((KeyCode)308, false) || ZInput.GetKey((KeyCode)307, false), }; if (1 == 0) { } return result; } internal static bool IsPressed(KeyboardShortcut key) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref key)).MainKey == 0 || !ZInput.GetKeyDown(((KeyboardShortcut)(ref key)).MainKey, false)) { return false; } foreach (KeyCode modifier in ((KeyboardShortcut)(ref key)).Modifiers) { if (!ZInput.GetKey(modifier, false)) { return false; } } return true; } internal static void Update(Player player) { //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_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) if (ZInput.IsGamepadActive()) { return; } KeyboardShortcut openChestKey = OpenChestKey; KeyboardShortcut followStayKey = FollowStayKey; bool flag = IsPressed(openChestKey); bool flag2 = IsPressed(followStayKey); if ((!flag && !flag2) || !((Character)player).TakeInput() || Hud.InRadial()) { return; } GameObject hoverObject = ((Humanoid)player).GetHoverObject(); Tameable val = (((Object)(object)hoverObject != (Object)null) ? hoverObject.GetComponentInParent() : null); if ((Object)(object)val == (Object)null || !CompanionsState.IsCompanion(((Component)val).gameObject)) { return; } ZNetView view = CompanionsContainer.GetView((Component)(object)val); if (!CompanionsState.IsOwner((Humanoid)(object)player, view)) { return; } if (!view.IsOwner()) { view.ClaimOwnership(); } if (flag && flag2) { if (ModifierCount(openChestKey) >= ModifierCount(followStayKey)) { flag2 = false; } else { flag = false; } } if (flag) { Container val2 = CompanionsContainer.FindContainer((Component)(object)val); if ((Object)(object)val2 != (Object)null) { val2.Interact((Humanoid)(object)player, false, false); } } else if (flag2) { val.Command((Humanoid)(object)player, true); } } internal static string GetHoverText(Tameable tameable) { bool flag = ZInput.IsGamepadActive(); float time = Time.time; if (tameable == _hoverTameable && flag == _hoverGamepad && time < _hoverUntil) { return _hoverText; } _hoverTameable = tameable; _hoverGamepad = flag; _hoverUntil = time + 0.25f; _hoverText = BuildHoverText(tameable, CompanionsState.IsOwner((Humanoid)(object)Player.m_localPlayer, CompanionsContainer.GetView((Component)(object)tameable)), flag); return _hoverText; } private unsafe static string Label(KeyboardShortcut key) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return ((int)((KeyboardShortcut)(ref key)).MainKey == 0) ? string.Empty : ((object)(*(KeyboardShortcut*)(&key))/*cast due to .constrained prefix*/).ToString(); } private static int ModifierCount(KeyboardShortcut key) { //IL_0014: 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) int num = 0; foreach (KeyCode modifier in ((KeyboardShortcut)(ref key)).Modifiers) { num++; } return num; } private static string BuildHoverText(Tameable tameable, bool owner, bool gamepad) { string hoverName = tameable.GetHoverName(); if (!owner) { return hoverName; } StringBuilder stringBuilder = new StringBuilder(hoverName); string text = (gamepad ? "$KEY_Use" : FollowStayLabel); if (text.Length > 0) { stringBuilder.Append('\n').Append(Localization.instance.Localize("[" + text + "] ")).Append(CompanionsLocalization.Localize("$companions_hover_follow_stay")); } string text2 = ((!gamepad) ? OpenChestLabel : (ZInput.IsNonClassicFunctionality() ? "$KEY_AltKeys + $KEY_Use" : "$KEY_AltPlace + $KEY_Use")); if (text2.Length > 0 && (Object)(object)CompanionsContainer.FindContainer((Component)(object)tameable) != (Object)null) { stringBuilder.Append('\n').Append(Localization.instance.Localize("[" + text2 + "] ")).Append(CompanionsLocalization.Localize("$companions_hover_open_chest")); } string callLabel = CallLabel; if (callLabel.Length > 0) { stringBuilder.Append('\n').Append("[" + callLabel + "] ").Append("") .Append(CompanionsLocalization.Localize("$companions_hover_call")) .Append(""); } return stringBuilder.ToString(); } } [HarmonyPatch(typeof(Player), "Update")] internal static class Player_Update_CompanionControls_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Player __instance) { if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { CompanionsControls.Update(__instance); CompanionsCall.Update(__instance); } } } [HarmonyPriority(0)] [HarmonyPatch(typeof(Tameable), "GetHoverText")] internal static class Tameable_GetHoverText_CompanionInteraction_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Tameable __instance, ref string __result) { if (!((Object)(object)__instance == (Object)null) && CompanionsState.IsCompanion(((Component)__instance).gameObject)) { __result = CompanionsControls.GetHoverText(__instance); } } } [HarmonyPatch(typeof(Tameable), "Interact", new Type[] { typeof(Humanoid), typeof(bool), typeof(bool) })] [HarmonyPriority(0)] internal static class Tameable_Interact_CompanionInteraction_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt, ref bool __result) { if ((Object)(object)__instance == (Object)null || (Object)(object)user == (Object)null || !CompanionsState.IsCompanion(((Component)__instance).gameObject)) { return true; } __result = false; ZNetView view = CompanionsContainer.GetView((Component)(object)__instance); if (!CompanionsState.IsOwner(user, view)) { return false; } if (!view.IsOwner()) { view.ClaimOwnership(); } if (!ZInput.IsGamepadActive()) { return false; } if (ZInput.GetKey((KeyCode)306, true) || ZInput.GetKey((KeyCode)305, true)) { return false; } if (!alt) { return true; } Container val = CompanionsContainer.FindContainer((Component)(object)__instance); if ((Object)(object)val == (Object)null) { return false; } __result = val.Interact(user, hold, false); return false; } } public sealed class CompanionBehavior : MonoBehaviour { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] private static readonly Dictionary Instances = new Dictionary(); [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static CompanionBehavior Find(Component component) { if (Instances.Count == 0 || (Object)(object)component == (Object)null) { return null; } CompanionBehavior value; return (Instances.TryGetValue(component.gameObject, out value) && (Object)(object)value != (Object)null) ? value : null; } private void Awake() { Instances[((Component)this).gameObject] = this; } private void OnDestroy() { if (Instances.TryGetValue(((Component)this).gameObject, out var value) && (Object)(object)value == (Object)(object)this) { Instances.Remove(((Component)this).gameObject); } } } [HarmonyPatch(typeof(Character), "Damage", new Type[] { typeof(HitData) })] internal static class Character_Damage_CompanionInvulnerability_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Character __instance) { return (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null; } } [HarmonyPatch(typeof(Character), "StartAttack", new Type[] { typeof(Character), typeof(bool) })] internal static class Character_StartAttack_CompanionPacifism_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Character __instance) { return (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null; } } [HarmonyPatch(typeof(BaseAI), "Alert")] internal static class BaseAI_Alert_CompanionPacifism_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(BaseAI __instance) { return (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null; } } [HarmonyPatch(typeof(BaseAI), "SetAlerted", new Type[] { typeof(bool) })] internal static class BaseAI_SetAlerted_CompanionPacifism_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(BaseAI __instance, bool alert) { return !alert || (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null; } } [HarmonyPatch(typeof(BaseAI), "SetAggravated", new Type[] { typeof(bool), typeof(AggravatedReason) })] internal static class BaseAI_SetAggravated_CompanionPacifism_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(BaseAI __instance, bool aggro) { return !aggro || (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null; } } [HarmonyPatch(typeof(BaseAI), "IsEnemy", new Type[] { typeof(Character) })] internal static class BaseAI_IsEnemy_CompanionPacifism_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(BaseAI __instance, Character other, ref bool __result) { if (__result && !((Object)(object)__instance == (Object)null) && !((Object)(object)other == (Object)null) && ((Object)(object)CompanionBehavior.Find((Component)(object)__instance) != (Object)null || (Object)(object)CompanionBehavior.Find((Component)(object)other) != (Object)null)) { __result = false; } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsFlight { internal const float DefaultHeight = 1f; internal const float FollowTurnSpeed = 900f; internal const float CollectTurnSpeed = 220f; private const float SmoothAcceleration = 0.15f; private const float RebindInterval = 0.5f; private const float ShipClearance = 2f; internal static readonly int StayBaseKey = StringExtensionMethods.GetStableHashCode("comp.stayBase"); internal static readonly int HasStayKey = StringExtensionMethods.GetStableHashCode("comp.hasStay"); internal static readonly int DungeonWaitKey = StringExtensionMethods.GetStableHashCode("comp.dungeonWait"); private static readonly Dictionary Anchors = new Dictionary(); internal static float Height { get { float num = CompanionsPlugin.FlightHeight?.Value ?? 1f; return (float.IsNaN(num) || float.IsInfinity(num)) ? 1f : Mathf.Max(0f, num); } } internal static Vector3 GetArrivalPosition(Vector3 origin, Vector3 horizontalOffset) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: 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_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) return origin + horizontalOffset + Vector3.up * Height; } internal static Vector3 GetArrivalPosition(Player owner, Vector3 horizontalOffset) { //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) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_001b: Unknown result type (might be due to invalid IL or missing references) return RaiseForShip(owner, GetArrivalPosition(((Component)owner).transform.position, horizontalOffset)); } internal static Vector3 RaiseForShip(Player owner, Vector3 position) { //IL_0018: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //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) //IL_0033: Unknown result type (might be due to invalid IL or missing references) return ((Object)(object)owner != (Object)null && (Object)(object)((Character)owner).GetStandingOnShip() != (Object)null) ? (position + Vector3.up * 2f) : position; } internal static void ApplyHeight(MonsterAI ai, bool initializeTurnSpeed = true) { if ((Object)(object)ai == (Object)null) { return; } ((BaseAI)ai).m_flyAltitudeMin = 0f; ((BaseAI)ai).m_flyAltitudeMax = 0f; ((BaseAI)ai).m_flyAbsMinAltitude = 0f; ((BaseAI)ai).m_smoothMovement = false; ((BaseAI)ai).m_serpentMovement = false; ((BaseAI)ai).m_moveMinAngle = 181f; ((BaseAI)ai).m_randomFly = false; ai.m_fallAsleepDistance = 0f; ai.m_avoidLand = false; ((BaseAI)ai).m_avoidFire = false; ((BaseAI)ai).m_afraidOfFire = false; ai.m_fleeInLava = false; Character component = ((Component)ai).GetComponent(); if ((Object)(object)component != (Object)null) { component.m_flying = true; if (initializeTurnSpeed) { component.m_flyTurnSpeed = 900f; } component.m_acceleration = 0.15f; } } internal static void ForgetAnchor(CompanionFlightAnchor anchor) { Player owner = anchor.Owner; if (owner != null && Anchors.TryGetValue(owner, out var value) && value == anchor) { Anchors.Remove(owner); } } internal static GameObject GetFollowTarget(Player owner) { //IL_008c: 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) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown if (!Anchors.TryGetValue(owner, out var value) || (Object)(object)value == (Object)null || (Object)(object)((Component)value).transform.parent != (Object)(object)((Component)owner).transform) { value = ((Component)owner).GetComponentInChildren(true); if ((Object)(object)value == (Object)null) { GameObject val = new GameObject("CompanionFlightAnchor"); val.transform.SetParent(((Component)owner).transform, false); value = val.AddComponent(); } value.Owner = owner; Anchors[owner] = value; } ((Component)value).transform.localPosition = Vector3.up * Height; ((Component)value).transform.localRotation = Quaternion.identity; return ((Component)value).gameObject; } internal static void FollowOwner(Character character, Player owner, bool smooth = false) { if ((Object)(object)character == (Object)null || (Object)(object)owner == (Object)null) { return; } ZNetView component = ((Component)character).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner()) { return; } CompanionCollector componentInChildren = ((Component)character).GetComponentInChildren(); if (!((Object)(object)componentInChildren != (Object)null) || !componentInChildren.RestoreTarget(character)) { SetTarget(character, GetFollowTarget(owner), smooth); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.ScheduleScan(); } } } internal static void FollowCollectionTarget(Character character, GameObject target) { if ((Object)(object)character != (Object)null && (Object)(object)target != (Object)null) { SetTarget(character, target, smooth: true); } } private static void SetTarget(Character character, GameObject target, bool smooth) { //IL_0047: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) MonsterAI component = ((Component)character).GetComponent(); if ((Object)(object)component == (Object)null) { return; } ApplyHeight(component, initializeTurnSpeed: false); if ((Object)(object)component.GetFollowTarget() == (Object)(object)target) { return; } if (!smooth) { Vector3 val = target.transform.position - ((Component)character).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { ((Component)character).transform.rotation = Quaternion.RotateTowards(((Component)character).transform.rotation, Quaternion.LookRotation(val), 110f); character.SetLookDir(val, 0f); } Rigidbody component2 = ((Component)character).GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.linearVelocity = Vector3.zero; } } component.Wakeup(); component.m_targetCreature = null; component.m_targetStatic = null; ((BaseAI)component).m_getOutOfCornerTimer = 0f; ((BaseAI)component).m_stuckTimer = 0f; ((BaseAI)component).SetHuntPlayer(false); ((BaseAI)component).SetAlerted(false); ((BaseAI)component).ResetPatrolPoint(); if (!smooth) { ((BaseAI)component).StopMoving(); } component.SetFollowTarget(target); } internal static void Stay(Character character, Vector3 reference) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)character).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner()) { CompanionCollector componentInChildren = ((Component)character).GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.CancelTarget(); } ZDO zDO = component.GetZDO(); zDO.Set(StayBaseKey, reference); zDO.Set(HasStayKey, true); zDO.Set(ZDOVars.s_follow, string.Empty); RestoreFollow(((Component)character).gameObject); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.ScheduleScan(); } } } internal static void RestoreFollow(GameObject instance, bool smooth = false) { //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_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Expected O, but got Unknown CompanionIdentity companionIdentity = default(CompanionIdentity); if ((Object)(object)instance == (Object)null || !instance.TryGetComponent(ref companionIdentity)) { return; } ZNetView component = instance.GetComponent(); Character component2 = instance.GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || (Object)(object)component2 == (Object)null) { return; } ZDO zDO = component.GetZDO(); if (CompanionsRegistry.ForCompanion(zDO) == null) { return; } if (!string.IsNullOrEmpty(zDO.GetString(ZDOVars.s_follow, ""))) { Player val = CompanionsState.FindOwner(zDO); if ((Object)(object)val != (Object)null) { FollowOwner(component2, val, smooth); } } else if (zDO.GetLong(CompanionsState.OwnerKey, 0L) != 0) { Vector3 val2 = instance.transform.position - Vector3.up * Height; if (!zDO.GetBool(HasStayKey, false)) { zDO.Set(StayBaseKey, val2); zDO.Set(HasStayKey, true); } if ((Object)(object)companionIdentity.StayTarget == (Object)null) { companionIdentity.StayTarget = new GameObject("CompanionStayAnchor"); } companionIdentity.StayTarget.transform.position = zDO.GetVec3(StayBaseKey, val2) + Vector3.up * Height; SetTarget(component2, companionIdentity.StayTarget, smooth); } } internal static void Rebind(BaseAI ai) { CompanionIdentity companionIdentity = default(CompanionIdentity); if (((Component)ai).TryGetComponent(ref companionIdentity) && !(Time.time < companionIdentity.NextRebind)) { companionIdentity.NextRebind = Time.time + 0.5f; RestoreFollow(((Component)ai).gameObject); } } internal static void RefreshHeight() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) CompanionFlightAnchor[] array = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (CompanionFlightAnchor companionFlightAnchor in array) { ((Component)companionFlightAnchor).transform.localPosition = Vector3.up * Height; } CompanionIdentity[] array2 = Object.FindObjectsByType((FindObjectsSortMode)0); foreach (CompanionIdentity companionIdentity in array2) { ApplyHeight(((Component)companionIdentity).GetComponent()); RestoreFollow(((Component)companionIdentity).gameObject); } } } public sealed class CompanionFlightAnchor : MonoBehaviour { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal Player Owner; private void OnDestroy() { CompanionsFlight.ForgetAnchor(this); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [HarmonyPatch(typeof(BaseAI), "Follow", new Type[] { typeof(GameObject), typeof(float) })] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class BaseAI_Follow_CompanionSmoothArrival_Patch { private const float StopDistance = 3f; private const float SlowDownDistance = 8f; private const float RunDistance = 10f; private const float MinSpeedFactor = 0.2f; private const float CatchUpSpeedMultiplier = 1.25f; private const float MaxSampledOwnerSpeed = 100f; private const float WaterClearance = 1f; private const float CollectSpeedFactor = 0.55f; private const float CollectSpeedChangePerSecond = 1.5f; private const float TurnSpeedChangePerSecond = 700f; private static bool Prefix(BaseAI __instance, GameObject go, float dt) { //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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: 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_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)go == (Object)null || (Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null) { return true; } Character character = __instance.m_character; CompanionIdentity identity = default(CompanionIdentity); if ((Object)(object)character == (Object)null || !((Component)__instance).TryGetComponent(ref identity)) { return true; } Vector3 val = AboveWater(identity, character, go.transform.position); float num = Vector3.Distance(val, ((Component)__instance).transform.position); UpdateFlySpeed(identity, character, go, num, dt); UpdateTurnSpeed(identity, character, dt); if (num < 3f) { __instance.StopMoving(); return false; } __instance.MoveTo(dt, val, 0f, num > 10f); if (num < 8f) { float num2 = Mathf.InverseLerp(3f, 8f, num); character.m_moveDir *= Mathf.SmoothStep(0.2f, 1f, num2); } character.m_moveDir *= UpdateCollectSpeed(identity, dt); return false; } internal static Vector3 AboveWater(CompanionIdentity identity, Character character, Vector3 destination) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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)ZoneSystem.instance == (Object)null) { return destination; } if (identity.BodyBelowPivot < 0f) { if ((Object)(object)character.m_collider == (Object)null) { return destination; } float y = ((Component)character).transform.position.y; Bounds bounds = ((Collider)character.m_collider).bounds; identity.BodyBelowPivot = Mathf.Max(0f, y - ((Bounds)(ref bounds)).min.y); } float num = ZoneSystem.instance.m_waterLevel + 1f + identity.BodyBelowPivot; if (destination.y < num) { destination.y = num; } return destination; } private static float UpdateCollectSpeed(CompanionIdentity identity, float dt) { float num = (identity.Collecting ? 0.55f : 1f); identity.CollectSpeedScale = Mathf.MoveTowards(identity.CollectSpeedScale, num, 1.5f * dt); return identity.CollectSpeedScale; } private static void UpdateTurnSpeed(CompanionIdentity identity, Character character, float dt) { float num = (identity.Collecting ? 220f : 900f); character.m_flyTurnSpeed = Mathf.MoveTowards(character.m_flyTurnSpeed, num, 700f * dt); } private static void UpdateFlySpeed(CompanionIdentity identity, Character character, GameObject target, float distance, float dt) { //IL_0051: 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_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_0073: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (identity.BaseFlyFastSpeed < 0f) { identity.BaseFlyFastSpeed = character.m_flyFastSpeed; } float num = identity.BaseFlyFastSpeed; CompanionFlightAnchor companionFlightAnchor = default(CompanionFlightAnchor); if (target.TryGetComponent(ref companionFlightAnchor) && (Object)(object)companionFlightAnchor.Owner != (Object)null) { Vector3 position = ((Component)companionFlightAnchor.Owner).transform.position; if (identity.HasOwnerSample && dt > 0f) { Vector3 val = position - identity.LastOwnerPosition; float num2 = ((Vector3)(ref val)).magnitude / dt; if (num2 < 100f) { identity.OwnerSpeed = Mathf.Lerp(identity.OwnerSpeed, num2, Mathf.Clamp01(dt * 4f)); } } identity.LastOwnerPosition = position; identity.HasOwnerSample = true; if (distance > 10f) { num = Mathf.Max(num, identity.OwnerSpeed * 1.25f); } } else { identity.HasOwnerSample = false; } character.m_flyFastSpeed = num; } } [HarmonyPatch(typeof(BaseAI), "MoveTo")] internal static class BaseAI_MoveTo_CompanionAboveWater_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(BaseAI __instance, ref Vector3 point) { //IL_003a: 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) //IL_0044: Unknown result type (might be due to invalid IL or missing references) CompanionIdentity identity = default(CompanionIdentity); if (!((Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null) && !((Object)(object)__instance.m_character == (Object)null) && ((Component)__instance).TryGetComponent(ref identity)) { point = BaseAI_Follow_CompanionSmoothArrival_Patch.AboveWater(identity, __instance.m_character, point); } } } [HarmonyPatch(typeof(BaseAI), "IdleMovement")] internal static class BaseAI_IdleMovement_Companion_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(BaseAI __instance) { if ((Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null) { return true; } __instance.StopMoving(); CompanionsFlight.Rebind(__instance); return false; } } [HarmonyPatch(typeof(Tameable), "UpdateSavedFollowTarget")] internal static class Tameable_UpdateSavedFollowTarget_Companion_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Tameable __instance) { if ((Object)(object)CompanionBehavior.Find((Component)(object)__instance) == (Object)null) { return true; } MonsterAI monsterAI = __instance.m_monsterAI; if ((Object)(object)monsterAI != (Object)null && (Object)(object)monsterAI.GetFollowTarget() == (Object)null && (Object)(object)__instance.m_nview != (Object)null && __instance.m_nview.IsValid() && __instance.m_nview.IsOwner()) { CompanionsFlight.Rebind((BaseAI)(object)monsterAI); } return false; } } [HarmonyPatch(typeof(MonsterAI), "SetFollowTarget", new Type[] { typeof(GameObject) })] internal static class MonsterAI_SetFollowTarget_CompanionFlight_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(MonsterAI __instance, ref GameObject go) { if (!((Object)(object)go == (Object)null) && CompanionsState.IsCompanion(((Component)__instance).gameObject)) { Player component = go.GetComponent(); if ((Object)(object)component != (Object)null) { go = CompanionsFlight.GetFollowTarget(component); } } } } [HarmonyPatch(typeof(Tameable), "RPC_Command", new Type[] { typeof(long), typeof(ZDOID), typeof(bool) })] internal static class Tameable_RPC_Command_CompanionFlight_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Tameable __instance, long sender, ZDOID characterID, bool message) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0180: 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_018f: 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) if (!CompanionsState.IsCompanion(((Component)__instance).gameObject)) { return true; } ZNetView nview = __instance.m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid() || !nview.IsOwner()) { return false; } if ((Object)(object)ZNetScene.instance == (Object)null) { return false; } GameObject val = ZNetScene.instance.FindInstance(characterID); Player val2 = (((Object)(object)val != (Object)null) ? val.GetComponent() : null); if ((Object)(object)val2 == (Object)null || !CompanionsState.IsOwner((Humanoid)(object)val2, nview)) { return false; } ZNetView nview2 = ((Character)val2).m_nview; if ((Object)(object)nview2 == (Object)null || !nview2.IsValid()) { return false; } long num = ((ZRoutedRpc.instance != null) ? ZRoutedRpc.instance.GetServerPeerID() : 0); if (sender != nview2.GetZDO().GetOwner() && sender != num) { return false; } ZDO zDO = nview.GetZDO(); zDO.Set(CompanionsFlight.DungeonWaitKey, false); bool flag = !message || string.IsNullOrEmpty(zDO.GetString(ZDOVars.s_follow, "")); Character character = __instance.m_character; if (flag) { zDO.Set(ZDOVars.s_follow, val2.GetPlayerName()); CompanionsFlight.FollowOwner(character, val2); } else { Vector3 position = ((Component)character).transform.position; position.y = ((Component)val2).transform.position.y; CompanionsFlight.Stay(character, position); } if (message) { ((Character)val2).Message((MessageType)2, __instance.GetHoverName() + (flag ? " $hud_tamefollow" : " $hud_tamestay"), 0, (Sprite)null, false); } return false; } } [HarmonyPatch(typeof(ZNetScene), "CreateObject", new Type[] { typeof(ZDO) })] internal static class ZNetScene_CreateObject_CompanionFollow_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(GameObject __result) { CompanionIdentity companionIdentity = default(CompanionIdentity); if ((Object)(object)__result != (Object)null && __result.TryGetComponent(ref companionIdentity)) { CompanionsFlight.RestoreFollow(__result); } } } [HarmonyPatch(typeof(ZDO), "Deserialize", new Type[] { typeof(ZPackage) })] internal static class ZDO_Deserialize_CompanionFollow_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ZDO __instance) { if (__instance == null) { return; } int prefab = __instance.GetPrefab(); if (!CompanionsTracker.IsTracked(prefab)) { return; } CompanionsTracker.Observe(__instance); if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsDedicated() && CompanionsRegistry.ForCompanion(prefab) != null && __instance.IsOwner() && CompanionsState.IsCompanion(__instance)) { ZNetView val = CompanionsState.FindInstance(__instance); CompanionIdentity companionIdentity = default(CompanionIdentity); if ((Object)(object)val != (Object)null && ((Component)val).TryGetComponent(ref companionIdentity)) { companionIdentity.ScheduleRestore(); } } } } [HarmonyPatch(typeof(ZDO), "SetOwnerInternal", new Type[] { typeof(long) })] internal static class ZDO_SetOwnerInternal_Companions_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ZDO __instance) { if (__instance == null || (Object)(object)ZNetScene.instance == (Object)null) { return; } if (CompanionsRegistry.ForCompanion(__instance.GetPrefab()) != null) { if (!CompanionsState.IsCompanion(__instance)) { return; } ZNetView val = ZNetScene.instance.FindInstance(__instance); if (!((Object)(object)val == (Object)null)) { CompanionIdentity companionIdentity = default(CompanionIdentity); if (__instance.IsOwner() && ((Component)val).TryGetComponent(ref companionIdentity)) { companionIdentity.ScheduleRestore(); } CompanionCollector componentInChildren = ((Component)val).GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.UpdateActive(); } } } else if (__instance.IsOwner() && CompanionCollector.AnyActive) { ZNetView val2 = ZNetScene.instance.FindInstance(__instance); ItemDrop drop = default(ItemDrop); if ((Object)(object)val2 != (Object)null && ((Component)val2).TryGetComponent(ref drop)) { CompanionCollector.NotifyNearby(drop); } } } } public sealed class CompanionIdentity : MonoBehaviour { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal GameObject StayTarget; internal float BaseFlyFastSpeed = -1f; internal Vector3 LastOwnerPosition; internal float OwnerSpeed; internal bool HasOwnerSample; internal bool Collecting; internal float CollectSpeedScale = 1f; internal float NextRebind; internal float BodyBelowPivot = -1f; private bool _bound; private bool _restorePending; internal void ScheduleRestore() { _restorePending = true; } private void Awake() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) CompanionsFlight.ApplyHeight(((Component)this).GetComponent()); Character component = ((Component)this).GetComponent(); if ((Object)(object)component != (Object)null) { component.m_tamed = true; component.m_faction = (Faction)0; } Bind(); } private void Start() { Bind(); CompanionsFlight.RestoreFollow(((Component)this).gameObject); } private void Update() { if (_restorePending) { _restorePending = false; CompanionsFlight.RestoreFollow(((Component)this).gameObject); } } private void OnDestroy() { if ((Object)(object)StayTarget != (Object)null) { Object.Destroy((Object)(object)StayTarget); } } private void Bind() { if (_bound) { return; } ZNetView component = ((Component)this).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { if (component.IsOwner()) { component.GetZDO().Set(CompanionsState.CompanionKey, 1, false); } CompanionsCall.Register(component); _bound = true; } } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsCreature { internal static void Configure(GameObject prefab, CompanionDefinition definition) { //IL_001a: 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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Expected O, but got Unknown //IL_01d2: Unknown result type (might be due to invalid IL or missing references) Character component = prefab.GetComponent(); if ((Object)(object)component == (Object)null) { throw new MissingComponentException("Character"); } MonsterAI component2 = prefab.GetComponent(); if ((Object)(object)component2 == (Object)null) { throw new MissingComponentException("MonsterAI"); } Tameable orAdd = GetOrAdd(prefab); ZNetView orAdd2 = GetOrAdd(prefab); component.m_name = definition.CompanionNameToken; component.m_faction = (Faction)0; component.m_tamed = true; component.m_flying = true; ((BaseAI)component2).m_randomFly = false; component2.m_sleeping = false; component2.m_fallAsleepDistance = 0f; component2.m_avoidLand = false; component2.m_enableHuntPlayer = false; component2.m_attackPlayerObjects = false; component2.m_fleeIfHurtWhenTargetCantBeReached = false; component2.m_fleeIfNotAlerted = false; component2.m_fleeIfLowHealth = 0f; component2.m_consumeItems?.Clear(); CompanionsFlight.ApplyHeight(component2); orAdd.m_startsTamed = true; orAdd.m_commandable = true; orAdd.m_fedDuration = 999999f; orAdd2.m_persistent = true; GetOrAdd(prefab); GetOrAdd(prefab); Container orAdd3 = GetOrAdd(prefab); orAdd3.m_name = "$companions_chest_name"; CompanionsContainer.ApplySize(orAdd3, definition); if ((Object)(object)prefab.GetComponentInChildren(true) == (Object)null) { GameObject val = new GameObject("CompanionCollectionSensor"); val.transform.SetParent(prefab.transform, false); val.layer = LayerMask.NameToLayer("Ignore Raycast"); SphereCollider val2 = val.AddComponent(); ((Collider)val2).isTrigger = true; CompanionCollector.ApplyLayerFilter((Collider)(object)val2); val.AddComponent(); } if ((Object)(object)prefab.GetComponent() == (Object)null) { CapsuleCollider val3 = prefab.AddComponent(); ((Collider)val3).isTrigger = false; val3.radius = 0.6f; val3.height = 2f; val3.center = new Vector3(0f, 1f, 0f); } } private static T GetOrAdd<[<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] T>(GameObject prefab) where T : Component { T component = prefab.GetComponent(); return ((Object)(object)component != (Object)null) ? component : prefab.AddComponent(); } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsMapIcons { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private sealed class Entry { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal PinData Pin; internal Vector3 Target; internal int PrefabHash; internal bool Seen; internal bool IsCrate; } private const float PinMoveSpeed = 200f; private const float SnapDistance = 300f; private static readonly Dictionary Entries = new Dictionary(); private static readonly List Removed = new List(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Minimap _minimap; internal static void Clear() { Minimap minimap = (((Object)(object)_minimap != (Object)null) ? _minimap : Minimap.instance); foreach (Entry value in Entries.Values) { RemovePin(minimap, value); } Entries.Clear(); _minimap = null; } internal static void Receive(ZPackage package) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //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_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) foreach (Entry value2 in Entries.Values) { value2.Seen = false; } int num = package.ReadInt(); for (int i = 0; i < num; i++) { ZDOID key = package.ReadZDOID(); int prefabHash = package.ReadInt(); Vector3 target = package.ReadVector3(); if (!Entries.TryGetValue(key, out var value)) { value = new Entry(); Entries[key] = value; } value.Target = target; value.PrefabHash = prefabHash; value.IsCrate = CompanionsRegistry.ForCompanion(prefabHash) == null; value.Seen = true; } Minimap instance = Minimap.instance; if ((Object)(object)instance != (Object)null) { foreach (Entry value3 in Entries.Values) { if (value3.Pin != null && !instance.m_pins.Contains(value3.Pin)) { value3.Pin = null; } } } Removed.Clear(); foreach (KeyValuePair entry in Entries) { if (!entry.Value.Seen) { RemovePin(instance, entry.Value); Removed.Add(entry.Key); } } for (int j = 0; j < Removed.Count; j++) { Entries.Remove(Removed[j]); } } internal static void Update(Minimap minimap, float dt) { //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_013e: 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_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: 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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) if (_minimap != minimap) { _minimap = minimap; Entries.Clear(); } bool flag = CompanionsPlugin.ShowMapIcon?.Value ?? true; foreach (Entry value in Entries.Values) { if (!value.IsCrate && !flag) { RemovePin(minimap, value); continue; } if (value.Pin == null) { CompanionDefinition definition = CompanionsRegistry.ForCompanion(value.PrefabHash); value.Pin = minimap.AddPin(value.Target, (PinType)8, value.IsCrate ? GetCrateName() : GetName(definition), false, false, 0L, default(PlatformUserID)); Sprite val = (value.IsCrate ? CompanionsAssets.DeathMapIcon : CompanionsAssets.GetMapIcon(definition)); value.Pin.m_icon = (((Object)(object)val != (Object)null) ? val : minimap.GetSprite((PinType)(value.IsCrate ? 4 : 3))); minimap.m_pinUpdateRequired = true; continue; } Vector3 pos = value.Pin.m_pos; Vector3 val2 = ((Vector3.Distance(pos, value.Target) > 300f) ? value.Target : Vector3.MoveTowards(pos, value.Target, 200f * dt)); if (!(val2 == pos)) { value.Pin.m_pos = val2; minimap.m_pinUpdateRequired = true; } } } private static void RemovePin([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] Minimap minimap, Entry entry) { if (entry.Pin != null && (Object)(object)minimap != (Object)null) { minimap.RemovePin(entry.Pin); } entry.Pin = null; } private static string GetCrateName() { return (Localization.instance != null) ? Localization.instance.Localize("$companions_cargo_name") : string.Empty; } private static string GetName([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] CompanionDefinition definition) { return (definition != null && Localization.instance != null) ? Localization.instance.Localize(definition.CompanionNameToken) : string.Empty; } } [HarmonyPatch(typeof(Minimap), "Update")] internal static class Minimap_Update_CompanionIcons_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Minimap __instance) { CompanionsMapIcons.Update(__instance, Time.deltaTime); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsLifecycle { private static readonly Vector3 SummonOffset = new Vector3(1.25f, 0f, 0.75f); private static readonly List LoadedBuffer = new List(); internal static CompanionStatus HandleRequest(long sender, CompanionOp op, string prefabName, bool option, ZPackage origin, ZPackage data) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) CompanionDefinition companionDefinition = null; if (prefabName.Length > 0) { companionDefinition = CompanionsRegistry.ForCompanion(prefabName); if (companionDefinition == null) { return CompanionStatus.Invalid; } } bool flag = companionDefinition == null; bool flag2 = flag; if (flag2) { bool flag3; switch (op) { case CompanionOp.Summon: case CompanionOp.Unsummon: case CompanionOp.Keep: flag3 = true; break; default: flag3 = false; break; } flag2 = flag3; } if (flag2) { return CompanionStatus.Invalid; } if (!CompanionsTracker.IndexReady || !CompanionsPeers.TryResolve(sender, out var requester)) { return CompanionStatus.NotReady; } if (origin != null && origin.Size() > 0 && origin.ReadBool()) { requester = requester.At(origin.ReadVector3(), origin.ReadSingle()); } return op switch { CompanionOp.Summon => Summon(requester, companionDefinition, option, data), CompanionOp.Check => Check(requester, companionDefinition, data), CompanionOp.Unsummon => Unsummon(requester, companionDefinition, option), CompanionOp.Keep => Keep(requester, companionDefinition), _ => DeathDrop(requester), }; } internal static void SpawnLocal(Player owner, CompanionDefinition definition, string platform) { //IL_0031: 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_003a: Unknown result type (might be due to invalid IL or missing references) //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_0050: 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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: 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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)owner == (Object)null || definition == null || (Object)(object)ZNetScene.instance == (Object)null) { return; } Quaternion rotation = ((Component)owner).transform.rotation; Quaternion val = Quaternion.Euler(0f, ((Quaternion)(ref rotation)).eulerAngles.y, 0f); Vector3 arrivalPosition = CompanionsFlight.GetArrivalPosition(owner, SummonOffset); CompanionsState.CollectLoaded(owner, definition, LoadedBuffer); if (LoadedBuffer.Count > 0) { ZNetView val2 = LoadedBuffer[0]; LoadedBuffer.Clear(); if (!val2.IsOwner()) { val2.ClaimOwnership(); } CompanionsNetwork.MoveLocal(val2, arrivalPosition, val, CompanionMove.Follow | CompanionMove.Summon, owner.GetPlayerName(), control: true); CompanionsAssets.SpawnBirthEffect(arrivalPosition, definition); return; } GameObject prefab = ZNetScene.instance.GetPrefab(definition.CompanionPrefab); if (!((Object)(object)prefab == (Object)null)) { GameObject val3 = Object.Instantiate(prefab, arrivalPosition, val); if (platform.Length == 0) { platform = CompanionsState.GetPlatformId(owner); } CompanionsState.MarkOwned(val3, owner, platform); ZNetView component = val3.GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid()) { CompanionsTracker.Observe(component.GetZDO()); } Character component2 = val3.GetComponent(); if ((Object)(object)component2 != (Object)null) { CompanionsFlight.FollowOwner(component2, owner); } CompanionsAssets.SpawnBirthEffect(arrivalPosition, definition); } } internal static void DestroyLoaded(Player owner, CompanionDefinition definition, bool discardItems) { if (!((Object)(object)owner == (Object)null) && definition != null) { CompanionsState.CollectLoaded(owner, definition, LoadedBuffer); for (int i = 0; i < LoadedBuffer.Count; i++) { CompanionsNetwork.DestroyLocal(LoadedBuffer[i], discardItems); } LoadedBuffer.Clear(); } } internal static void KeepLoaded(Player owner, CompanionDefinition definition) { if ((Object)(object)owner == (Object)null || definition == null) { return; } CompanionsState.CollectLoaded(owner, definition, LoadedBuffer); for (int i = 0; i < LoadedBuffer.Count; i++) { ZNetView val = LoadedBuffer[i]; if (!val.IsOwner()) { val.ClaimOwnership(); } val.GetZDO().Set(CompanionsState.KeptKey, true); } LoadedBuffer.Clear(); } internal static Vector3 GetTeleportOffset(int index) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_005a: 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_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_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) int num = index % 4; if (1 == 0) { } Vector3 result = (Vector3)(num switch { 0 => new Vector3(1.5f, 0f, 0f), 1 => new Vector3(-1.5f, 0f, 0f), 2 => new Vector3(0f, 0f, 1.5f), _ => new Vector3(0f, 0f, -1.5f), }); if (1 == 0) { } return result; } private static CompanionStatus Summon(CompanionRequester requester, CompanionDefinition definition, bool followersOnly, ZPackage data) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) if (!requester.HasPosition) { return CompanionStatus.NotReady; } List owned = CompanionsTracker.GetOwned(requester.PlayerId, requester.Platform, definition); if (followersOnly) { owned.RemoveAll((ZDO zdo) => !CompanionsCatchUp.IsFollowing(zdo) && !CompanionsCatchUp.IsWaiting(zdo)); } if (owned.Count == 0) { if (followersOnly) { return CompanionStatus.NotFound; } if (!CompanionsTracker.TryReserve(requester.PlayerId, definition)) { return CompanionStatus.Busy; } data.Write(requester.Platform); return CompanionStatus.SpawnLocal; } ZDO val = FindClosest(owned, requester.Position); if (val.GetBool(CompanionsFlight.DungeonWaitKey, false) && Character.InInterior(requester.Position)) { return CompanionStatus.Waiting; } if (IsAlreadyNear(val, requester.Position)) { CompanionsNetwork.ClaimIdle(val, requester); return CompanionStatus.Ok; } Vector3 arrivalPosition = CompanionsFlight.GetArrivalPosition(requester.Position, SummonOffset); Quaternion rotation = Quaternion.Euler(0f, requester.Yaw, 0f); bool flag = CompanionsNetwork.MoveCompanion(val, requester, arrivalPosition, rotation, CompanionMove.Follow | CompanionMove.Summon); data.Write(arrivalPosition); return flag ? CompanionStatus.Routed : CompanionStatus.Moved; } private static CompanionStatus Check(CompanionRequester requester, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] CompanionDefinition definition, ZPackage data) { List owned = CompanionsTracker.GetOwned(requester.PlayerId, requester.Platform, definition); if (definition == null) { owned.RemoveAll(CompanionsState.IsKept); } bool flag = false; data.Write(owned.Count); for (int i = 0; i < owned.Count; i++) { ZDO val = owned[i]; bool flag2 = CompanionsState.HasStoredItems(val); flag = flag || flag2; data.Write(val.GetPrefab()); data.Write(flag2); } return flag ? CompanionStatus.HasItems : CompanionStatus.NoItems; } private static CompanionStatus Unsummon(CompanionRequester requester, CompanionDefinition definition, bool discardItems) { List owned = CompanionsTracker.GetOwned(requester.PlayerId, requester.Platform, definition); if (owned.Count == 0) { return CompanionStatus.NotFound; } if (!discardItems && CompanionsState.HasStoredItems(owned)) { return CompanionStatus.HasItems; } bool flag = false; for (int i = 0; i < owned.Count; i++) { if (!CompanionsNetwork.DestroyCompanion(owned[i], discardItems)) { flag = true; } } return flag ? CompanionStatus.HasItems : CompanionStatus.Ok; } private static CompanionStatus Keep(CompanionRequester requester, CompanionDefinition definition) { List owned = CompanionsTracker.GetOwned(requester.PlayerId, requester.Platform, definition); for (int i = 0; i < owned.Count; i++) { ZDO zdo = owned[i]; if (!CompanionsNetwork.IsInPeerArea(zdo, requester.Peer)) { CompanionsNetwork.KeepCompanion(zdo, requester); } } return CompanionStatus.Ok; } private static CompanionStatus DeathDrop(CompanionRequester requester) { List owned = CompanionsTracker.GetOwned(requester.PlayerId, requester.Platform, null); for (int i = 0; i < owned.Count; i++) { ZDO zdo = owned[i]; if (!CompanionsNetwork.IsInPeerArea(zdo, requester.Peer)) { CompanionsNetwork.DeathDropCompanion(zdo, requester); } } return CompanionStatus.Ok; } private static bool IsAlreadyNear(ZDO companion, Vector3 origin) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) Vector3 position = companion.GetPosition(); return CompanionsCatchUp.IsFollowing(companion) && !CompanionsState.IsKept(companion) && Character.InInterior(position) == Character.InInterior(origin) && Vector3.Distance(position, origin) <= CompanionsCatchUp.Distance; } private static ZDO FindClosest(List companions, Vector3 origin) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_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) //IL_002d: Unknown result type (might be due to invalid IL or missing references) ZDO val = companions[0]; float num = Vector3.SqrMagnitude(val.GetPosition() - origin); for (int i = 1; i < companions.Count; i++) { float num2 = Vector3.SqrMagnitude(companions[i].GetPosition() - origin); if (!(num2 >= num)) { num = num2; val = companions[i]; } } return val; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal readonly struct CompanionRequester { internal readonly long Peer; internal readonly long PlayerId; internal readonly string Platform; internal readonly string Name; internal readonly Vector3 Position; internal readonly float Yaw; internal readonly bool HasPosition; internal CompanionRequester(long peer, long playerId, string platform, string name, Vector3 position, float yaw, bool hasPosition) { //IL_0031: 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) Peer = peer; PlayerId = playerId; Platform = platform ?? string.Empty; Name = name ?? string.Empty; Position = position; Yaw = yaw; HasPosition = hasPosition; } internal CompanionRequester At(Vector3 position, float yaw) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) return new CompanionRequester(Peer, PlayerId, Platform, Name, position, yaw, hasPosition: true); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsPeers { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private sealed class Entry { internal long PlayerId; internal string Platform = string.Empty; internal string Name = string.Empty; internal Vector3 Position; } private static readonly Dictionary Cache = new Dictionary(); private static readonly List Stale = new List(); internal static void Reset() { Cache.Clear(); } internal static bool TryResolve(long sender, out CompanionRequester requester) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) requester = default(CompanionRequester); if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null) { return false; } if (sender == ZDOMan.GetSessionID()) { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return false; } long playerID = localPlayer.GetPlayerID(); if (playerID == 0) { return false; } string platformId = CompanionsState.GetPlatformId(localPlayer); string playerName = localPlayer.GetPlayerName(); Vector3 position = ((Component)localPlayer).transform.position; Quaternion rotation = ((Component)localPlayer).transform.rotation; requester = new CompanionRequester(sender, playerID, platformId, playerName, position, ((Quaternion)(ref rotation)).eulerAngles.y, hasPosition: true); return true; } ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer == null) { return false; } if (TryRead(peer, out requester)) { return true; } if (!Cache.TryGetValue(sender, out var value)) { return false; } requester = new CompanionRequester(sender, value.PlayerId, value.Platform, value.Name, value.Position, 0f, hasPosition: false); return true; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static void Refresh(ZNetPeer peer) { if (peer != null) { TryRead(peer, out var _); } } internal static void Update() { if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null) { return; } List peers = ZNet.instance.GetPeers(); for (int i = 0; i < peers.Count; i++) { ZNetPeer val = peers[i]; if (val != null && val.IsReady()) { TryRead(val, out var _); } } Stale.Clear(); foreach (long key in Cache.Keys) { if (ZNet.instance.GetPeer(key) == null) { Stale.Add(key); } } for (int j = 0; j < Stale.Count; j++) { Cache.Remove(Stale[j]); } } private static bool TryRead(ZNetPeer peer, out CompanionRequester requester) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) requester = default(CompanionRequester); if (ZDOMan.instance == null) { return false; } ZDOID characterID = peer.m_characterID; ZDO val = (((ZDOID)(ref characterID)).IsNone() ? null : ZDOMan.instance.GetZDO(characterID)); if (val == null) { return false; } long num = val.GetLong(ZDOVars.s_playerID, 0L); if (num == 0) { return false; } if (!Cache.TryGetValue(peer.m_uid, out var value)) { value = new Entry(); Cache[peer.m_uid] = value; } if (value.PlayerId != num) { value.PlayerId = num; value.Platform = string.Empty; } string platformId = CompanionsState.GetPlatformId(characterID); if (platformId.Length > 0) { value.Platform = platformId; } value.Name = val.GetString(ZDOVars.s_playerName, peer.m_playerName ?? string.Empty) ?? string.Empty; value.Position = val.GetPosition(); long uid = peer.m_uid; string platform = value.Platform; string name = value.Name; Vector3 position = value.Position; Quaternion rotation = val.GetRotation(); requester = new CompanionRequester(uid, num, platform, name, position, ((Quaternion)(ref rotation)).eulerAngles.y, hasPosition: true); return true; } } [HarmonyPatch(typeof(ZNet), "RPC_CharacterID", new Type[] { typeof(ZRpc), typeof(ZDOID) })] internal static class ZNet_RPC_CharacterID_CompanionPeers_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ZNet __instance, ZRpc rpc) { if ((Object)(object)__instance != (Object)null && __instance.IsServer()) { CompanionsPeers.Refresh(__instance.GetPeer(rpc)); } } } internal enum CompanionOp { Summon, Check, Unsummon, DeathDrop, Keep } internal enum CompanionStatus { Ok, NotReady, NotFound, Busy, HasItems, NoItems, SpawnLocal, Moved, Routed, Waiting, Invalid } [Flags] internal enum CompanionMove { Follow = 1, DungeonWait = 2, Effect = 4, Summon = 8, KeepOnly = 0x10 } internal sealed class CompanionRequest { internal int Id; internal CompanionOp Op; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal CompanionDefinition Definition; internal bool Option; internal float Budget; internal float FirstSent; internal float LastSent; internal float RetryAt; } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsNetwork { private const string RequestRpc = "RDC_Companion_Request_v2"; private const string ResponseRpc = "RDC_Companion_Response_v1"; private const string MoveOwnerRpc = "RDC_Companion_MoveOwner_v4"; private const string DestroyOwnerRpc = "RDC_Companion_DestroyOwner_v3"; private const string DeathDropOwnerRpc = "RDC_Companion_DeathDropOwner_v3"; private const string MapPositionsRpc = "RDC_Companion_MapPositions_v1"; private const float ReplyTimeout = 10f; private const float RetryDelay = 1f; private static readonly string[] RpcNames = new string[6] { "RDC_Companion_Request_v2", "RDC_Companion_Response_v1", "RDC_Companion_MoveOwner_v4", "RDC_Companion_DestroyOwner_v3", "RDC_Companion_DeathDropOwner_v3", "RDC_Companion_MapPositions_v1" }; private static readonly Dictionary Pending = new Dictionary(); private static readonly List PendingIds = new List(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static ZRoutedRpc _registeredInstance; private static int _nextRequestId; internal static void Register() { ZRoutedRpc instance = ZRoutedRpc.instance; if (instance != null && instance != _registeredInstance) { Unregister(); RemoveHandlers(instance); instance.Register("RDC_Companion_Request_v2", (Method)RpcServerRequest); instance.Register("RDC_Companion_Response_v1", (Action)RpcClientResponse); instance.Register("RDC_Companion_MoveOwner_v4", (Method)RpcOwnerMove); instance.Register("RDC_Companion_DestroyOwner_v3", (Action)RpcOwnerDestroy); instance.Register("RDC_Companion_DeathDropOwner_v3", (Action)RpcOwnerDeathDrop); instance.Register("RDC_Companion_MapPositions_v1", (Action)RpcClientMapPositions); instance.m_onNewPeer = (Action)Delegate.Combine(instance.m_onNewPeer, new Action(OnNewPeer)); _registeredInstance = instance; } } internal static void Unregister() { ZRoutedRpc registeredInstance = _registeredInstance; _registeredInstance = null; if (registeredInstance != null) { registeredInstance.m_onNewPeer = (Action)Delegate.Remove(registeredInstance.m_onNewPeer, new Action(OnNewPeer)); RemoveHandlers(registeredInstance); } } internal static void Reset() { Pending.Clear(); } internal static int NextRequestId() { _nextRequestId++; if (_nextRequestId <= 0) { _nextRequestId = 1; } return _nextRequestId; } internal static bool IsPending(int requestId) { return requestId != 0 && Pending.ContainsKey(requestId); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool SendRequest(int requestId, CompanionOp op, CompanionDefinition definition, bool option, float budget) { if (requestId <= 0 || !NetworkReady() || GetServerPeer() == 0) { return false; } float time = Time.time; CompanionRequest companionRequest = new CompanionRequest { Id = requestId, Op = op, Definition = definition, Option = option, Budget = budget, FirstSent = time, LastSent = time }; Pending[requestId] = companionRequest; Send(companionRequest); return true; } internal static void Update() { if (Pending.Count == 0) { return; } float time = Time.time; PendingIds.Clear(); PendingIds.AddRange(Pending.Keys); for (int i = 0; i < PendingIds.Count; i++) { if (Pending.TryGetValue(PendingIds[i], out var value)) { if (time - value.FirstSent >= value.Budget || (value.RetryAt <= 0f && time - value.LastSent >= 10f)) { Pending.Remove(value.Id); CompanionsInvoker.OnTimeout(value); } else if (value.RetryAt > 0f && time >= value.RetryAt) { Send(value); } } } } internal static void SendMapPositions(long peer, ZPackage package) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown if (peer == ZDOMan.GetSessionID()) { CompanionsMapIcons.Receive(new ZPackage(package.GetArray())); } else if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.InvokeRoutedRPC(peer, "RDC_Companion_MapPositions_v1", new object[1] { package }); } } internal static bool IsInPeerArea(ZDO zdo, long peer) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return peer != 0L && ZDOMan.instance != null && ZDOMan.instance.IsInPeerActiveArea(zdo.GetPosition(), peer); } internal static bool MoveCompanion(ZDO zdo, CompanionRequester requester, Vector3 position, Quaternion rotation, CompanionMove move) { //IL_0003: 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) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0041: 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) float y = ((Quaternion)(ref rotation)).eulerAngles.y; if (IsSimulated(zdo, out var owner)) { long num = ((owner == requester.Peer) ? 0 : requester.Peer); if (owner == ZDOMan.GetSessionID()) { OwnerMove(zdo.m_uid, position, y, move, num, requester.Name); } else { ZRoutedRpc.instance.InvokeRoutedRPC(owner, "RDC_Companion_MoveOwner_v4", new object[6] { zdo.m_uid, position, y, (int)move, num, requester.Name }); } return true; } ClaimLocal(zdo); WritePlatform(zdo, requester.Platform); WriteMove(zdo, position, rotation, move, requester.Name); HandOff(zdo, requester.Peer, send: true); return false; } internal static void ClaimIdle(ZDO zdo, CompanionRequester requester) { if (!IsSimulated(zdo, out var _)) { ClaimLocal(zdo); WritePlatform(zdo, requester.Platform); HandOff(zdo, requester.Peer, send: true); } } internal static void KeepCompanion(ZDO zdo, CompanionRequester requester) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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_0024: Unknown result type (might be due to invalid IL or missing references) if (IsSimulated(zdo, out var owner)) { if (owner == ZDOMan.GetSessionID()) { OwnerMove(zdo.m_uid, zdo.GetPosition(), 0f, CompanionMove.KeepOnly, 0L, string.Empty); return; } ZRoutedRpc.instance.InvokeRoutedRPC(owner, "RDC_Companion_MoveOwner_v4", new object[6] { zdo.m_uid, zdo.GetPosition(), 0f, 16, 0L, string.Empty }); } else { ClaimLocal(zdo); zdo.Set(CompanionsState.KeptKey, true); HandOff(zdo, requester.Peer, send: false); } } internal static bool DestroyCompanion(ZDO zdo, bool discardItems) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (IsSimulated(zdo, out var owner)) { if (owner == ZDOMan.GetSessionID()) { return OwnerDestroy(zdo.m_uid, discardItems); } ZRoutedRpc.instance.InvokeRoutedRPC(owner, "RDC_Companion_DestroyOwner_v3", new object[2] { zdo.m_uid, discardItems }); return true; } return DestroyStored(zdo, discardItems); } internal static void DeathDropCompanion(ZDO zdo, CompanionRequester requester) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (IsSimulated(zdo, out var owner)) { if (owner == ZDOMan.GetSessionID()) { OwnerDeathDrop(zdo.m_uid); return; } ZRoutedRpc.instance.InvokeRoutedRPC(owner, "RDC_Companion_DeathDropOwner_v3", new object[1] { zdo.m_uid }); } else { ClaimLocal(zdo); CompanionsDeathDrop.DropStoredInventory(zdo); HandOff(zdo, requester.Peer, send: false); } } internal static void MoveLocal(ZNetView view, Vector3 position, Quaternion rotation, CompanionMove move, string followName, bool control) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0053: 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) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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) //IL_00b4: 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) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)view == (Object)null || !view.IsValid()) { return; } Character component = ((Component)view).GetComponent(); if ((Object)(object)component == (Object)null) { return; } ZDO zDO = view.GetZDO(); WriteMove(zDO, position, rotation, move, followName); ((Component)component).transform.SetPositionAndRotation(position, rotation); Rigidbody component2 = ((Component)component).GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.position = position; component2.rotation = rotation; component2.linearVelocity = Vector3.zero; component2.angularVelocity = Vector3.zero; } if (!control) { return; } if ((move & CompanionMove.Follow) == 0) { CompanionsFlight.Stay(component, position - Vector3.up * CompanionsFlight.Height); return; } Player val = CompanionsState.FindOwner(zDO); if ((Object)(object)val != (Object)null) { CompanionsFlight.FollowOwner(component, val); } } internal static bool DestroyLocal(ZNetView view, bool discardItems) { //IL_0080: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)view == (Object)null || !view.IsValid() || (Object)(object)ZNetScene.instance == (Object)null) { return true; } ZDO zDO = view.GetZDO(); if (!discardItems && CompanionsState.HasStoredItems(zDO)) { return false; } if (!view.IsOwner()) { view.ClaimOwnership(); } if (discardItems) { CompanionsState.ClearStoredItems(zDO); } CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(zDO); if (companionDefinition != null) { CompanionsAssets.SpawnBirthEffect(((Component)view).transform.position, companionDefinition); } ZNetScene.instance.Destroy(((Component)view).gameObject); return true; } private static void OnNewPeer(long peer) { CompanionsInvoker.ProcessPendingSummon(); } private static void RemoveHandlers(ZRoutedRpc rpc) { for (int i = 0; i < RpcNames.Length; i++) { rpc.m_functions.Remove(StringExtensionMethods.GetStableHashCode(RpcNames[i])); } } private static bool NetworkReady() { if ((Object)(object)ZNet.instance == (Object)null || ZRoutedRpc.instance == null) { return false; } Register(); return true; } private static long GetServerPeer() { return (ZRoutedRpc.instance != null) ? ZRoutedRpc.instance.GetServerPeerID() : 0; } private static bool IsServerSender(long sender) { return ZRoutedRpc.instance != null && sender == ZRoutedRpc.instance.GetServerPeerID(); } private static void Send(CompanionRequest request) { request.LastSent = Time.time; request.RetryAt = 0f; long serverPeer = GetServerPeer(); if (serverPeer == 0) { request.RetryAt = Time.time + 1f; return; } ZRoutedRpc.instance.InvokeRoutedRPC(serverPeer, "RDC_Companion_Request_v2", new object[5] { (int)request.Op, (request.Definition != null) ? request.Definition.CompanionPrefab : string.Empty, request.Option, request.Id, WriteOrigin() }); } private static ZPackage WriteOrigin() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); Player localPlayer = Player.m_localPlayer; val.Write((Object)(object)localPlayer != (Object)null); if ((Object)(object)localPlayer == (Object)null) { return val; } val.Write(((Component)localPlayer).transform.position); Quaternion rotation = ((Component)localPlayer).transform.rotation; val.Write(((Quaternion)(ref rotation)).eulerAngles.y); return val; } private static bool IsSimulated(ZDO zdo, out long owner) { owner = zdo.GetOwner(); return IsInPeerArea(zdo, owner) && !IsStaleSession(zdo, owner); } private static bool IsStaleSession(ZDO zdo, long owner) { if (owner == ZDOMan.GetSessionID()) { return false; } long num = zdo.GetLong(CompanionsState.OwnerKey, 0L); if (num == 0L || GetPeerPlayerId(ZNet.instance.GetPeer(owner)) != num) { return false; } List peers = ZNet.instance.GetPeers(); for (int i = 0; i < peers.Count; i++) { ZNetPeer val = peers[i]; if (val != null && val.m_uid != owner && GetPeerPlayerId(val) == num) { return true; } } return false; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static long GetPeerPlayerId(ZNetPeer peer) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (peer == null || ((ZDOID)(ref peer.m_characterID)).IsNone()) { return 0L; } ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); return (zDO != null) ? zDO.GetLong(ZDOVars.s_playerID, 0L) : 0; } private static bool DestroyStored(ZDO zdo, bool discardItems) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (!discardItems && CompanionsState.HasStoredItems(zdo)) { return false; } ClaimLocal(zdo); if (discardItems) { CompanionsState.ClearStoredItems(zdo); } CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(zdo); if (companionDefinition != null) { CompanionsAssets.SpawnBirthEffect(zdo.GetPosition(), companionDefinition); } ZDOMan.instance.DestroyZDO(zdo); return true; } private static void ClaimLocal(ZDO zdo) { if (!zdo.IsOwner()) { zdo.SetOwner(ZDOMan.GetSessionID()); } } private static void HandOff(ZDO zdo, long peer, bool send) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (peer != 0L && peer != ZDOMan.GetSessionID()) { zdo.SetOwner(peer); if (send && CompanionsState.IsServer && ZDOMan.instance != null) { ZDOMan.instance.ForceSendZDO(peer, zdo.m_uid); } } } private static void WritePlatform(ZDO zdo, string platform) { long playerId = zdo.GetLong(CompanionsState.OwnerKey, 0L); CompanionsState.RefreshPlatform(zdo, CompanionsState.OwnerKey, CompanionsState.OwnerPlatformKey, playerId, platform); } private static void WriteMove(ZDO zdo, Vector3 position, Quaternion rotation, CompanionMove move, string followName) { //IL_004a: 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_0088: 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) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) zdo.Set(CompanionsFlight.DungeonWaitKey, (move & CompanionMove.DungeonWait) != 0); if (CompanionsCatchUp.IsLeftBehind(zdo)) { zdo.Set(CompanionsCatchUp.LeftBehindKey, false); } if ((move & CompanionMove.Summon) != 0 && CompanionsState.IsKept(zdo)) { zdo.Set(CompanionsState.KeptKey, false); } zdo.SetPosition(position); zdo.SetRotation(rotation); if ((move & CompanionMove.Follow) != 0) { if (followName.Length > 0) { zdo.Set(ZDOVars.s_follow, followName); } } else { zdo.Set(CompanionsFlight.StayBaseKey, position - Vector3.up * CompanionsFlight.Height); zdo.Set(CompanionsFlight.HasStayKey, true); zdo.Set(ZDOVars.s_follow, string.Empty); } } private static void OwnerMove(ZDOID id, Vector3 position, float yaw, CompanionMove move, long newOwner, string followName) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) ZDO val = CompanionsState.FindZdo(id); if (val == null || !CompanionsState.IsCompanion(val)) { return; } ZNetView val2 = CompanionsState.FindInstance(val); bool flag = (Object)(object)val2 != (Object)null && val2.IsValid(); if (!flag) { ClaimLocal(val); } else if (!val2.IsOwner()) { val2.ClaimOwnership(); } if ((move & CompanionMove.KeepOnly) != 0) { val.Set(CompanionsState.KeptKey, true); return; } bool flag2 = newOwner == 0L || newOwner == ZDOMan.GetSessionID(); if (flag2 && (move & CompanionMove.Follow) != 0) { position = RaiseForLocalOwner(val, position); } Quaternion rotation = Quaternion.Euler(0f, yaw, 0f); if (flag) { MoveLocal(val2, position, rotation, move, followName, flag2); } else { WriteMove(val, position, rotation, move, followName); } if ((move & CompanionMove.Effect) != 0) { CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(val); if (companionDefinition != null) { CompanionsAssets.SpawnBirthEffect(position, companionDefinition); } } if (!flag2) { HandOff(val, newOwner, send: true); } } private static Vector3 RaiseForLocalOwner(ZDO zdo, Vector3 position) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; return ((Object)(object)localPlayer != (Object)null && CompanionsState.MatchesOwner(zdo, localPlayer.GetPlayerID(), CompanionsState.GetPlatformId(localPlayer))) ? CompanionsFlight.RaiseForShip(localPlayer, position) : position; } private static bool OwnerDestroy(ZDOID id, bool discardItems) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ZDO val = CompanionsState.FindZdo(id); if (val == null || !CompanionsState.IsCompanion(val)) { return true; } ZNetView val2 = CompanionsState.FindInstance(val); return ((Object)(object)val2 != (Object)null && val2.IsValid()) ? DestroyLocal(val2, discardItems) : DestroyStored(val, discardItems); } private static void OwnerDeathDrop(ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) ZDO val = CompanionsState.FindZdo(id); if (val == null || !CompanionsState.IsCompanion(val)) { return; } ZNetView val2 = CompanionsState.FindInstance(val); if ((Object)(object)val2 != (Object)null && val2.IsValid()) { if (!val2.IsOwner()) { val2.ClaimOwnership(); } Container componentInChildren = ((Component)val2).GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { CompanionsDeathDrop.DropInventory(componentInChildren, ((Component)val2).transform.position); } } else { ClaimLocal(val); CompanionsDeathDrop.DropStoredInventory(val); } } private static void RpcServerRequest(long sender, int op, string prefabName, bool option, int requestId, ZPackage origin) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (CompanionsState.IsServer && ZRoutedRpc.instance != null) { ZPackage val = new ZPackage(); CompanionStatus companionStatus = (Enum.IsDefined(typeof(CompanionOp), op) ? CompanionsLifecycle.HandleRequest(sender, (CompanionOp)op, prefabName ?? string.Empty, option, origin, val) : CompanionStatus.Invalid); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "RDC_Companion_Response_v1", new object[3] { requestId, (int)companionStatus, val }); } } private static void RpcClientResponse(long sender, int requestId, int status, ZPackage data) { if (!IsServerSender(sender) || !Pending.TryGetValue(requestId, out var value)) { return; } if ((status == 1 || status == 3) ? true : false) { float time = Time.time; if (time + 1f - value.FirstSent < value.Budget) { value.RetryAt = time + 1f; return; } Pending.Remove(requestId); CompanionsInvoker.OnTimeout(value); } else { Pending.Remove(requestId); CompanionsInvoker.OnResponse(value, (CompanionStatus)status, data); } } private static void RpcClientMapPositions(long sender, ZPackage package) { if (IsServerSender(sender)) { CompanionsMapIcons.Receive(package); } } private static void RpcOwnerMove(long sender, ZDOID id, Vector3 position, float yaw, int flags, long newOwner, string followName) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (IsServerSender(sender)) { OwnerMove(id, position, yaw, (CompanionMove)flags, newOwner, followName ?? string.Empty); } } private static void RpcOwnerDestroy(long sender, ZDOID id, bool discardItems) { //IL_0009: 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) if (IsServerSender(sender) && !OwnerDestroy(id, discardItems)) { ZDO zdo = CompanionsState.FindZdo(id); Player localPlayer = Player.m_localPlayer; CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(zdo); if ((Object)(object)localPlayer != (Object)null && companionDefinition != null && CompanionsState.MatchesOwner(zdo, localPlayer.GetPlayerID(), CompanionsState.GetPlatformId(localPlayer))) { CompanionsInvoker.OnUnsummonRefused(companionDefinition); } } } private static void RpcOwnerDeathDrop(long sender, ZDOID id) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (IsServerSender(sender)) { OwnerDeathDrop(id); } } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class ZNet_Awake_CompanionNetwork_Patch { private static void Postfix() { CompanionsTracker.Reset(); CompanionsCatchUp.Reset(); CompanionsNetwork.Reset(); CompanionsNetwork.Register(); CompanionsInvoker.ProcessPendingSummon(); } } [HarmonyPatch(typeof(ZNet), "Update")] internal static class ZNet_Update_CompanionRequests_Patch { private static void Postfix() { CompanionsNetwork.Update(); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] internal static class ZNetScene_Awake_CompanionReadiness_Patch { private static void Postfix() { CompanionsInvoker.ProcessPendingSummon(); } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsState { private const char PlatformSeparator = '_'; internal static readonly int OwnerKey = StringExtensionMethods.GetStableHashCode("comp.owner"); internal static readonly int CompanionKey = StringExtensionMethods.GetStableHashCode("comp.isCompanion"); internal static readonly int OwnerPlatformKey = StringExtensionMethods.GetStableHashCode("comp.ownerPlatform"); internal static readonly int KeptKey = StringExtensionMethods.GetStableHashCode("comp.kept"); private static int _localPlatformFrame = -1; private static string _localPlatform = string.Empty; internal static bool IsServer => (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer(); [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool IsCompanion(GameObject gameObject) { CompanionIdentity companionIdentity = default(CompanionIdentity); return (Object)(object)gameObject != (Object)null && gameObject.TryGetComponent(ref companionIdentity); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool IsCompanion(ZDO zdo) { return zdo != null && CompanionsRegistry.ForCompanion(zdo) != null && (zdo.GetInt(CompanionKey, 0) == 1 || zdo.GetLong(OwnerKey, 0L) != 0); } internal static bool IsKept(ZDO zdo) { return zdo.GetBool(KeptKey, false); } internal unsafe static string GetPlatformId(ZDOID characterId) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //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) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || ((ZDOID)(ref characterId)).IsNone()) { return string.Empty; } List playerList = ZNet.instance.GetPlayerList(); for (int i = 0; i < playerList.Count; i++) { if (playerList[i].m_characterID == characterId) { PlatformUserID id = playerList[i].m_userInfo.m_id; return ((PlatformUserID)(ref id)).IsValid ? ((object)(*(PlatformUserID*)(&id))/*cast due to .constrained prefix*/).ToString() : string.Empty; } } return string.Empty; } internal static string GetPlatformId([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] Player player) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null) { return string.Empty; } if ((Object)(object)player != (Object)(object)Player.m_localPlayer) { return GetPlatformId(((Character)player).GetZDOID()); } if (_localPlatformFrame != Time.frameCount) { _localPlatformFrame = Time.frameCount; _localPlatform = GetPlatformId(((Character)player).GetZDOID()); } return _localPlatform; } internal static bool PlatformMatches(ZDO zdo, int key, string platform) { string text = zdo.GetString(key, string.Empty); return !SamePlatform(text, platform) || text == platform; } internal static bool MatchesOwner([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] ZDO zdo, int ownerKey, int platformKey, long playerId, string platform) { return zdo != null && playerId != 0L && zdo.GetLong(ownerKey, 0L) == playerId && PlatformMatches(zdo, platformKey, platform); } internal static bool MatchesOwner([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] ZDO zdo, long playerId, string platform) { return MatchesOwner(zdo, OwnerKey, OwnerPlatformKey, playerId, platform); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool IsOwner(Humanoid humanoid, ZNetView view) { Player val = (Player)(object)((humanoid is Player) ? humanoid : null); if (val == null || (Object)(object)view == (Object)null || !view.IsValid()) { return false; } return MatchesOwner(view.GetZDO(), val.GetPlayerID(), GetPlatformId(val)); } internal static void RefreshPlatform(ZDO zdo, int ownerKey, int platformKey, long playerId, string platform) { if (zdo.IsOwner() && playerId != 0L && platform.Length != 0 && zdo.GetLong(ownerKey, 0L) == playerId) { string text = zdo.GetString(platformKey, string.Empty); if (text != platform && !SamePlatform(text, platform)) { zdo.Set(platformKey, platform); } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static Player FindOwner(ZDO zdo) { if (zdo == null) { return null; } long num = zdo.GetLong(OwnerKey, 0L); if (num == 0) { return null; } List allPlayers = Player.GetAllPlayers(); for (int i = 0; i < allPlayers.Count; i++) { Player val = allPlayers[i]; if ((Object)(object)val != (Object)null && val.GetPlayerID() == num && PlatformMatches(zdo, OwnerPlatformKey, GetPlatformId(val))) { return val; } } return null; } internal static void CollectLoaded(Player owner, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] CompanionDefinition definition, List result) { result.Clear(); if ((Object)(object)owner == (Object)null) { return; } List allCharacters = Character.GetAllCharacters(); CompanionIdentity companionIdentity = default(CompanionIdentity); for (int i = 0; i < allCharacters.Count; i++) { Character val = allCharacters[i]; if ((Object)(object)val == (Object)null || !((Component)val).TryGetComponent(ref companionIdentity)) { continue; } ZNetView component = ((Component)val).GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid()) { CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(component.GetZDO()); if (companionDefinition != null && (definition == null || companionDefinition == definition) && IsOwner((Humanoid)(object)owner, component)) { result.Add(component); } } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static ZNetView FindInstance(ZDO zdo) { if (zdo == null || (Object)(object)ZNetScene.instance == (Object)null) { return null; } return ZNetScene.instance.FindInstance(zdo); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static ZDO FindZdo(ZDOID id) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) return (ZDOMan.instance != null) ? ZDOMan.instance.GetZDO(id) : null; } internal static void MarkOwned(GameObject instance, Player owner, string platform) { if ((Object)(object)instance == (Object)null || (Object)(object)owner == (Object)null) { return; } ZNetView component = instance.GetComponent(); if (!((Object)(object)component == (Object)null) && component.IsValid() && component.IsOwner()) { ZDO zDO = component.GetZDO(); zDO.Set(CompanionKey, 1, false); zDO.Set(OwnerKey, owner.GetPlayerID()); if (platform.Length > 0) { zDO.Set(OwnerPlatformKey, platform); } zDO.Set(ZDOVars.s_follow, owner.GetPlayerName()); zDO.Set(ZDOVars.s_sleeping, false); } } internal static bool HasStoredItems(List companions) { for (int i = 0; i < companions.Count; i++) { if (HasStoredItems(companions[i])) { return true; } } return false; } internal static bool HasStoredItems(ZDO zdo) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected O, but got Unknown ZNetView val = FindInstance(zdo); if ((Object)(object)val != (Object)null) { Container component = ((Component)val).GetComponent(); Inventory val2 = (((Object)(object)component != (Object)null) ? component.GetInventory() : null); if (val2 != null) { return val2.NrOfItems() > 0; } } byte[] byteArray = zdo.GetByteArray(ZDOVars.s_items, (byte[])null); if (byteArray == null || byteArray.Length == 0) { return false; } try { Inventory val3 = new Inventory(true); val3.Load(new ZPackage(byteArray)); return val3.NrOfItems() > 0; } catch { return true; } } internal static void ClearStoredItems(ZDO zdo) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown ZNetView val = FindInstance(zdo); if ((Object)(object)val != (Object)null) { Container component = ((Component)val).GetComponent(); Inventory val2 = (((Object)(object)component != (Object)null) ? component.GetInventory() : null); if (val2 != null) { val2.RemoveAll(); return; } } Inventory val3 = new Inventory(true); ZPackage val4 = new ZPackage(); val3.Save(val4); zdo.Set(ZDOVars.s_items, val4.GetArray()); } private static bool SamePlatform(string first, string second) { int num = first.IndexOf('_'); return num > 0 && num < second.Length && second[num] == '_' && string.CompareOrdinal(first, 0, second, 0, num) == 0; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal static class CompanionsTracker { private const float TickInterval = 1f; private const int ScanStepsPerFrame = 4; private const float ReservationSeconds = 10f; private static readonly int CargoCrateHash = StringExtensionMethods.GetStableHashCode("RDC_CargoCrate"); private static readonly HashSet Known = new HashSet(); private static readonly Dictionary> ByOwner = new Dictionary>(); private static readonly HashSet KnownCrates = new HashSet(); private static readonly Dictionary> CratesByOwner = new Dictionary>(); private static readonly List MapBuffer = new List(); private static readonly List OwnedBuffer = new List(); private static readonly List CrateBuffer = new List(); private static readonly List ScanBuffer = new List(); private static readonly ZPackage MapPackage = new ZPackage(); private static readonly Dictionary LastMapCount = new Dictionary(); private static readonly Dictionary FarTicks = new Dictionary(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 0 })] private static readonly Dictionary<(long, int), float> Reservations = new Dictionary<(long, int), float>(); private static readonly List Stale = new List(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] private static string[] _scanPrefabs; private static int _scanPrefab; private static int _scanIndex; private static bool _indexReady; private static float _nextTick; internal static bool IndexReady => _indexReady; internal static bool IsTracked(int prefabHash) { return CompanionsRegistry.ForCompanion(prefabHash) != null || IsCrate(prefabHash); } private static bool IsCrate(int prefabHash) { return prefabHash == CargoCrateHash; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static void Observe(ZDO zdo) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) if (zdo == null || !CompanionsState.IsServer) { return; } int prefab = zdo.GetPrefab(); if (CompanionsRegistry.ForCompanion(prefab) != null) { Known.Add(zdo.m_uid); long num = zdo.GetLong(CompanionsState.OwnerKey, 0L); if (num != 0) { Reservations.Remove((num, prefab)); } } else if (IsCrate(prefab) && zdo.GetLong(CompanionsContainer.CargoOwnerKey, 0L) != 0) { KnownCrates.Add(zdo.m_uid); } } internal static void Forget(ZDOID id) { //IL_0006: 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_001e: Unknown result type (might be due to invalid IL or missing references) Known.Remove(id); KnownCrates.Remove(id); FarTicks.Remove(id); } internal static List GetOwned(long playerId, string platform, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] CompanionDefinition definition) { //IL_002d: 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_003a: Unknown result type (might be due to invalid IL or missing references) List list = new List(); if (playerId == 0L || ZDOMan.instance == null) { return list; } foreach (ZDOID item in Known) { ZDO zDO = ZDOMan.instance.GetZDO(item); if (CompanionsState.IsCompanion(zDO) && (definition == null || CompanionsRegistry.ForCompanion(zDO) == definition) && CompanionsState.MatchesOwner(zDO, playerId, platform)) { list.Add(zDO); } } return list; } internal static bool TryReserve(long playerId, CompanionDefinition definition) { (long, int) key = (playerId, StringExtensionMethods.GetStableHashCode(definition.CompanionPrefab)); float time = Time.time; if (Reservations.TryGetValue(key, out var value) && time < value) { return false; } Reservations[key] = time + 10f; return true; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] private static List FilterByAccount([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] List source, int key, string platform, List buffer) { if (source == null) { return null; } buffer.Clear(); for (int i = 0; i < source.Count; i++) { if (CompanionsState.PlatformMatches(source[i], key, platform)) { buffer.Add(source[i]); } } return buffer; } internal static void Reset() { Known.Clear(); KnownCrates.Clear(); CratesByOwner.Clear(); LastMapCount.Clear(); ByOwner.Clear(); FarTicks.Clear(); Reservations.Clear(); ScanBuffer.Clear(); _scanPrefab = 0; _scanIndex = 0; _indexReady = false; _nextTick = 0f; CompanionsPeers.Reset(); } private static string[] GetScanPrefabs() { if (_scanPrefabs != null) { return _scanPrefabs; } List list = new List(); for (int i = 0; i < CompanionsRegistry.All.Length; i++) { list.Add(CompanionsRegistry.All[i].CompanionPrefab); } list.Add("RDC_CargoCrate"); _scanPrefabs = list.ToArray(); return _scanPrefabs; } private static void ScanStep() { if (_indexReady) { return; } string[] scanPrefabs = GetScanPrefabs(); for (int i = 0; i < 4; i++) { if (_indexReady) { break; } if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(scanPrefabs[_scanPrefab], ScanBuffer, ref _scanIndex)) { for (int j = 0; j < ScanBuffer.Count; j++) { Observe(ScanBuffer[j]); } ScanBuffer.Clear(); _scanIndex = 0; _scanPrefab++; if (_scanPrefab >= scanPrefabs.Length) { _indexReady = true; } } } } internal static void Update() { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) if (!CompanionsState.IsServer || ZDOMan.instance == null || (Object)(object)ZNet.instance == (Object)null) { return; } ScanStep(); float time = Time.time; if (time < _nextTick) { return; } _nextTick = time + 1f; CompanionsPeers.Update(); GroupByOwner(); bool flag = CompanionsPlugin.ShowMapIcon?.Value ?? true; bool enabled = CompanionsCatchUp.Enabled; float distance = CompanionsCatchUp.Distance; List allCharacterZDOS = ZNet.instance.GetAllCharacterZDOS(); for (int i = 0; i < allCharacterZDOS.Count; i++) { ZDO val = allCharacterZDOS[i]; long num = val.GetLong(ZDOVars.s_playerID, 0L); if (num != 0) { string platformId = CompanionsState.GetPlatformId(val.m_uid); ByOwner.TryGetValue(num, out var value); List list = FilterByAccount(value, CompanionsState.OwnerPlatformKey, platformId, OwnedBuffer); if (enabled && list != null && list.Count > 0 && !CompanionsCatchUp.IsSuppressed(val)) { CatchUp(val, num, platformId, list, distance); } MapBuffer.Clear(); if (flag && list != null) { MapBuffer.AddRange(list); } CratesByOwner.TryGetValue(num, out var value2); List list2 = FilterByAccount(value2, CompanionsContainer.CargoOwnerPlatformKey, platformId, CrateBuffer); if (list2 != null) { MapBuffer.AddRange(list2); } LastMapCount.TryGetValue(num, out var value3); if (MapBuffer.Count != 0 || value3 != 0) { LastMapCount[num] = MapBuffer.Count; SendMap(val, MapBuffer); } } } } private static void AddToGroup(Dictionary> groups, long owner, ZDO zdo) { if (!groups.TryGetValue(owner, out var value)) { value = (groups[owner] = new List()); } value.Add(zdo); } private static void ClearGroups(Dictionary> groups) { foreach (List value in groups.Values) { value.Clear(); } } private static void GroupByOwner() { //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) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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_00b3: Unknown result type (might be due to invalid IL or missing references) //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_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0140: 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) ClearGroups(ByOwner); Stale.Clear(); foreach (ZDOID item in Known) { ZDO zDO = ZDOMan.instance.GetZDO(item); if (!CompanionsState.IsCompanion(zDO)) { Stale.Add(item); } else { AddToGroup(ByOwner, zDO.GetLong(CompanionsState.OwnerKey, 0L), zDO); } } for (int i = 0; i < Stale.Count; i++) { Known.Remove(Stale[i]); FarTicks.Remove(Stale[i]); } ClearGroups(CratesByOwner); Stale.Clear(); foreach (ZDOID knownCrate in KnownCrates) { ZDO zDO2 = ZDOMan.instance.GetZDO(knownCrate); long num = ((zDO2 != null) ? zDO2.GetLong(CompanionsContainer.CargoOwnerKey, 0L) : 0); if (num == 0) { Stale.Add(knownCrate); } else { AddToGroup(CratesByOwner, num, zDO2); } } for (int j = 0; j < Stale.Count; j++) { KnownCrates.Remove(Stale[j]); } } private static void CatchUp(ZDO character, long playerId, string platform, List companions, float maxDistance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_0035: 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_0062: 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) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) Vector3 position = character.GetPosition(); Quaternion rotation = character.GetRotation(); bool flag = Character.InInterior(position); long owner = character.GetOwner(); CompanionRequester requester = new CompanionRequester(owner, playerId, platform, character.GetString(ZDOVars.s_playerName, string.Empty), position, ((Quaternion)(ref rotation)).eulerAngles.y, hasPosition: true); int num = 0; for (int i = 0; i < companions.Count; i++) { ZDO val = companions[i]; Vector3 position2 = val.GetPosition(); float distance = Vector3.Distance(position2, position); bool sameSide = Character.InInterior(position2) == flag; if (CompanionsNetwork.IsInPeerArea(val, owner) || !CompanionsCatchUp.IsEligible(val, sameSide, distance, maxDistance)) { FarTicks.Remove(val.m_uid); continue; } FarTicks.TryGetValue(val.m_uid, out var value); if (++value < 2) { FarTicks[val.m_uid] = value; continue; } FarTicks.Remove(val.m_uid); Vector3 arrivalPosition = CompanionsFlight.GetArrivalPosition(position, CompanionsLifecycle.GetTeleportOffset(num++)); CompanionsNetwork.MoveCompanion(val, requester, arrivalPosition, rotation, CompanionMove.Follow | CompanionMove.Effect); } } private static void SendMap(ZDO character, List entries) { //IL_0042: 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) long owner = character.GetOwner(); if (owner != 0) { MapPackage.Clear(); MapPackage.Write(entries.Count); for (int i = 0; i < entries.Count; i++) { ZDO val = entries[i]; MapPackage.Write(val.m_uid); MapPackage.Write(val.GetPrefab()); MapPackage.Write(val.GetPosition()); } CompanionsNetwork.SendMapPositions(owner, MapPackage); } } } [HarmonyPatch(typeof(ZNet), "Update")] internal static class ZNet_Update_CompanionTracker_Patch { private static void Postfix() { CompanionsTracker.Update(); } } [HarmonyPatch(typeof(ZDOMan), "CreateNewZDO", new Type[] { typeof(ZDOID), typeof(Vector3), typeof(int) })] internal static class ZDOMan_CreateNewZDO_CompanionIndex_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ZDO __result) { if (__result != null && CompanionsTracker.IsTracked(__result.GetPrefab())) { CompanionsTracker.Observe(__result); } } } [HarmonyPatch(typeof(ZDOMan), "HandleDestroyedZDO", new Type[] { typeof(ZDOID) })] internal static class ZDOMan_HandleDestroyedZDO_CompanionIndex_Patch { private static void Postfix(ZDOID uid) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (CompanionsState.IsServer) { CompanionsTracker.Forget(uid); } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsAssets { private const string BundleName = "rd_comp"; internal const string CargoCratePrefab = "RDC_CargoCrate"; internal const string BirthEffectPrefab = "fx_companion_birth_rd_comp"; private const string SawDustPrefab = "vfx_SawDust_rd_comp"; private const string FlapSoundPrefab = "sfx_companion_flap_rd_comp"; private const string IdleSoundPrefab = "sfx_companion_idle_rd_comp"; private const string DeathMapIconName = "mapicon_death_pet"; private const string MapIconPrefix = "map_ico_pet_"; private static readonly Dictionary MapIcons = new Dictionary(); internal static AssetBundle Bundle { get; private set; } = null; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] [field: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal static Sprite DeathMapIcon { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] get; [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private set; } internal static bool HasCargoCrate { get; private set; } internal static bool LoadBundle(out string error) { Assembly assembly = typeof(CompanionsAssets).Assembly; string text = assembly.GetName().Name + ".assets.rd_comp"; if (assembly.GetManifestResourceInfo(text) == null) { error = "Embedded asset bundle '" + text + "' was not found. The mod was not loaded."; return false; } AssetBundle val = PrefabManager.RegisterAssetBundle("rd_comp"); if ((Object)(object)val == (Object)null) { error = "Asset bundle 'rd_comp' could not be loaded. The mod was not loaded."; return false; } List list = new List(); CompanionDefinition[] all = CompanionsRegistry.All; foreach (CompanionDefinition companionDefinition in all) { RequireAsset(val, companionDefinition.CompanionPrefab, list); RequireAsset(val, companionDefinition.InvokerPrefab, list); RequireAsset(val, companionDefinition.BirthEffectPrefab, list); } RequireAsset(val, "sfx_companion_flap_rd_comp", list); RequireAsset(val, "sfx_companion_idle_rd_comp", list); if (list.Count > 0) { error = "Asset bundle 'rd_comp' is missing: " + string.Join(", ", list) + ". The mod was not loaded."; return false; } Bundle = val; error = string.Empty; return true; } internal static void Register() { CompanionDefinition[] all = CompanionsRegistry.All; foreach (CompanionDefinition definition in all) { RegisterCompanion(definition); } PrefabManager.RegisterPrefab(Bundle, "sfx_companion_flap_rd_comp"); PrefabManager.RegisterPrefab(Bundle, "sfx_companion_idle_rd_comp"); HasCargoCrate = RegisterCargoCrate(); RegisterOptional("vfx_SawDust_rd_comp"); DeathMapIcon = LoadMapIcon("mapicon_death_pet"); MapIcons.Clear(); CompanionDefinition[] all2 = CompanionsRegistry.All; foreach (CompanionDefinition companionDefinition in all2) { Sprite val = LoadMapIcon("map_ico_pet_" + companionDefinition.Id); if ((Object)(object)val != (Object)null) { MapIcons[companionDefinition.Id] = val; } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static Sprite GetMapIcon(CompanionDefinition definition) { Sprite value; return (definition != null && MapIcons.TryGetValue(definition.Id, out value)) ? value : null; } internal static void SpawnBirthEffect(Vector3 position, CompanionDefinition definition) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0061: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ZNetScene.instance == (Object)null) && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsDedicated() && ZNetScene.InActiveArea(position, ZNet.instance.GetReferencePosition())) { GameObject prefab = ZNetScene.instance.GetPrefab(definition.BirthEffectPrefab); if ((Object)(object)prefab != (Object)null) { Object.Instantiate(prefab, position, Quaternion.identity); } } } private static void RequireAsset(AssetBundle bundle, string name, List missing) { if (!missing.Contains(name) && (Object)(object)bundle.LoadAsset(name) == (Object)null) { missing.Add(name); } } private static void RegisterCompanion(CompanionDefinition definition) { //IL_0097: 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) GameObject val = Bundle.LoadAsset(definition.CompanionPrefab); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("The companion prefab could not be loaded: " + definition.CompanionPrefab); } CompanionsCreature.Configure(val, definition); PrefabManager.RegisterPrefab(val); PrefabManager.RegisterPrefab(Bundle, definition.BirthEffectPrefab); Item item = new Item(Bundle, definition.InvokerPrefab); ItemDrop component = item.Prefab.GetComponent(); if ((Object)(object)component == (Object)null) { throw new MissingComponentException("ItemDrop"); } component.m_itemData.m_shared.m_itemType = (ItemType)16; component.m_itemData.m_shared.m_maxStackSize = 1; component.m_itemData.m_shared.m_name = definition.InvokerNameToken; component.m_itemData.m_shared.m_description = definition.InvokerDescriptionToken; component.m_itemData.m_shared.m_equipStatusEffect = null; CompanionsRegistry.BindInvoker(definition, item.Prefab); item.Crafting.Add(definition.CraftingStation, definition.CraftingStationLevel); for (int i = 0; i < definition.Recipe.Length; i++) { var (itemName, amount) = definition.Recipe[i]; item.RequiredItems.Add(itemName, amount); } MaterialReplacer.RegisterGameObjectForShaderSwap(item.Prefab, MaterialReplacer.ShaderType.UseUnityShader); } private static bool RegisterCargoCrate() { GameObject val = Bundle.LoadAsset("RDC_CargoCrate"); if ((Object)(object)val == (Object)null) { return false; } Container[] componentsInChildren = val.GetComponentsInChildren(true); foreach (Container val2 in componentsInChildren) { val2.m_name = "$companions_cargo_name"; } PrefabManager.RegisterPrefab(val); return true; } private static void RegisterOptional(string prefabName) { GameObject val = Bundle.LoadAsset(prefabName); if ((Object)(object)val != (Object)null) { PrefabManager.RegisterPrefab(val); } } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Sprite LoadMapIcon(string assetName) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) Sprite val = Bundle.LoadAsset(assetName); if ((Object)(object)val != (Object)null) { return val; } Texture2D val2 = Bundle.LoadAsset(assetName); return ((Object)(object)val2 != (Object)null) ? Sprite.Create(val2, new Rect(0f, 0f, (float)((Texture)val2).width, (float)((Texture)val2).height), new Vector2(0.5f, 0.5f)) : null; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal sealed class CompanionDefinition { internal readonly string Id; internal readonly string CompanionPrefab; internal readonly string InvokerPrefab; internal readonly string BirthEffectPrefab; internal readonly string InvokerNameToken; internal readonly string InvokerDescriptionToken; internal readonly string CompanionNameToken; internal readonly int DefaultContainerWidth; internal readonly int DefaultContainerHeight; internal readonly CraftingTable CraftingStation; internal readonly int CraftingStationLevel; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 0, 1 })] internal readonly (string Prefab, int Amount)[] Recipe; internal int ContainerWidth; internal int ContainerHeight; internal CompanionDefinition(string id, string companionPrefab, string invokerPrefab, string birthEffectPrefab, string invokerNameToken, string invokerDescriptionToken, string companionNameToken, int defaultContainerWidth, int defaultContainerHeight, CraftingTable craftingStation, int craftingStationLevel, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 0, 1 })] params (string Prefab, int Amount)[] recipe) { Id = id; CompanionPrefab = companionPrefab; InvokerPrefab = invokerPrefab; BirthEffectPrefab = birthEffectPrefab; InvokerNameToken = invokerNameToken; InvokerDescriptionToken = invokerDescriptionToken; CompanionNameToken = companionNameToken; DefaultContainerWidth = defaultContainerWidth; DefaultContainerHeight = defaultContainerHeight; ContainerWidth = defaultContainerWidth; ContainerHeight = defaultContainerHeight; CraftingStation = craftingStation; CraftingStationLevel = craftingStationLevel; Recipe = recipe; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsRegistry { private static readonly CompanionDefinition Companion01; private static readonly CompanionDefinition Companion02; private static readonly CompanionDefinition Companion03; internal static readonly CompanionDefinition[] All; private static readonly Dictionary ByInvokerToken; private static readonly Dictionary ByInvokerObject; private static readonly Dictionary ByCompanionPrefab; private static readonly Dictionary ByCompanionHash; static CompanionsRegistry() { Companion01 = new CompanionDefinition("01", "RDC_companion_01", "RDC_invoke_pet_01", "fx_companion_birth_rd_comp", "$companions_item_invoker_01_name", "$companions_item_invoker_01_description", "$companions_pet_01_name", 3, 2, CraftingTable.Forge, 1, ("SurtlingCore", 25), ("TrophyEikthyr", 10), ("Bronze", 25)); Companion02 = new CompanionDefinition("02", "RDC_companion_02", "RDC_invoke_pet_02", "fx_companion_birth_rd_comp", "$companions_item_invoker_02_name", "$companions_item_invoker_02_description", "$companions_pet_02_name", 3, 3, CraftingTable.Forge, 1, ("SurtlingCore", 25), ("TrophyTheElder", 10), ("Iron", 50)); Companion03 = new CompanionDefinition("03", "RDC_companion_03", "RDC_invoke_pet_03", "fx_companion_birth_rd_comp", "$companions_item_invoker_03_name", "$companions_item_invoker_03_description", "$companions_pet_03_name", 4, 4, CraftingTable.Forge, 1, ("SurtlingCore", 25), ("TrophyBonemass", 10), ("Silver", 50)); All = new CompanionDefinition[3] { Companion01, Companion02, Companion03 }; ByInvokerToken = new Dictionary(StringComparer.Ordinal); ByInvokerObject = new Dictionary(); ByCompanionPrefab = new Dictionary(StringComparer.Ordinal); ByCompanionHash = new Dictionary(); for (int i = 0; i < All.Length; i++) { CompanionDefinition companionDefinition = All[i]; if (!ByInvokerToken.ContainsKey(companionDefinition.InvokerNameToken)) { ByInvokerToken.Add(companionDefinition.InvokerNameToken, companionDefinition); } if (!ByCompanionPrefab.ContainsKey(companionDefinition.CompanionPrefab)) { ByCompanionPrefab.Add(companionDefinition.CompanionPrefab, companionDefinition); } int stableHashCode = StringExtensionMethods.GetStableHashCode(companionDefinition.CompanionPrefab); if (!ByCompanionHash.ContainsKey(stableHashCode)) { ByCompanionHash.Add(stableHashCode, companionDefinition); } } } internal static void BindInvoker(CompanionDefinition definition, GameObject prefab) { if (definition != null && (Object)(object)prefab != (Object)null) { ByInvokerObject[prefab] = definition; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static CompanionDefinition ForInvoker(ItemData item) { if (item == null) { return null; } string text = item.m_shared?.m_name; if (text != null && ByInvokerToken.TryGetValue(text, out var value)) { return value; } GameObject dropPrefab = item.m_dropPrefab; return ((Object)(object)dropPrefab != (Object)null && ByInvokerObject.TryGetValue(dropPrefab, out value)) ? value : null; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal static CompanionDefinition ForCompanion(string prefabName) { CompanionDefinition value; return (prefabName != null && ByCompanionPrefab.TryGetValue(prefabName, out value)) ? value : null; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static CompanionDefinition ForCompanion(ZDO zdo) { return (zdo != null) ? ForCompanion(zdo.GetPrefab()) : null; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static CompanionDefinition ForCompanion(int prefabHash) { CompanionDefinition value; return ByCompanionHash.TryGetValue(prefabHash, out value) ? value : null; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class AzuEpiApi { internal static bool IsLoaded() { return AzuExtendedPlayerInventory.API.IsLoaded(); } internal static bool AddSlot(string name, Func getItem, Func isValid, int index) { return AzuExtendedPlayerInventory.API.AddSlot(name, getItem, isValid, index); } internal static bool RemoveSlot(string name) { return AzuExtendedPlayerInventory.API.RemoveSlot(name); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsInvoker { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(ItemData), "IsEquipable")] private static class ItemData_IsEquipable_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(ItemData __instance, ref bool __result) { if (IsInvoker(__instance)) { __result = true; } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(Humanoid), "EquipItem", new Type[] { typeof(ItemData), typeof(bool) })] private static class Humanoid_EquipItem_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Humanoid __instance, ItemData item, bool triggerEquipEffects, ref bool __result) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) if (!(__instance is Player) || !IsInvoker(item)) { return true; } ItemData equipped = GetEquipped(__instance); if (equipped == item) { __result = !triggerEquipEffects && item.m_equipped; return false; } if (!CanEquip(__instance, item)) { __result = false; return false; } if (equipped != null) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { ((Character)(Player)__instance).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_unequip_first"), 0, (Sprite)null, false); } __result = false; return false; } item.m_equipped = true; SetEquipped(__instance, item); RefreshEquipment(__instance); __result = true; if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { _pendingSummon = true; ProcessPendingSummon(); } return false; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [HarmonyPatch(typeof(Humanoid), "UnequipItem", new Type[] { typeof(ItemData), typeof(bool) })] private static class Humanoid_UnequipItem_CompanionInvoker_Patch { private static bool Prefix(Humanoid __instance, ItemData item, bool triggerEquipEffects, out bool __state) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown __state = false; if (!(__instance is Player) || item == null || !item.m_equipped || !IsInvoker(item)) { return true; } if (_playerDeathInProgress || _internalMove) { return false; } if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer && !ApprovedUnequip.Contains(item)) { BeginUnequip((Player)__instance, item, triggerEquipEffects); return false; } __state = true; return true; } private static void Postfix(Humanoid __instance, ItemData item, bool __state) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown if (!__state || item.m_equipped) { return; } SetEquipped(__instance, null); RefreshEquipment(__instance); if (!((Object)(object)__instance == (Object)(object)Player.m_localPlayer)) { return; } CompanionDefinition companionDefinition = CompanionsRegistry.ForInvoker(item); if (companionDefinition != null) { if (_offlineUnequip) { UnsummonOffline((Player)__instance, companionDefinition, discardItems: false); } else { RequestUnsummon((Player)__instance, companionDefinition, _discardOnCompletedUnequip, fromUnequip: true); } } } } [HarmonyPatch(typeof(Player), "OnDeath")] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private static class Player_OnDeath_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(Player __instance) { _playerDeathInProgress = true; if (!((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer) && ((Character)__instance).IsOwner()) { CompanionsDeathDrop.DropLoaded(__instance); CompanionsNetwork.SendRequest(CompanionsNetwork.NextRequestId(), CompanionOp.DeathDrop, null, option: false, 30f); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static Exception Finalizer(Exception __exception) { _playerDeathInProgress = false; return __exception; } } [HarmonyPatch(typeof(Humanoid), "IsItemEquiped", new Type[] { typeof(ItemData) })] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private static class Humanoid_IsItemEquiped_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Humanoid __instance, ItemData item, ref bool __result) { if (__instance is Player && IsInvoker(item) && GetEquipped(__instance) == item) { __result = true; } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(Humanoid), "UnequipAllItems")] private static class Humanoid_UnequipAllItems_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Prefix(Humanoid __instance) { if (__instance is Player) { ItemData equipped = GetEquipped(__instance); if (equipped != null) { __instance.UnequipItem(equipped, false); } } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(Humanoid), "DropItem", new Type[] { typeof(Inventory), typeof(ItemData), typeof(int) })] private static class Humanoid_DropItem_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Humanoid __instance, ItemData item, ref bool __result) { if (!(__instance is Player) || !IsInvoker(item) || !item.m_equipped) { return true; } if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { CompanionsContainer.Show("$companions_msg_unequip_first"); } __result = false; return false; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(InventoryGui), "OnSelectedItem", new Type[] { typeof(InventoryGrid), typeof(ItemData), typeof(Vector2i), typeof(Modifier) })] private static class InventoryGui_OnSelectedItem_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(InventoryGui __instance, InventoryGrid grid, ItemData item, Vector2i pos, Modifier mod) { //IL_0067: 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_0037: Invalid comparison between Unknown and I4 if ((Object)(object)grid == (Object)null) { return true; } Inventory inventory = grid.GetInventory(); Container currentContainer = __instance.m_currentContainer; bool flag = (Object)(object)__instance.m_dragGo != (Object)null; bool num; if (!flag) { if ((int)mod != 2 || !((Object)(object)currentContainer != (Object)null)) { goto IL_0086; } num = BlocksTransfer(inventory, item, currentContainer.GetInventory()); } else { num = BlocksDrop(inventory, __instance.m_dragInventory, __instance.m_dragItem, __instance.m_dragAmount, pos); } if (num) { CompanionsContainer.Show("$companions_msg_unequip_first"); return false; } goto IL_0086; IL_0086: _internalMove = flag && IsLocalInventory(inventory) && inventory == __instance.m_dragInventory; return true; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static Exception Finalizer(Exception __exception) { _internalMove = false; return __exception; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(Inventory), "MoveItemToThis", new Type[] { typeof(Inventory), typeof(ItemData) })] private static class Inventory_MoveItemToThis_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static bool Prefix(Inventory __instance, Inventory fromInventory, ItemData item) { if (!BlocksTransfer(fromInventory, item, __instance)) { return true; } CompanionsContainer.Show("$companions_msg_unequip_first"); return false; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [HarmonyPatch(typeof(Player), "OnSpawned", new Type[] { typeof(bool) })] private static class Player_OnSpawned_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Player __instance) { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { Initialize(); Resync((Humanoid)(object)__instance); if (GetEquipped((Humanoid)(object)__instance) != null) { RefreshEquipment((Humanoid)(object)__instance); _pendingSummon = !CompanionsNetwork.IsPending(_summonRequestId); } else { _reconcilePending = true; } ProcessPendingSummon(); } } } [HarmonyPatch(typeof(Humanoid), "OnDestroy")] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private static class Humanoid_OnDestroy_CompanionInvoker_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Humanoid __instance) { if (__instance is Player) { EquippedItems.Remove(__instance); EmptyResyncAt.Remove(__instance); if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { ClearPendingUnequip(); ClearUnequipUnsummon(); _pendingSummon = false; _summonRequestId = 0; ResetReconcile(); } } } } private const float EmptyResyncInterval = 1f; private const float UnequipReplyBudget = 10f; private const float RequestBudget = 30f; private const float SummonGraceSeconds = 10f; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 2 })] private static readonly Dictionary EquippedItems = new Dictionary(); private static readonly Dictionary EmptyResyncAt = new Dictionary(); private static readonly HashSet ApprovedUnequip = new HashSet(); private static readonly List ReconcileQueue = new List(); private static readonly List ReconcileHasItems = new List(); private static bool _slotRegistered; private static bool _pendingSummon; private static bool _playerDeathInProgress; private static bool _reconcilePending; private static bool _reconcileRunning; private static bool _offlineUnequip; private static bool _internalMove; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static ItemData _pendingUnequipItem; private static bool _pendingUnequipEffects; private static bool _pendingUnequipAwaitingServer; private static bool _discardOnCompletedUnequip; private static int _pendingUnequipRequestId; private static int _summonRequestId; private static int _reconcileRequestId; private static int _unequipUnsummonRequestId; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static CompanionDefinition _unequipUnsummonDefinition; internal static void Initialize() { if (!_slotRegistered && AzuEpiApi.IsLoaded()) { _slotRegistered = AzuEpiApi.AddSlot("$companions_slot_name", (Player player) => GetEquipped((Humanoid)(object)player), IsInvoker, -1); } } internal static void Unregister() { if (_slotRegistered && AzuEpiApi.RemoveSlot("$companions_slot_name")) { _slotRegistered = false; } } internal static void Reset() { EquippedItems.Clear(); EmptyResyncAt.Clear(); ApprovedUnequip.Clear(); ClearPendingUnequip(); ClearUnequipUnsummon(); ResetReconcile(); _pendingSummon = false; _playerDeathInProgress = false; _reconcileRunning = false; _offlineUnequip = false; _internalMove = false; _discardOnCompletedUnequip = false; _summonRequestId = 0; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static bool IsInvoker(ItemData item) { return CompanionsRegistry.ForInvoker(item) != null; } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] internal static CompanionDefinition GetEquippedDefinition(Player player) { return CompanionsRegistry.ForInvoker(GetEquipped((Humanoid)(object)player)); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool BlocksTransfer(Inventory from, ItemData item, Inventory to) { return to != null && item != null && from != to && IsLocalInventory(from) && item.m_equipped && IsInvoker(item); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static bool BlocksDrop(Inventory target, Inventory from, ItemData item, int amount, Vector2i position) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (target == null || from == null || item == null) { return false; } if (BlocksTransfer(from, item, target)) { return true; } ItemData itemAt = target.GetItemAt(position.x, position.y); return CompanionsContainer.WouldSwap(itemAt, item, amount) && BlocksTransfer(target, itemAt, from); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static bool IsLocalInventory(Inventory inventory) { Player localPlayer = Player.m_localPlayer; return (Object)(object)localPlayer != (Object)null && inventory != null && inventory == ((Humanoid)localPlayer).GetInventory(); } private static void ResetReconcile() { _reconcilePending = false; _reconcileRequestId = 0; ReconcileQueue.Clear(); ReconcileHasItems.Clear(); } private static bool ShowDiscardPopup(Player player, Action yes, Action no) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_006e: Expected O, but got Unknown //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown if (!UnifiedPopup.IsAvailable()) { ((Character)player).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_popup_unavailable"), 0, (Sprite)null, false); return false; } UnifiedPopup.Push((PopupBase)new YesNoPopup(CompanionsLocalization.Localize("$companions_popup_title"), CompanionsLocalization.Localize("$companions_popup_discard"), (PopupButtonCallback)delegate { UnifiedPopup.Pop(); yes(); }, (PopupButtonCallback)delegate { UnifiedPopup.Pop(); no(); }, false, false)); return true; } internal static void ProcessPendingSummon() { Initialize(); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } ItemData equipped = GetEquipped((Humanoid)(object)localPlayer); if (equipped == null) { _pendingSummon = false; if (_reconcilePending) { StartReconcile(localPlayer); } return; } ResetReconcile(); if (!_pendingSummon || CompanionsNetwork.IsPending(_summonRequestId)) { return; } CompanionDefinition companionDefinition = CompanionsRegistry.ForInvoker(equipped); if (companionDefinition == null) { _pendingSummon = false; return; } int requestId = (_summonRequestId = CompanionsNetwork.NextRequestId()); _pendingSummon = false; if (CompanionsNetwork.SendRequest(requestId, CompanionOp.Summon, companionDefinition, option: false, 30f)) { CompanionsCatchUp.SuppressCatchUp(localPlayer, 10f); return; } _summonRequestId = 0; _pendingSummon = true; } internal static void RequestFollowerSummon(Player player, CompanionDefinition definition) { if (!((Object)(object)player == (Object)null) && definition != null && GetEquippedDefinition(player) == definition && !CompanionsNetwork.IsPending(_summonRequestId) && !CompanionsNetwork.SendRequest(_summonRequestId = CompanionsNetwork.NextRequestId(), CompanionOp.Summon, definition, option: true, 30f)) { _summonRequestId = 0; } } private static void StartReconcile(Player player) { if (!_reconcileRunning && GetEquipped((Humanoid)(object)player) == null && !CompanionsNetwork.IsPending(_reconcileRequestId)) { ReconcileQueue.Clear(); ReconcileHasItems.Clear(); int requestId = (_reconcileRequestId = CompanionsNetwork.NextRequestId()); _reconcilePending = false; if (!CompanionsNetwork.SendRequest(requestId, CompanionOp.Check, null, option: false, 30f)) { _reconcileRequestId = 0; _reconcilePending = true; } } } internal static void OnResponse(CompanionRequest request, CompanionStatus status, ZPackage data) { switch (request.Op) { case CompanionOp.Summon: OnSummonResponse(request, status, data); break; case CompanionOp.Check: if (request.Id == _pendingUnequipRequestId) { OnUnequipCheck(status); } else if (request.Id == _reconcileRequestId) { OnReconcileCheck(status, data); } break; case CompanionOp.Unsummon: OnUnsummonResponse(request, status); break; } Player localPlayer = Player.m_localPlayer; if (_reconcilePending && (Object)(object)localPlayer != (Object)null) { StartReconcile(localPlayer); } } internal static void OnTimeout(CompanionRequest request) { Player localPlayer = Player.m_localPlayer; switch (request.Op) { case CompanionOp.Summon: if (request.Id == _summonRequestId) { _summonRequestId = 0; if ((Object)(object)localPlayer != (Object)null) { ((Character)localPlayer).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_server_not_responding"), 0, (Sprite)null, false); } } break; case CompanionOp.Check: if (request.Id == _pendingUnequipRequestId) { CompleteUnequipOffline(); } else if (request.Id == _reconcileRequestId) { _reconcileRequestId = 0; _reconcilePending = true; } break; case CompanionOp.Unsummon: if (request.Id == _unequipUnsummonRequestId) { ClearUnequipUnsummon(); } if ((Object)(object)localPlayer != (Object)null && request.Definition != null) { UnsummonOffline(localPlayer, request.Definition, request.Option); } break; } } private static void OnSummonResponse(CompanionRequest request, CompanionStatus status, ZPackage data) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) if (request.Id != _summonRequestId) { return; } _summonRequestId = 0; Player localPlayer = Player.m_localPlayer; CompanionDefinition definition = request.Definition; ItemData val = (((Object)(object)localPlayer != (Object)null) ? GetEquipped((Humanoid)(object)localPlayer) : null); if ((Object)(object)localPlayer != (Object)null && definition != null && val != null && CompanionsRegistry.ForInvoker(val) == definition) { switch (status) { case CompanionStatus.SpawnLocal: CompanionsLifecycle.SpawnLocal(localPlayer, definition, data.ReadString()); break; case CompanionStatus.Moved: case CompanionStatus.Routed: CompanionsAssets.SpawnBirthEffect(data.ReadVector3(), definition); break; case CompanionStatus.Waiting: ((Character)localPlayer).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_waiting_at_entrance"), 0, (Sprite)null, false); break; } } if (_pendingSummon) { ProcessPendingSummon(); } } private static void OnUnequipCheck(CompanionStatus status) { ItemData item = _pendingUnequipItem; _pendingUnequipAwaitingServer = false; _pendingUnequipRequestId = 0; if (item != null) { Player player = Player.m_localPlayer; if ((Object)(object)player == (Object)null || !IsValid((Humanoid)(object)player, item)) { ClearPendingUnequip(); } else if ((status == CompanionStatus.NotFound || status == CompanionStatus.NoItems) ? true : false) { CompleteUnequip(player, item, discardItems: false, remoteUnsummon: true); } else if (status != CompanionStatus.HasItems) { ClearPendingUnequip(); } else if (!ShowDiscardPopup(player, delegate { if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || _pendingUnequipItem != item || !IsValid((Humanoid)(object)player, item)) { ClearPendingUnequip(); } else { CompleteUnequip(player, item, discardItems: true, remoteUnsummon: true); } }, ClearPendingUnequip)) { ClearPendingUnequip(); } } } private static void CompleteUnequipOffline() { ItemData pendingUnequipItem = _pendingUnequipItem; Player localPlayer = Player.m_localPlayer; if (pendingUnequipItem == null || (Object)(object)localPlayer == (Object)null || !IsValid((Humanoid)(object)localPlayer, pendingUnequipItem)) { ClearPendingUnequip(); return; } ((Character)localPlayer).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_server_not_responding"), 0, (Sprite)null, false); CompleteUnequip(localPlayer, pendingUnequipItem, discardItems: false, remoteUnsummon: false); } private static void RequestUnsummon(Player player, CompanionDefinition definition, bool discardItems, bool fromUnequip = false) { int num = CompanionsNetwork.NextRequestId(); if (fromUnequip && !discardItems) { _unequipUnsummonRequestId = num; _unequipUnsummonDefinition = definition; } if (!CompanionsNetwork.SendRequest(num, CompanionOp.Unsummon, definition, discardItems, 30f)) { if (_unequipUnsummonRequestId == num) { ClearUnequipUnsummon(); } UnsummonOffline(player, definition, discardItems); } } private static void ClearUnequipUnsummon() { _unequipUnsummonRequestId = 0; _unequipUnsummonDefinition = null; } internal static void OnUnsummonRefused(CompanionDefinition definition) { Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { if (_unequipUnsummonDefinition == definition && CompanionsNetwork.IsPending(_unequipUnsummonRequestId)) { ClearUnequipUnsummon(); ResolveRefusedUnsummon(localPlayer, definition); } else { _reconcilePending = true; } } } private static void ResolveRefusedUnsummon(Player player, CompanionDefinition definition) { if (!ShowDiscardPopup(player, delegate { if (!((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { if (GetEquipped((Humanoid)(object)player) == null) { RequestUnsummon(player, definition, discardItems: true); } else { _reconcilePending = true; } } }, delegate { if (!((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { Reequip(player, definition); } })) { Reequip(player, definition); } } private static void Reequip(Player player, CompanionDefinition definition) { ItemData val = ((GetEquipped((Humanoid)(object)player) == null) ? FindInvoker((Humanoid)(object)player, definition) : null); if (val == null || !((Humanoid)player).EquipItem(val, true)) { _reconcilePending = true; } } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static ItemData FindInvoker(Humanoid humanoid, CompanionDefinition definition) { Inventory inventory = humanoid.GetInventory(); if (inventory == null) { return null; } List allItems = inventory.GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && CompanionsRegistry.ForInvoker(val) == definition) { return val; } } return null; } private static void UnsummonOffline(Player player, CompanionDefinition definition, bool discardItems) { _reconcilePending = true; ItemData equipped = GetEquipped((Humanoid)(object)player); if (equipped == null || CompanionsRegistry.ForInvoker(equipped) != definition) { CompanionsLifecycle.DestroyLoaded(player, definition, discardItems); } } private static void OnUnsummonResponse(CompanionRequest request, CompanionStatus status) { Player localPlayer = Player.m_localPlayer; CompanionDefinition definition = request.Definition; if ((Object)(object)localPlayer == (Object)null || definition == null) { return; } bool flag = request.Id == _unequipUnsummonRequestId; if (flag) { ClearUnequipUnsummon(); } switch (status) { case CompanionStatus.HasItems: if (flag) { ResolveRefusedUnsummon(localPlayer, definition); } else { _reconcilePending = true; } break; case CompanionStatus.NotFound: { ItemData equipped = GetEquipped((Humanoid)(object)localPlayer); if (equipped == null || CompanionsRegistry.ForInvoker(equipped) != definition) { CompanionsLifecycle.DestroyLoaded(localPlayer, definition, request.Option); } break; } } } private static void OnReconcileCheck(CompanionStatus status, ZPackage data) { _reconcileRequestId = 0; Player localPlayer = Player.m_localPlayer; bool flag = (Object)(object)localPlayer == (Object)null || GetEquipped((Humanoid)(object)localPlayer) != null; bool flag2 = flag; if (!flag2) { bool flag3 = (uint)(status - 4) <= 1u; flag2 = !flag3; } if (flag2) { return; } ReconcileQueue.Clear(); ReconcileHasItems.Clear(); int num = data.ReadInt(); for (int i = 0; i < num; i++) { int prefabHash = data.ReadInt(); bool flag4 = data.ReadBool(); CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(prefabHash); if (companionDefinition != null) { int num2 = ReconcileQueue.IndexOf(companionDefinition); if (num2 < 0) { ReconcileQueue.Add(companionDefinition); ReconcileHasItems.Add(flag4); } else if (flag4) { ReconcileHasItems[num2] = true; } } } ProcessReconcileQueue(localPlayer); } private static void ProcessReconcileQueue(Player player) { _reconcileRunning = true; try { while (ReconcileQueue.Count > 0) { if ((Object)(object)player == (Object)null || (Object)(object)player != (Object)(object)Player.m_localPlayer || GetEquipped((Humanoid)(object)player) != null) { ReconcileQueue.Clear(); ReconcileHasItems.Clear(); break; } CompanionDefinition definition = ReconcileQueue[0]; bool flag = ReconcileHasItems[0]; ReconcileQueue.RemoveAt(0); ReconcileHasItems.RemoveAt(0); if (!flag) { RequestUnsummon(player, definition, discardItems: false); } else if (ShowDiscardPopup(player, delegate { if (!((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { if (GetEquipped((Humanoid)(object)player) == null) { RequestUnsummon(player, definition, discardItems: true); } ProcessReconcileQueue(player); } }, delegate { if (!((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)Player.m_localPlayer)) { KeepCompanion(player, definition); ProcessReconcileQueue(player); } })) { break; } } } finally { _reconcileRunning = false; } } private static void KeepCompanion(Player player, CompanionDefinition definition) { CompanionsLifecycle.KeepLoaded(player, definition); CompanionsNetwork.SendRequest(CompanionsNetwork.NextRequestId(), CompanionOp.Keep, definition, option: false, 30f); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] private static ItemData GetEquipped(Humanoid humanoid) { if (!(humanoid is Player)) { return null; } if (EquippedItems.TryGetValue(humanoid, out var value)) { if (value == null) { if (EmptyResyncAt.TryGetValue(humanoid, out var value2) && Time.time < value2) { return null; } } else if (IsValid(humanoid, value)) { return value; } } Resync(humanoid); return (EquippedItems.TryGetValue(humanoid, out value) && IsValid(humanoid, value)) ? value : null; } private static bool IsValid(Humanoid humanoid, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] ItemData item) { Inventory inventory = humanoid.GetInventory(); return item != null && item.m_equipped && inventory != null && inventory.ContainsItem(item); } private static void Resync(Humanoid humanoid) { Inventory inventory = humanoid.GetInventory(); if (inventory != null) { List allItems = inventory.GetAllItems(); for (int i = 0; i < allItems.Count; i++) { ItemData val = allItems[i]; if (val != null && val.m_equipped && IsInvoker(val)) { EquippedItems[humanoid] = val; return; } } } EquippedItems[humanoid] = null; EmptyResyncAt[humanoid] = Time.time + 1f; } private static void SetEquipped(Humanoid humanoid, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] ItemData item) { EquippedItems[humanoid] = item; if (item == null) { EmptyResyncAt[humanoid] = Time.time + 1f; } else { EmptyResyncAt.Remove(humanoid); } } private static bool CanEquip(Humanoid humanoid, ItemData item) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: 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_0109: Invalid comparison between Unknown and I4 //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Invalid comparison between Unknown and I4 Inventory inventory = humanoid.GetInventory(); if (inventory == null || !inventory.ContainsItem(item) || ((Character)humanoid).InAttack() || ((Character)humanoid).InDodge()) { return false; } if (((Character)humanoid).IsPlayer() && !((Character)humanoid).IsDead() && ((Character)humanoid).IsSwimming() && !((Character)humanoid).IsOnGround()) { return false; } if (item.m_shared.m_useDurability && item.m_durability <= 0f) { return false; } if (!string.IsNullOrEmpty(item.m_shared.m_dlc) && ((Object)(object)DLCMan.instance == (Object)null || !DLCMan.instance.IsDLCInstalled(item.m_shared.m_dlc))) { return false; } bool flag = Game.m_worldLevel <= 0 || item.m_worldLevel >= Game.m_worldLevel; bool flag2 = flag; if (!flag2) { ItemType itemType = item.m_shared.m_itemType; bool flag3 = (((int)itemType == 18 || (int)itemType == 24) ? true : false); flag2 = !flag3; } return flag2; } private static void BeginUnequip(Player player, ItemData item, bool triggerEquipEffects) { if (_pendingUnequipItem != null) { if (!_pendingUnequipAwaitingServer || CompanionsNetwork.IsPending(_pendingUnequipRequestId)) { return; } ClearPendingUnequip(); } CompanionDefinition companionDefinition = CompanionsRegistry.ForInvoker(item); if (companionDefinition != null) { int num = CompanionsNetwork.NextRequestId(); _pendingUnequipItem = item; _pendingUnequipEffects = triggerEquipEffects; _pendingUnequipAwaitingServer = true; _pendingUnequipRequestId = num; if (!CompanionsNetwork.SendRequest(num, CompanionOp.Check, companionDefinition, option: false, 10f)) { ((Character)player).Message((MessageType)2, CompanionsLocalization.Localize("$companions_msg_server_unavailable"), 0, (Sprite)null, false); ClearPendingUnequip(); } } } private static void CompleteUnequip(Player player, ItemData item, bool discardItems, bool remoteUnsummon) { bool pendingUnequipEffects = _pendingUnequipEffects; ClearPendingUnequip(); _discardOnCompletedUnequip = discardItems; _offlineUnequip = !remoteUnsummon; ApprovedUnequip.Add(item); try { ((Humanoid)player).UnequipItem(item, pendingUnequipEffects); } finally { ApprovedUnequip.Remove(item); _discardOnCompletedUnequip = false; _offlineUnequip = false; } } private static void ClearPendingUnequip() { _pendingUnequipItem = null; _pendingUnequipEffects = false; _pendingUnequipAwaitingServer = false; _pendingUnequipRequestId = 0; } private static void RefreshEquipment(Humanoid humanoid) { if ((Object)(object)humanoid == (Object)(object)Player.m_localPlayer && (Object)(object)Game.instance != (Object)null && (Object)(object)ZNet.instance != (Object)null && ZDOMan.instance != null) { humanoid.SetupEquipment(); } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsCatchUp { internal const int CatchUpTicks = 2; private const float TickInterval = 1f; private const float ClaimInterval = 2f; internal static readonly int LeftBehindKey = StringExtensionMethods.GetStableHashCode("comp.leftBehind"); internal static readonly int TeleportUntilKey = StringExtensionMethods.GetStableHashCode("comp.tpUntil"); private static readonly List Loaded = new List(); private static Dictionary _farTicks = new Dictionary(); private static Dictionary _nextFarTicks = new Dictionary(); private static float _nextTick; private static float _nextClaim; internal static bool Enabled => CompanionsPlugin.CatchUpTeleport?.Value ?? true; internal static float Distance => CompanionsPlugin.CatchUpDistance?.Value ?? 80f; internal static bool IsFollowing(ZDO zdo) { return !string.IsNullOrEmpty(zdo.GetString(ZDOVars.s_follow, "")); } internal static bool IsWaiting(ZDO zdo) { return zdo.GetBool(CompanionsFlight.DungeonWaitKey, false); } internal static bool IsLeftBehind(ZDO zdo) { return zdo.GetBool(LeftBehindKey, false); } internal static bool IsEligible(ZDO zdo, bool sameSide, float distance, float maxDistance) { return sameSide && distance > maxDistance && IsFollowing(zdo) && !IsWaiting(zdo) && !IsLeftBehind(zdo); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] internal static void SuppressCatchUp(Player player, float seconds) { ZNetView val = (((Object)(object)player != (Object)null) ? ((Character)player).m_nview : null); if (!((Object)(object)val == (Object)null) && val.IsValid() && val.IsOwner() && !((Object)(object)ZNet.instance == (Object)null)) { val.GetZDO().Set(TeleportUntilKey, ZNet.instance.GetTime().Ticks + TimeSpan.FromSeconds(seconds).Ticks); } } internal static bool IsSuppressed(ZDO character) { long num = character.GetLong(TeleportUntilKey, 0L); return num != 0L && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.GetTime().Ticks < num; } internal static void Reset() { _farTicks.Clear(); _nextFarTicks.Clear(); _nextTick = 0f; _nextClaim = 0f; } internal static void UpdateLocal() { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //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_0161: 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_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016a: 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_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || (Object)(object)ZNet.instance == (Object)null) { return; } float time = Time.time; if (time < _nextTick) { return; } _nextTick = time + 1f; CompanionsState.CollectLoaded(localPlayer, null, Loaded); if (time >= _nextClaim) { _nextClaim = time + 2f; ClaimLoaded(localPlayer); } ZNetView nview = ((Character)localPlayer).m_nview; if ((Object)(object)nview == (Object)null || !nview.IsValid() || ((Character)localPlayer).IsTeleporting() || ((Character)localPlayer).IsDead()) { _farTicks.Clear(); Loaded.Clear(); return; } bool flag = Enabled && !IsSuppressed(nview.GetZDO()); float distance = Distance; Vector3 position = ((Component)localPlayer).transform.position; bool flag2 = Character.InInterior(position); Quaternion rotation = ((Component)localPlayer).transform.rotation; Quaternion rotation2 = Quaternion.Euler(0f, ((Quaternion)(ref rotation)).eulerAngles.y, 0f); _nextFarTicks.Clear(); int num = 0; for (int i = 0; i < Loaded.Count; i++) { ZNetView val = Loaded[i]; ZDO zDO = val.GetZDO(); Vector3 position2 = ((Component)val).transform.position; float num2 = Vector3.Distance(position2, position); bool flag3 = Character.InInterior(position2) == flag2; if (IsLeftBehind(zDO) && flag3 && num2 <= distance) { if (!val.IsOwner()) { val.ClaimOwnership(); } zDO.Set(LeftBehindKey, false); } if (!flag || !IsEligible(zDO, flag3, num2, distance)) { continue; } _farTicks.TryGetValue(zDO.m_uid, out var value); if (++value < 2) { _nextFarTicks[zDO.m_uid] = value; continue; } if (!val.IsOwner()) { val.ClaimOwnership(); } Vector3 arrivalPosition = CompanionsFlight.GetArrivalPosition(localPlayer, CompanionsLifecycle.GetTeleportOffset(num++)); CompanionsNetwork.MoveLocal(val, arrivalPosition, rotation2, CompanionMove.Follow, localPlayer.GetPlayerName(), control: true); CompanionDefinition companionDefinition = CompanionsRegistry.ForCompanion(zDO); if (companionDefinition != null) { CompanionsAssets.SpawnBirthEffect(arrivalPosition, companionDefinition); } } Loaded.Clear(); Dictionary nextFarTicks = _nextFarTicks; Dictionary farTicks = _farTicks; _farTicks = nextFarTicks; _nextFarTicks = farTicks; } private static void ClaimLoaded(Player player) { long playerID = player.GetPlayerID(); string platformId = CompanionsState.GetPlatformId(player); for (int i = 0; i < Loaded.Count; i++) { ZNetView val = Loaded[i]; if (!val.IsOwner()) { val.ClaimOwnership(); } CompanionsState.RefreshPlatform(val.GetZDO(), CompanionsState.OwnerKey, CompanionsState.OwnerPlatformKey, playerID, platformId); } } } [HarmonyPatch(typeof(ZNet), "Update")] internal static class ZNet_Update_CompanionCatchUp_Patch { private static void Postfix() { CompanionsCatchUp.UpdateLocal(); } } internal enum CompanionTeleportMode { Follow = 0, WaitAtEntrance = 1, LeaveDungeon = 2, LeaveBehind = 4 } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] internal static class CompanionsTeleport { private const float TravelSeconds = 30f; private const float GraceSeconds = 10f; private static readonly List Loaded = new List(); private static readonly HashSet Moved = new HashSet(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Player _player; private static bool _pending; private static CompanionTeleportMode _mode; internal static bool Pending => _pending; internal static void Reset() { _pending = false; _player = null; Moved.Clear(); Loaded.Clear(); } internal static void Begin(Player player, Vector3 destination, Quaternion rotation, CompanionTeleportMode mode) { //IL_0030: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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) //IL_0041: 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_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: 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_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) _player = player; _pending = true; _mode = mode; Moved.Clear(); CompanionsCatchUp.SuppressCatchUp(player, 30f); Quaternion rotation2 = Flatten(((Component)player).transform.rotation); Quaternion rotation3 = Flatten(rotation); string playerName = player.GetPlayerName(); CompanionsState.CollectLoaded(player, null, Loaded); int num = 0; for (int i = 0; i < Loaded.Count; i++) { ZNetView val = Loaded[i]; ZDO zDO = val.GetZDO(); bool flag = CompanionsCatchUp.IsFollowing(zDO); bool flag2 = CompanionsCatchUp.IsWaiting(zDO); if (mode == CompanionTeleportMode.LeaveBehind) { if (!(!flag || flag2)) { if (!val.IsOwner()) { val.ClaimOwnership(); } zDO.Set(CompanionsCatchUp.LeftBehindKey, true); } } else if (flag || flag2) { if (!val.IsOwner()) { val.ClaimOwnership(); } if (mode == CompanionTeleportMode.WaitAtEntrance) { CompanionsNetwork.MoveLocal(val, CompanionsFlight.GetArrivalPosition(player, CompanionsLifecycle.GetTeleportOffset(num++)), rotation2, CompanionMove.DungeonWait, playerName, control: true); continue; } CompanionsNetwork.MoveLocal(val, CompanionsFlight.GetArrivalPosition(destination, CompanionsLifecycle.GetTeleportOffset(num++)), rotation3, CompanionMove.Follow, playerName, control: true); Moved.Add(zDO.m_uid); } } Loaded.Clear(); } internal static void Update(Player player) { if (!_pending) { return; } if (player != _player) { _pending = false; _player = null; Moved.Clear(); } else if (!((Character)player).IsTeleporting()) { _pending = false; _player = null; CompanionsCatchUp.SuppressCatchUp(player, 10f); CompanionTeleportMode mode = _mode; if ((mode == CompanionTeleportMode.Follow || mode == CompanionTeleportMode.LeaveDungeon) ? true : false) { Arrive(player); } Moved.Clear(); } } private static void Arrive(Player player) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) Quaternion rotation = Flatten(((Component)player).transform.rotation); string playerName = player.GetPlayerName(); CompanionDefinition equippedDefinition = CompanionsInvoker.GetEquippedDefinition(player); bool flag = false; CompanionsState.CollectLoaded(player, null, Loaded); int num = 0; for (int i = 0; i < Loaded.Count; i++) { ZNetView val = Loaded[i]; ZDO zDO = val.GetZDO(); if (CompanionsRegistry.ForCompanion(zDO) == equippedDefinition) { flag = true; } if (Moved.Contains(zDO.m_uid)) { if (!val.IsOwner()) { val.ClaimOwnership(); } CompanionsNetwork.MoveLocal(val, CompanionsFlight.GetArrivalPosition(player, CompanionsLifecycle.GetTeleportOffset(num++)), rotation, CompanionMove.Follow, playerName, control: true); } } Loaded.Clear(); if (equippedDefinition != null && !flag) { CompanionsInvoker.RequestFollowerSummon(player, equippedDefinition); } } private static Quaternion Flatten(Quaternion rotation) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Euler(0f, ((Quaternion)(ref rotation)).eulerAngles.y, 0f); } } [HarmonyPatch(typeof(Player), "TeleportTo", new Type[] { typeof(Vector3), typeof(Quaternion), typeof(bool) })] internal static class Player_TeleportTo_CompanionTeleport_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Player __instance, Vector3 pos, Quaternion rot, bool __result) { //IL_0028: 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_0083: Unknown result type (might be due to invalid IL or missing references) if (__result && !((Object)(object)__instance == (Object)null) && !((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { bool flag = ((Character)__instance).InInterior(); bool flag2 = Character.InInterior(pos); CompanionTeleportMode mode; if (!flag && flag2) { ConfigEntry waitAtDungeonEntrance = CompanionsPlugin.WaitAtDungeonEntrance; mode = ((waitAtDungeonEntrance != null && waitAtDungeonEntrance.Value) ? CompanionTeleportMode.WaitAtEntrance : CompanionTeleportMode.Follow); } else if (flag && !flag2) { mode = CompanionTeleportMode.LeaveDungeon; } else { ConfigEntry teleportCompanion = CompanionsPlugin.TeleportCompanion; mode = ((teleportCompanion == null || !teleportCompanion.Value) ? CompanionTeleportMode.LeaveBehind : CompanionTeleportMode.Follow); } CompanionsTeleport.Begin(__instance, pos, rot, mode); } } } [HarmonyPatch(typeof(Player), "UpdateTeleport")] internal static class Player_UpdateTeleport_CompanionTeleport_Patch { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] private static void Postfix(Player __instance) { if (CompanionsTeleport.Pending && (Object)(object)__instance == (Object)(object)Player.m_localPlayer) { CompanionsTeleport.Update(__instance); } } } } namespace LocalizationManager { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [PublicAPI] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public class Localizer { private static readonly Dictionary>> PlaceholderProcessors; private static readonly Dictionary> loadedTexts; private static readonly ConditionalWeakTable localizationLanguage; private static readonly List> localizationObjects; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static BaseUnityPlugin _plugin; private static readonly List fileExtensions; private static BaseUnityPlugin plugin { get { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] [method: <4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] [field: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public static event Action OnLocalizationComplete; private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out var value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out var value2)) { text = value2.Aggregate(text, [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (string current, KeyValuePair> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } bool flag; switch (key) { case "companions_blocked_item": case "companions_owner_open": case "companions_owner_take_all": flag = true; break; default: flag = false; break; } if (flag) { text = "" + text + ""; } localization.AddWord(key, text); } public static void AddPlaceholder(string key, string placeholder, ConfigEntry config, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1, 1 })] Func convertConfigValue = null) { if (convertConfigValue == null) { convertConfigValue = (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary>(); } config.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { UpdatePlaceholder(); }; if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage())) { UpdatePlaceholder(); } void UpdatePlaceholder() { PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value); UpdatePlaceholderText(Localization.instance, key); } } public static void AddText(string key, string text) { List> list = new List>(); foreach (WeakReference localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference item in list) { localizationObjects.Remove(item); } } public static void Load() { _ = plugin; } public static void LoadLocalizationLater(Localization __instance) { LoadLocalization(Localization.instance, __instance.GetSelectedLanguage()); } public static void SafeCallLocalizeComplete() { Localizer.OnLocalizationComplete?.Invoke(); } private static void LoadLocalization(Localization __instance, string language) { if (!localizationLanguage.Remove(__instance)) { localizationObjects.Add(new WeakReference(__instance)); } localizationLanguage.Add(__instance, language); Dictionary dictionary = new Dictionary(); foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories) where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0 select f) { string[] array = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' }); if (array.Length >= 2) { string key = array[1]; if (!dictionary.ContainsKey(key)) { dictionary[key] = item; } } } byte[] array2 = LoadTranslationFromAssembly("English"); if (array2 == null) { throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml."); } string input = Encoding.UTF8.GetString(array2).TrimStart(new char[1] { '\ufeff' }); Dictionary dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize>(input); if (dictionary2 == null) { throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty."); } string text = null; if (language != "English") { if (dictionary.TryGetValue(language, out var value)) { text = File.ReadAllText(value); } else { byte[] array3 = LoadTranslationFromAssembly(language); if (array3 != null) { text = Encoding.UTF8.GetString(array3); } } } if (text == null && dictionary.TryGetValue("English", out var value2)) { text = File.ReadAllText(value2); } if (text != null) { text = text.TrimStart(new char[1] { '\ufeff' }); foreach (KeyValuePair item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize>(text) ?? new Dictionary()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair item3 in dictionary2) { UpdatePlaceholderText(__instance, item3.Key); } } static Localizer() { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Expected O, but got Unknown //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Expected O, but got Unknown PlaceholderProcessors = new Dictionary>>(); loadedTexts = new Dictionary>(); localizationLanguage = new ConditionalWeakTable(); localizationObjects = new List>(); fileExtensions = new List(2) { ".json", ".yml" }; Harmony val = new Harmony("org.bepinex.helpers.LocalizationManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "SetupGui", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalizationLater", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Start", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "SafeCallLocalizeComplete", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static byte[] LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] public static byte[] ReadEmbeddedFileBytes([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] string resourceFileName, Assembly containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = containingAssembly.GetManifestResourceNames().FirstOrDefault([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal)); if (text != null) { containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream); } return (memoryStream.Length == 0L) ? null : memoryStream.ToArray(); } } public static class LocalizationManagerVersion { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public const string Version = "1.4.1"; } } namespace ItemManager { [PublicAPI] public 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] public enum ConversionPiece { Disabled, [InternalName("smelter")] Smelter, [InternalName("charcoal_kiln")] CharcoalKiln, [InternalName("blastfurnace")] BlastFurnace, [InternalName("windmill")] Windmill, [InternalName("piece_spinningwheel")] SpinningWheel, [InternalName("eitrrefinery")] EitrRefinery, Custom } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [PublicAPI] public class RequiredResourceList { public readonly List Requirements = new List(); public bool Free = false; 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 }); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [PublicAPI] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] public 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 }); } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [PublicAPI] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] public 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 = false; public float QualityResultAmountMultiplier = 1f; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public ConfigEntryBase RecipeIsActive = null; } [PublicAPI] public class Trade { public Trader Trader = Trader.None; public uint Price = 0u; public uint Stack = 1u; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public string RequiredGlobalKey = null; } [PublicAPI] [Flags] public enum Trader { None = 0, Haldor = 1, Hildir = 2 } public struct Requirement { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public string itemName; public int amount; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public ConfigEntry amountConfig; [Description("Set to a non-zero value to apply the requirement only for a specific quality")] public int quality; } public struct CraftingStationConfig { public CraftingTable Table; public int level; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public string custom; } [Flags] public enum Configurability { Disabled = 0, Recipe = 1, Stats = 2, Drop = 4, Trader = 8, Full = 0xF } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [PublicAPI] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public 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 }); } } public struct DropTarget { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public string creature; public int min; public int max; public float chance; public bool levelMultiplier; } public enum Toggle { On = 1, Off = 0 } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] [PublicAPI] public class Item { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private class ItemConfig { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] public ConfigEntry craft; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] public ConfigEntry upgrade; public ConfigEntry table = null; public ConfigEntry tableLevel = null; public ConfigEntry customTable = null; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public ConfigEntry maximumTableLevel; public ConfigEntry requireOneIngredient = null; public ConfigEntry qualityResultAmountMultiplier = null; } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private class TraderConfig { public ConfigEntry trader = null; public ConfigEntry price = null; public ConfigEntry stack = null; public ConfigEntry requiredGlobalKey = null; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private class RequirementQuality { public int quality; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string Category; [UsedImplicitly] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1 })] public Action CustomDrawer; public Func browsability; } [PublicAPI] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] public enum DamageModifier { Normal, Resistant, Weak, Immune, Ignore, VeryResistant, VeryWeak, None } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] private delegate void setDmgFunc(ref DamageTypes dmg, float value); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private class SerializedRequirements { public readonly List Reqs; public SerializedRequirements(List reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) : this(reqs.Split(new char[1] { ',' }).Select([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : ""))); } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public static ItemDrop fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); return (itemPrefab != null) ? itemPrefab.GetComponent() : null; } public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade) { //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_010d: Unknown result type (might be due to invalid IL or missing references) //IL_019b: 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_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Expected O, but got Unknown //IL_01b7: Expected O, but got Unknown //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown Dictionary dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func)([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Requirement r) => r.itemName), (Func)([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Requirement r) => { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0037: Unknown result type (might be due to invalid IL or missing references) ItemDrop val6 = ResItem(r); return (val6 == null) ? ((Requirement)null) : new Requirement { m_amount = (r.amountConfig?.Value ?? r.amount), m_resItem = val6, m_amountPerLevel = 0 }; })); List list = dictionary.Values.Where([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (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(); [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] ItemDrop ResItem(Requirement r) { return fetchByName(objectDB, r.itemName); } } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0"))); } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Character fetchByName(ZNetScene netScene, string name) { GameObject prefab = netScene.GetPrefab(name); return (prefab != null) ? prefab.GetComponent() : null; } public Dictionary toCharacterDrops(ZNetScene netScene, GameObject item) { //IL_0039: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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: Unknown result type (might be due to invalid IL or missing references) //IL_007a: 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>>(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 2 })] private static Dictionary hiddenCraftRecipes = new Dictionary(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 2 })] 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 = null; private Configurability configurationVisible = Configurability.Full; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] 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(); [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private LocalizeKey _name; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private LocalizeKey _description; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static object configManager; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static Localization _english; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static BaseUnityPlugin _plugin; private static bool hasConfigSync = true; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] 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; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] [Description("Specifies a config entry which toggles whether a recipe is active.")] public ConfigEntryBase RecipeIsActive { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] get { return this[""].RecipeIsActive; } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] 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 var 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] private static object configSync { [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] 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 var value)) { Toggle((ConfigEntryBase)(object)value, Configurability.Drop); } if (itemCraftConfigs.TryGetValue(this, out var 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; foreach (object obj in tags) { if (obj 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(); foreach (FieldInfo fieldInfo in fields) { object? value3 = fieldInfo.GetValue(obj); ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null); if (val != null) { Toggle(val, check); } } } } internal static void reloadConfigDisplay() { if (configManager?.GetType().GetProperty("DisplayingWindow").GetValue(configManager) is int num && num != 0) { 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 var 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 var value)) { return; } foreach (Recipe item in value) { item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements); } } internal static void Patch_FejdStartup() { //IL_1001: Unknown result type (might be due to invalid IL or missing references) //IL_1006: Unknown result type (might be due to invalid IL or missing references) //IL_2395: Unknown result type (might be due to invalid IL or missing references) //IL_239f: Expected O, but got Unknown //IL_10ce: Unknown result type (might be due to invalid IL or missing references) //IL_10d1: Unknown result type (might be due to invalid IL or missing references) //IL_1127: Expected I4, but got Unknown //IL_0ccc: Unknown result type (might be due to invalid IL or missing references) //IL_0cd6: Expected O, but got Unknown //IL_1267: Unknown result type (might be due to invalid IL or missing references) //IL_126a: Unknown result type (might be due to invalid IL or missing references) //IL_126c: Invalid comparison between Unknown and I4 //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0365: Expected O, but got Unknown //IL_0dfa: Unknown result type (might be due to invalid IL or missing references) //IL_0e04: Expected O, but got Unknown //IL_0ea6: Unknown result type (might be due to invalid IL or missing references) //IL_0eb0: Expected O, but got Unknown //IL_1270: Unknown result type (might be due to invalid IL or missing references) //IL_1274: Invalid comparison between Unknown and I4 //IL_0f5b: Unknown result type (might be due to invalid IL or missing references) //IL_0f65: Expected O, but got Unknown //IL_1489: Unknown result type (might be due to invalid IL or missing references) //IL_148c: Unknown result type (might be due to invalid IL or missing references) //IL_148e: Invalid comparison between Unknown and I4 //IL_045e: Unknown result type (might be due to invalid IL or missing references) //IL_0468: Expected O, but got Unknown //IL_1278: Unknown result type (might be due to invalid IL or missing references) //IL_127c: Invalid comparison between Unknown and I4 //IL_1492: Unknown result type (might be due to invalid IL or missing references) //IL_1496: Unknown result type (might be due to invalid IL or missing references) //IL_1498: Invalid comparison between Unknown and I4 //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_05b7: Expected O, but got Unknown //IL_1581: Unknown result type (might be due to invalid IL or missing references) //IL_1586: Unknown result type (might be due to invalid IL or missing references) //IL_1588: Unknown result type (might be due to invalid IL or missing references) //IL_158b: Invalid comparison between Unknown and I4 //IL_149c: Unknown result type (might be due to invalid IL or missing references) //IL_14a0: Invalid comparison between Unknown and I4 //IL_158f: Unknown result type (might be due to invalid IL or missing references) //IL_1593: Invalid comparison between Unknown and I4 //IL_0796: Unknown result type (might be due to invalid IL or missing references) //IL_07a0: Expected O, but got Unknown //IL_06eb: Unknown result type (might be due to invalid IL or missing references) //IL_06f5: Expected O, but got Unknown //IL_160c: Unknown result type (might be due to invalid IL or missing references) //IL_160f: Unknown result type (might be due to invalid IL or missing references) //IL_1611: Invalid comparison between Unknown and I4 //IL_08b0: Unknown result type (might be due to invalid IL or missing references) //IL_08ba: Expected O, but got Unknown //IL_1615: Unknown result type (might be due to invalid IL or missing references) //IL_1619: Unknown result type (might be due to invalid IL or missing references) //IL_161b: Invalid comparison between Unknown and I4 //IL_176e: Unknown result type (might be due to invalid IL or missing references) //IL_1771: Invalid comparison between Unknown and I4 //IL_161f: Unknown result type (might be due to invalid IL or missing references) //IL_1623: Invalid comparison between Unknown and I4 //IL_1980: Unknown result type (might be due to invalid IL or missing references) //IL_1987: Invalid comparison between Unknown and I4 //IL_1a5c: Unknown result type (might be due to invalid IL or missing references) //IL_1a61: Unknown result type (might be due to invalid IL or missing references) //IL_1a63: Unknown result type (might be due to invalid IL or missing references) //IL_1a67: Unknown result type (might be due to invalid IL or missing references) //IL_1a69: Invalid comparison between Unknown and I4 //IL_16de: Unknown result type (might be due to invalid IL or missing references) //IL_16e3: Unknown result type (might be due to invalid IL or missing references) //IL_1ae2: Unknown result type (might be due to invalid IL or missing references) //IL_1ae5: Unknown result type (might be due to invalid IL or missing references) //IL_1ae7: Invalid comparison between Unknown and I4 //IL_1aeb: Unknown result type (might be due to invalid IL or missing references) //IL_1aef: Invalid comparison between Unknown and I4 //IL_1af3: Unknown result type (might be due to invalid IL or missing references) //IL_1af7: Invalid comparison between Unknown and I4 //IL_1f88: Unknown result type (might be due to invalid IL or missing references) //IL_1f8b: Invalid comparison between Unknown and I4 Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out var 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out var 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out var 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_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: 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) } }))); ConfigEntry val3 = val; val3.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { if (index < item.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop val4 = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); item.conversions[index].m_from = val4; 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { 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) { Smelter component = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent(); int num4 = component.m_conversion.IndexOf(item.conversions[index]); if (num4 >= 0) { Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val4 in array3) { if (Utils.GetPrefabName(((Component)val4).gameObject) == activePiece) { val4.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[] array4 = Resources.FindObjectsOfTypeAll(); foreach (Smelter val5 in array4) { if (Utils.GetPrefabName(((Component)val5).gameObject) == text3) { val5.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 val4) => val4.m_weight, delegate(SharedData val4, float value) { val4.m_weight = value; }); statcfg("Trader Value", "Trader value of " + englishName + ".", (SharedData val4) => val4.m_value, delegate(SharedData val4, int value) { val4.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 val4) => val4.m_maxDurability, delegate(SharedData val4, float value) { val4.m_maxDurability = value; }); statcfg("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData val4) => val4.m_durabilityPerLevel, delegate(SharedData val4, float value) { val4.m_durabilityPerLevel = value; }); statcfg("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData val4) => val4.m_movementModifier, delegate(SharedData val4, float value) { val4.m_movementModifier = value; }); } if ((itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Block Armor", "Block armor of " + englishName + ".", (SharedData val4) => val4.m_blockPower, delegate(SharedData val4, float value) { val4.m_blockPower = value; }); statcfg("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData val4) => val4.m_blockPowerPerLevel, delegate(SharedData val4, float value) { val4.m_blockPowerPerLevel = value; }); statcfg("Block Force", "Block force of " + englishName + ".", (SharedData val4) => val4.m_deflectionForce, delegate(SharedData val4, float value) { val4.m_deflectionForce = value; }); statcfg("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData val4) => val4.m_deflectionForcePerLevel, delegate(SharedData val4, float value) { val4.m_deflectionForcePerLevel = value; }); statcfg("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData val4) => val4.m_timedBlockBonus, delegate(SharedData val4, float value) { val4.m_timedBlockBonus = value; }); } else if ((itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { statcfg("Armor", "Armor of " + englishName + ".", (SharedData val4) => val4.m_armor, delegate(SharedData val4, float value) { val4.m_armor = value; }); statcfg("Armor per Level", "Armor per level for " + englishName + ".", (SharedData val4) => val4.m_armorPerLevel, delegate(SharedData val4, float value) { val4.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 val4) => val4.m_toolTier, delegate(SharedData val4, int value) { val4.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) ? value : DamageModifier.None, delegate(SharedData val5, DamageModifier value) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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) //IL_001f: 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_0031: 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_009d: 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) DamageModPair val4 = new DamageModPair { m_type = damageType, m_modifier = (DamageModifier)value }; for (int i = 0; i < val5.m_damageModifiers.Count; i++) { if (val5.m_damageModifiers[i].m_type == damageType) { if (value == DamageModifier.None) { val5.m_damageModifiers.RemoveAt(i); } else { val5.m_damageModifiers[i] = val4; } return; } } if (value != DamageModifier.None) { val5.m_damageModifiers.Add(val4); } }); } } if ((int)itemType == 2 && shared.m_food > 0f) { statcfg("Health", "Health value of " + englishName + ".", (SharedData val4) => val4.m_food, delegate(SharedData val4, float value) { val4.m_food = value; }); statcfg("Stamina", "Stamina value of " + englishName + ".", (SharedData val4) => val4.m_foodStamina, delegate(SharedData val4, float value) { val4.m_foodStamina = value; }); statcfg("Eitr", "Eitr value of " + englishName + ".", (SharedData val4) => val4.m_foodEitr, delegate(SharedData val4, float value) { val4.m_foodEitr = value; }); statcfg("Duration", "Duration of " + englishName + ".", (SharedData val4) => val4.m_foodBurnTime, delegate(SharedData val4, float value) { val4.m_foodBurnTime = value; }); statcfg("Health Regen", "Health regen value of " + englishName + ".", (SharedData val4) => val4.m_foodRegen, delegate(SharedData val4, float value) { val4.m_foodRegen = value; }); } if ((int)shared.m_skillType == 10) { statcfg("Health Cost", "Health cost of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackHealth, delegate(SharedData val4, float value) { val4.m_attack.m_attackHealth = value; }); statcfg("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackHealthPercentage, delegate(SharedData val4, float value) { val4.m_attack.m_attackHealthPercentage = value; }); } skillType = shared.m_skillType; if (skillType - 9 <= 1) { statcfg("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackEitr, delegate(SharedData val4, float value) { val4.m_attack.m_attackEitr = value; }); } if ((itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg("Knockback", "Knockback of " + englishName + ".", (SharedData val4) => val4.m_attackForce, delegate(SharedData val4, float value) { val4.m_attackForce = value; }); statcfg("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData val4) => val4.m_backstabBonus, delegate(SharedData val4, float value) { val4.m_backstabBonus = value; }); statcfg("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData val4) => val4.m_attack.m_attackStamina, delegate(SharedData val4, float value) { val4.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 val4) => val4.m_attack.m_projectileBursts, delegate(SharedData val4, int value) { val4.m_attack.m_projectileBursts = value; }); statcfg("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData val4) => val4.m_attack.m_burstInterval, delegate(SharedData val4, float value) { val4.m_attack.m_burstInterval = value; }); statcfg("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileAccuracyMin, delegate(SharedData val4, float value) { val4.m_attack.m_projectileAccuracyMin = value; }); statcfg("Accuracy", "Accuracy for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileAccuracy, delegate(SharedData val4, float value) { val4.m_attack.m_projectileAccuracy = value; }); statcfg("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileVelMin, delegate(SharedData val4, float value) { val4.m_attack.m_projectileVelMin = value; }); statcfg("Velocity", "Velocity for " + englishName + ".", (SharedData val4) => val4.m_attack.m_projectileVel, delegate(SharedData val4, float value) { val4.m_attack.m_projectileVel = value; }); statcfg("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData val4) => val4.m_attack.m_drawDurationMin, delegate(SharedData val4, float value) { val4.m_attack.m_drawDurationMin = value; }); statcfg("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData val4) => val4.m_attack.m_drawStaminaDrain, delegate(SharedData val4, float value) { val4.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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { 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 val4) => readDmg(val4.m_damages), delegate(SharedData val4, float value) { setDmg(ref val4.m_damages, value); }); statcfg(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData val4) => readDmg(val4.m_damagesPerLevel), delegate(SharedData val4, float value) { setDmg(ref val4.m_damagesPerLevel, value); }); } bool TraderBrowsability() { return item.traderConfig.trader.Value != Trader.None; } void statcfg(string configName, string description, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 0 })] Func readDefault, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 0 })] Action setValue) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0083: 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 += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { ApplyConfig(); } }; void ApplyConfig() { item.ApplyToAllInstances(delegate(ItemData val4) { setValue(val4.m_shared, cfg2.Value); }); } } [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 0 })] ConfigEntry traderConfig(string name2, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] T value, string desc) { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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 val4 = config(englishName, name2, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 })); val4.SettingChanged += [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object _, EventArgs _) => { item.ReloadTraderConfiguration(); }; return val4; } } 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 var 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 var 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 var 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsByType((FindObjectsSortMode)0) 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Inventory i) => i.GetAllItems()))) { if (item.m_shared.m_name == name) { callback(item); } } } public void ApplyToAllInstances(Action callback) { ApplyToAllInstances(Prefab, callback); } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] [return: <040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] 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_045a: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Unknown result type (might be due to invalid IL or missing references) //IL_0492: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Expected O, but got Unknown activeRecipes[this] = new Dictionary>(); itemCraftConfigs.TryGetValue(this, out var 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 { 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); if (1 == 0) { } Trader trader = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None)); if (1 == 0) { } 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 var value)) { return; } IEnumerable source; if (!itemCraftConfigs.TryGetValue(value, out var 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([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (KeyValuePair c) => { CraftingTable value3 = c.Value.table.Value; if (1 == 0) { } bool result; switch (value3) { case CraftingTable.Disabled: case CraftingTable.Inventory: result = false; break; case CraftingTable.Custom: result = c.Value.customTable.Value == stationName; break; default: result = getInternalName(c.Value.table.Value) == stationName; break; } if (1 == 0) { } return result; }) 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([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 2, 1, 1, 1, 2 })] 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([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(new byte[] { 1, 1, 1, 1, 2 })] Dictionary> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out var 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 bool Patch_RequirementGetAmount(Requirement __instance, int qualityLevel, ref int __result) { if (requirementQuality.TryGetValue(__instance, out var value)) { __result = ((value.quality == qualityLevel) ? __instance.m_amountPerLevel : 0); return false; } return true; } internal static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (Item registeredItem in registeredItems) { registeredItem.AssignDropToCreature(); } } public void AssignDropToCreature() { foreach (KeyValuePair characterDrop in characterDrops) { if (Object.op_Implicit((Object)(object)characterDrop.Key)) { characterDrop.Key.m_drops.Remove(characterDrop.Value); } } characterDrops.Clear(); SerializedDrop serializedDrop = new SerializedDrop(DropsFrom.Drops); if (itemDropConfigs.TryGetValue(this, out var value)) { serializedDrop = new SerializedDrop(value.Value); } foreach (KeyValuePair item in serializedDrop.toCharacterDrops(ZNetScene.s_instance, Prefab)) { CharacterDrop val = ((Component)item.Key).GetComponent(); if (val == null) { val = ((Component)item.Key).gameObject.AddComponent(); } val.m_drops.Add(item.Value); characterDrops.Add(val, item.Value); } } public void UpdateCharacterDrop() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { AssignDropToCreature(); } } public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null) { SnapshotItem(Prefab.GetComponent(), lightIntensity, cameraRotation, itemRotation); } public static void SnapshotItem(ItemDrop item, float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null) { if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { Do(); } else { ((MonoBehaviour)plugin).StartCoroutine(Delay()); } IEnumerator Delay() { yield return null; Do(); } void Do() { //IL_0019: 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_008b: 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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: 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_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: 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_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0227: 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) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02aa: Unknown result type (might be due to invalid IL or missing references) //IL_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02c9: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_030d: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0358: Expected O, but got Unknown //IL_035a: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) //IL_0398: Unknown result type (might be due to invalid IL or missing references) Camera component = new GameObject("Camera", new Type[1] { typeof(Camera) }).GetComponent(); component.backgroundColor = Color.clear; component.clearFlags = (CameraClearFlags)2; component.fieldOfView = 0.5f; component.farClipPlane = 10000000f; component.cullingMask = 1073741824; ((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(90f, 0f, 45f)); Light component2 = new GameObject("Light", new Type[1] { typeof(Light) }).GetComponent(); ((Component)component2).transform.rotation = Quaternion.Euler(150f, 0f, -5f); component2.type = (LightType)1; component2.cullingMask = 1073741824; component2.intensity = lightIntensity; Rect val = default(Rect); ((Rect)(ref val))..ctor(0f, 0f, 64f, 64f); Transform val2 = ((Component)item).transform.Find("attach"); GameObject val3; if (val2 != null) { val3 = Object.Instantiate(((Component)val2).gameObject); } else { ZNetView.m_forceDisableInit = true; val3 = Object.Instantiate(((Component)item).gameObject); ZNetView.m_forceDisableInit = false; } if (itemRotation.HasValue) { val3.transform.rotation = itemRotation.Value; } Transform[] componentsInChildren = val3.GetComponentsInChildren(); foreach (Transform val4 in componentsInChildren) { ((Component)val4).gameObject.layer = 30; } Renderer[] componentsInChildren2 = val3.GetComponentsInChildren(); Vector3 val5 = componentsInChildren2.Aggregate(Vector3.positiveInfinity, [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_0017: Unknown result type (might be due to invalid IL or missing references) Vector3 result; if (!(renderer is ParticleSystemRenderer)) { Bounds bounds = renderer.bounds; result = Vector3.Min(cur, ((Bounds)(ref bounds)).min); } else { result = cur; } return result; }); Vector3 val6 = componentsInChildren2.Aggregate(Vector3.negativeInfinity, [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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_0017: Unknown result type (might be due to invalid IL or missing references) Vector3 result; if (!(renderer is ParticleSystemRenderer)) { Bounds bounds = renderer.bounds; result = Vector3.Max(cur, ((Bounds)(ref bounds)).max); } else { result = cur; } return result; }); Vector3 val7 = val6 - val5; component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height); float num = Mathf.Max(val7.x, val7.z); float num2 = Mathf.Min(val7.x, val7.z); float num3 = (num + num2) / Mathf.Sqrt(2f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)); Transform transform = ((Component)component).transform; Vector3 val8 = (val5 + val6) / 2f; val8.y = val6.y; transform.position = val8 + new Vector3(0f, num3, 0f); ((Component)component2).transform.position = transform.position + new Vector3(-2f, 0f, 0.2f) / 3f * (0f - num3); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val9 = new Texture2D((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height, (TextureFormat)4, false); val9.ReadPixels(val, 0, 0); val9.Apply(); RenderTexture.active = active; item.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { Sprite.Create(val9, val, new Vector2(0.5f, 0.5f)) }; Object.DestroyImmediate((Object)(object)val3); component.targetTexture.Release(); Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); } } private static bool CheckItemIsUpgrade(InventoryGui gui) { ItemData itemData = ((RecipeDataPair)(ref gui.m_selectedRecipe)).ItemData; return itemData != null && itemData.m_quality > 0; } internal static IEnumerable Transpile_InventoryGui(IEnumerable instructions) { List instrs = instructions.ToList(); FieldInfo amountField = AccessTools.DeclaredField(typeof(Recipe), "m_amount"); int i = 0; while (i < instrs.Count) { yield return instrs[i]; if (i > 1 && instrs[i - 2].opcode == OpCodes.Ldfld && CodeInstructionExtensions.OperandIs(instrs[i - 2], (MemberInfo)amountField) && instrs[i - 1].opcode == OpCodes.Ldc_I4_1 && instrs[i].operand is Label) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)AccessTools.DeclaredMethod(typeof(Item), "CheckItemIsUpgrade", (Type[])null, (Type[])null)); yield return new CodeInstruction(OpCodes.Brtrue, instrs[i].operand); } int num = i + 1; i = num; } } private static Action drawRequirementsConfigTable(Item item, bool isUpgrade) { return delegate(ConfigEntryBase cfg) { bool locked = cfg.Description.Tags.Select([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object a) => (a.GetType().Name == "ConfigurationManagerAttributes") ? ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a)) : ((bool?)null)).FirstOrDefault((bool? v) => v.HasValue) == true; List newReqs = new List(); bool wasUpdated = false; int RightColumnWidth = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonPublic: true) .Invoke(configManager, Array.Empty()) ?? ((object)130)); GUILayout.BeginVertical(Array.Empty()); List reqs = new SerializedRequirements((string)cfg.BoxedValue).Reqs; bool flag = false; int maxQuality = item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality; if (isUpgrade && maxQuality > 2) { flag = reqs.Any((Requirement r) => r.quality > 0); if (flag) { int count = reqs.Count; for (int num = 0; num < count; num++) { if (reqs[num].quality == 0) { List list = reqs; int index = num; Requirement value = reqs[num]; value.quality = 2; list[index] = value; for (int num2 = 3; num2 <= maxQuality; num2++) { List list2 = reqs; value = reqs[num]; value.quality = num2; list2.Add(value); } } } } if (flag != GUILayout.Toggle(flag, "Individual costs per upgrade level", Array.Empty())) { flag = !flag; wasUpdated = true; if (flag) { int count2 = reqs.Count; for (int num3 = 0; num3 < count2; num3++) { List list3 = reqs; int index2 = num3; Requirement value = reqs[num3]; value.quality = 2; list3[index2] = value; for (int num4 = 3; num4 <= maxQuality; num4++) { List list4 = reqs; value = reqs[num3]; value.quality = num4; list4.Add(value); } } } else { reqs.RemoveAll((Requirement req) => req.quality > 1); for (int num5 = 0; num5 < reqs.Count; num5++) { List list5 = reqs; int index3 = num5; Requirement value = reqs[num5]; value.quality = 0; list5[index3] = value; } } } } if (flag) { for (int num6 = 2; num6 <= maxQuality; num6++) { GUILayout.Label($"Upgrade level {num6 - 1}:", Array.Empty()); DisplayQuality(num6); } } else { DisplayQuality(0); } GUILayout.EndVertical(); if (wasUpdated) { cfg.BoxedValue = new SerializedRequirements(newReqs).ToString(); } void DisplayQuality(int quality) { //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_008b: Expected O, but got Unknown //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Expected O, but got Unknown //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Expected O, but got Unknown foreach (Requirement item2 in reqs.Where((Requirement r) => r.quality == quality)) { GUILayout.BeginHorizontal(Array.Empty()); int num7 = item2.amount; if (int.TryParse(GUILayout.TextField(num7.ToString(), new GUIStyle(GUI.skin.textField) { fixedWidth = 40f }, Array.Empty()), out var result) && result != num7 && !locked) { num7 = result; wasUpdated = true; } string text = GUILayout.TextField(item2.itemName, new GUIStyle(GUI.skin.textField) { fixedWidth = RightColumnWidth - 40 - 21 - 21 - 9 }, Array.Empty()); string text2 = (locked ? item2.itemName : text); wasUpdated = wasUpdated || text2 != item2.itemName; if (GUILayout.Button("x", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()) && !locked) { wasUpdated = true; } else { newReqs.Add(new Requirement { amount = num7, itemName = text2, quality = quality }); } if (GUILayout.Button("+", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()) && !locked) { wasUpdated = true; newReqs.Add(new Requirement { amount = 1, itemName = "", quality = quality }); } GUILayout.EndHorizontal(); } } }; } private static void drawDropsConfigTable(ConfigEntryBase cfg) { //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Expected O, but got Unknown //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Expected O, but got Unknown //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Expected O, but got Unknown //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Expected O, but got Unknown //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Expected O, but got Unknown bool valueOrDefault = cfg.Description.Tags.Select([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (object a) => (a.GetType().Name == "ConfigurationManagerAttributes") ? ((bool?)a.GetType().GetField("ReadOnly")?.GetValue(a)) : ((bool?)null)).FirstOrDefault((bool? v) => v.HasValue) == true; List list = new List(); bool flag = false; int num = (int)(configManager?.GetType().GetProperty("RightColumnWidth", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(nonPublic: true) .Invoke(configManager, Array.Empty()) ?? ((object)130)); GUILayout.BeginVertical(Array.Empty()); foreach (DropTarget item in new SerializedDrop((string)cfg.BoxedValue).Drops.DefaultIfEmpty(new DropTarget { min = 1, max = 1, creature = "", chance = 1f })) { GUILayout.BeginHorizontal(Array.Empty()); string text = GUILayout.TextField(item.creature, new GUIStyle(GUI.skin.textField) { fixedWidth = num - 21 - 21 - 6 }, Array.Empty()); string text2 = (valueOrDefault ? item.creature : text); flag = flag || text2 != item.creature; bool flag2 = GUILayout.Button("x", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()); bool flag3 = GUILayout.Button("+", new GUIStyle(GUI.skin.button) { fixedWidth = 21f }, Array.Empty()); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); GUILayout.Label("Chance: ", Array.Empty()); float num2 = item.chance; if (float.TryParse(GUILayout.TextField((num2 * 100f).ToString(CultureInfo.InvariantCulture), new GUIStyle(GUI.skin.textField) { fixedWidth = 45f }, Array.Empty()), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && !Mathf.Approximately(result / 100f, num2) && !valueOrDefault) { num2 = result / 100f; flag = true; } GUILayout.Label("% Amount: ", Array.Empty()); int num3 = item.min; if (int.TryParse(GUILayout.TextField(num3.ToString(), new GUIStyle(GUI.skin.textField) { fixedWidth = 35f }, Array.Empty()), out var result2) && result2 != num3 && !valueOrDefault) { num3 = result2; flag = true; } GUILayout.Label(" - ", Array.Empty()); int num4 = item.max; if (int.TryParse(GUILayout.TextField(num4.ToString(), new GUIStyle(GUI.skin.textField) { fixedWidth = 35f }, Array.Empty()), out var result3) && result3 != num4 && !valueOrDefault) { num4 = result3; flag = true; } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(Array.Empty()); bool flag4 = item.levelMultiplier; if (GUILayout.Toggle(flag4, "Level scaling drop amount", Array.Empty()) != flag4) { flag4 = !flag4; flag = true; } GUILayout.EndHorizontal(); if (flag2 && !valueOrDefault) { flag = true; } else { list.Add(new DropTarget { creature = text2, min = num3, max = num4, chance = num2, levelMultiplier = flag4 }); } if (flag3 && !valueOrDefault) { flag = true; list.Add(new DropTarget { min = 1, max = 1, creature = "", chance = 1f, levelMultiplier = true }); } } GUILayout.EndVertical(); if (flag) { cfg.BoxedValue = new SerializedDrop(list).ToString(); } } private static ConfigEntry config<[<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] T>(string group, string name, T value, ConfigDescription description) { ConfigEntry val = plugin.Config.Bind(group, name, value, description); configSync?.GetType().GetMethod("AddConfigEntry").MakeGenericMethod(typeof(T)) .Invoke(configSync, new object[1] { val }); return val; } private static ConfigEntry config<[<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] T>(string group, string name, T value, string description) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty())); } } [PublicAPI] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public class LocalizeKey { private static readonly List keys = new List(); public readonly string Key; public readonly Dictionary Localizations = new Dictionary(); public LocalizeKey(string key) { Key = key.Replace("$", ""); keys.Add(this); } public void Alias(string alias) { Localizations.Clear(); if (!alias.Contains("$")) { alias = "$" + alias; } Localizations["alias"] = alias; if (Localization.m_instance != null) { Localization.instance.AddWord(Key, Localization.instance.Localize(alias)); } } public LocalizeKey English(string key) { return addForLang("English", key); } public LocalizeKey Swedish(string key) { return addForLang("Swedish", key); } public LocalizeKey French(string key) { return addForLang("French", key); } public LocalizeKey Italian(string key) { return addForLang("Italian", key); } public LocalizeKey German(string key) { return addForLang("German", key); } public LocalizeKey Spanish(string key) { return addForLang("Spanish", key); } public LocalizeKey Russian(string key) { return addForLang("Russian", key); } public LocalizeKey Romanian(string key) { return addForLang("Romanian", key); } public LocalizeKey Bulgarian(string key) { return addForLang("Bulgarian", key); } public LocalizeKey Macedonian(string key) { return addForLang("Macedonian", key); } public LocalizeKey Finnish(string key) { return addForLang("Finnish", key); } public LocalizeKey Danish(string key) { return addForLang("Danish", key); } public LocalizeKey Norwegian(string key) { return addForLang("Norwegian", key); } public LocalizeKey Icelandic(string key) { return addForLang("Icelandic", key); } public LocalizeKey Turkish(string key) { return addForLang("Turkish", key); } public LocalizeKey Lithuanian(string key) { return addForLang("Lithuanian", key); } public LocalizeKey Czech(string key) { return addForLang("Czech", key); } public LocalizeKey Hungarian(string key) { return addForLang("Hungarian", key); } public LocalizeKey Slovak(string key) { return addForLang("Slovak", key); } public LocalizeKey Polish(string key) { return addForLang("Polish", key); } public LocalizeKey Dutch(string key) { return addForLang("Dutch", key); } public LocalizeKey Portuguese_European(string key) { return addForLang("Portuguese_European", key); } public LocalizeKey Portuguese_Brazilian(string key) { return addForLang("Portuguese_Brazilian", key); } public LocalizeKey Chinese(string key) { return addForLang("Chinese", key); } public LocalizeKey Japanese(string key) { return addForLang("Japanese", key); } public LocalizeKey Korean(string key) { return addForLang("Korean", key); } public LocalizeKey Hindi(string key) { return addForLang("Hindi", key); } public LocalizeKey Thai(string key) { return addForLang("Thai", key); } public LocalizeKey Abenaki(string key) { return addForLang("Abenaki", key); } public LocalizeKey Croatian(string key) { return addForLang("Croatian", key); } public LocalizeKey Georgian(string key) { return addForLang("Georgian", key); } public LocalizeKey Greek(string key) { return addForLang("Greek", key); } public LocalizeKey Serbian(string key) { return addForLang("Serbian", key); } public LocalizeKey Ukrainian(string key) { return addForLang("Ukrainian", key); } private LocalizeKey addForLang(string lang, string value) { Localizations[lang] = value; if (Localization.m_instance != null) { if (Localization.instance.GetSelectedLanguage() == lang) { Localization.instance.AddWord(Key, value); } else if (lang == "English" && !Localization.instance.m_translations.ContainsKey(Key)) { Localization.instance.AddWord(Key, value); } } return this; } [HarmonyPriority(300)] internal static void AddLocalizedKeys(Localization __instance, string language) { foreach (LocalizeKey key in keys) { string value2; if (key.Localizations.TryGetValue(language, out var value) || key.Localizations.TryGetValue("English", out value)) { __instance.AddWord(key.Key, value); } else if (key.Localizations.TryGetValue("alias", out value2)) { __instance.AddWord(key.Key, Localization.instance.Localize(value2)); } } } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public static class LocalizationCache { private static readonly Dictionary localizations = new Dictionary(); internal static void LocalizationPostfix(Localization __instance, string language) { string key = localizations.FirstOrDefault([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (KeyValuePair l) => l.Value == __instance).Key; if (key != null) { localizations.Remove(key); } if (!localizations.ContainsKey(language)) { localizations.Add(language, __instance); } } public static Localization ForLanguage([<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] string language = null) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (localizations.TryGetValue(language ?? PlayerPrefs.GetString("language", "English"), out var value)) { return value; } value = new Localization(); if (language != null) { value.SetupLanguage(language); } return value; } } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [PublicAPI] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public static class PrefabManager { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] private struct BundleId { [UsedImplicitly] public string assetBundleFileName; [UsedImplicitly] public string folderName; } private static readonly Dictionary bundleCache; private static readonly List prefabs; private static readonly List ZnetOnlyPrefabs; internal static readonly Dictionary> CustomTradeItems; static PrefabManager() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Expected O, but got Unknown //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Expected O, but got Unknown //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Expected O, but got Unknown //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Expected O, but got Unknown //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Expected O, but got Unknown //IL_02a5: Expected O, but got Unknown //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Expected O, but got Unknown //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Expected O, but got Unknown //IL_0388: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown //IL_03c4: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Expected O, but got Unknown //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_040d: Expected O, but got Unknown bundleCache = new Dictionary(); prefabs = new List(); ZnetOnlyPrefabs = new List(); CustomTradeItems = new Dictionary>(); Harmony val = new Harmony("org.bepinex.helpers.ItemManager"); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "CopyOtherDB", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ObjectDB), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_ObjectDBInit", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_FejdStartup", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ZNetScene), "Awake", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(PrefabManager), "Patch_ZNetSceneAwake", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(InventoryGui), "UpdateRecipe", (Type[])null, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Transpile_InventoryGui", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Requirement), "GetAmount", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_RequirementGetAmount", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Player), "GetAvailableRecipes", (Type[])null, (Type[])null), new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_GetAvailableRecipesPrefix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_GetAvailableRecipesFinalizer", (Type[])null, (Type[])null)), (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Recipe), "GetRequiredStationLevel", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_MaximumRequiredStationLevel", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Smelter), "OnAddFuel", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_OnAddSmelterInput", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Smelter), "OnAddOre", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_OnAddSmelterInput", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Trader), "GetAvailableItems", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Item), "Patch_TraderGetAvailableItems", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "SetupLanguage", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizationCache), "LocalizationPostfix", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(LocalizeKey), "AddLocalizedKeys", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } public static AssetBundle RegisterAssetBundle(string assetBundleFileName, string folderName = "assets") { BundleId key = new BundleId { assetBundleFileName = assetBundleFileName, folderName = folderName }; if (!bundleCache.TryGetValue(key, out var value)) { Dictionary dictionary = bundleCache; AssetBundle? obj = ((IEnumerable)Resources.FindObjectsOfTypeAll()).FirstOrDefault((Func)([<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(0)] (AssetBundle a) => ((Object)a).name == assetBundleFileName)) ?? AssetBundle.LoadFromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + folderName + "." + assetBundleFileName)); AssetBundle result = obj; dictionary[key] = obj; return result; } return value; } public static GameObject RegisterPrefab(string assetBundleFileName, string prefabName, string folderName = "assets") { return RegisterPrefab(RegisterAssetBundle(assetBundleFileName, folderName), prefabName); } public static GameObject RegisterPrefab(AssetBundle assets, string prefabName, bool addToObjectDb = false) { return RegisterPrefab(assets.LoadAsset(prefabName), addToObjectDb); } public static GameObject RegisterPrefab(GameObject prefab, bool addToObjectDb = false) { if (addToObjectDb) { prefabs.Add(prefab); } else { ZnetOnlyPrefabs.Add(prefab); } return prefab; } public static void AddItemToTrader(GameObject prefab, Trader trader, uint price, uint stack = 1u, [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] string requiredGlobalKey = null) { //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) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown CustomTradeItems[prefab] = new Tuple(trader, new TradeItem { m_prefab = prefab.GetComponent(), m_price = (int)price, m_stack = (int)stack, m_requiredGlobalKey = (requiredGlobalKey ?? "") }); } public static void RemoveItemFromTrader(GameObject prefab) { CustomTradeItems.Remove(prefab); } [HarmonyPriority(700)] private static void Patch_ObjectDBInit(ObjectDB __instance) { foreach (GameObject prefab in prefabs) { if (!__instance.m_items.Contains(prefab)) { __instance.m_items.Add(prefab); } SharedData shared = prefab.GetComponent().m_itemData.m_shared; RegisterStatusEffect(shared.m_attackStatusEffect); RegisterStatusEffect(shared.m_consumeStatusEffect); RegisterStatusEffect(shared.m_equipStatusEffect); RegisterStatusEffect(shared.m_setStatusEffect); } __instance.UpdateRegisters(); [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] void RegisterStatusEffect(StatusEffect statusEffect) { if (statusEffect != null && !Object.op_Implicit((Object)(object)__instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(((Object)statusEffect).name)))) { __instance.m_StatusEffects.Add(statusEffect); } } } [HarmonyPriority(700)] private static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (GameObject item in prefabs.Concat(ZnetOnlyPrefabs)) { if (!__instance.m_prefabs.Contains(item)) { __instance.m_prefabs.Add(item); } } } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(2)] [PublicAPI] [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] public class Conversion { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(0)] [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] internal class ConversionConfig { public ConfigEntry input = null; [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(2)] public string activePiece; public ConfigEntry piece = null; public ConfigEntry customPiece = null; } [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public string Input = null; public ConversionPiece Piece; internal string customPiece = null; internal ConversionConfig config; public string Custom { get { return customPiece; } set { customPiece = value; Piece = ConversionPiece.Custom; } } [<4aa5bef7-1be0-456e-b57f-5048df7109d2>NullableContext(1)] public Conversion(Item outputItem) { outputItem.Conversions.Add(this); } } public static class ItemManagerVersion { [<040cafbb-8436-4a5b-a3c8-5aa8abcf3260>Nullable(1)] public const string Version = "1.2.9"; } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] 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 <70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContextAttribute : Attribute { public readonly byte Flag; public <70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [CompilerGenerated] [Embedded] internal sealed class <9822b6a9-3e76-4af8-8534-054f934867e2>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <9822b6a9-3e76-4af8-8534-054f934867e2>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [PublicAPI] [Nullable(0)] internal abstract class OwnConfigEntryBase { [Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] [Nullable(0)] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] internal class SyncedConfigEntry<[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; } } } [Nullable(0)] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(2)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [Nullable(1)] public readonly string Identifier; [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; [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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; }; } } [Nullable(0)] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [PublicAPI] internal sealed class CustomSyncedValue<[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; } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [PublicAPI] [Nullable(0)] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] private static class SnatchCurrentlyHandlingRPC { [Nullable(2)] public static ZRpc currentRpc; [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] internal static class RegisterRPCPatch { [HarmonyPostfix] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] 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()); } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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)); } } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] private static class RegisterClientRPCPatch { [HarmonyPostfix] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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); } } } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] private class ParsedConfigs { [Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary configValues = new Dictionary(); [Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] 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; } } [Nullable(0)] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { [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); } } } [HarmonyPrefix] [HarmonyPriority(800)] private static void Prefix([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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } [Nullable(0)] private class PackageEntry { public string section = null; public string key = null; public Type type = null; [Nullable(2)] public object value; } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [HarmonyPrefix] 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; } } [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] 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; } } [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; [Nullable(2)] public string DisplayName; [Nullable(2)] public string CurrentVersion; [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; [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>(); [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; [Nullable(2)] [method: <70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(2)] [field: Nullable(2)] public event Action SourceOfTruthChanged; [Nullable(2)] [method: <70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(2)] [field: 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<[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 += [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (object _, EventArgs _) => { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(0L, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry<[Nullable(0)] T>(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (object _, EventArgs _) => { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(0L, 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(([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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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 != 0) { list = list.Where([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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: Nullable(2)] private static OwnConfigEntryBase configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } [return: Nullable(new byte[] { 2, 1 })] public static SyncedConfigEntry ConfigData<[Nullable(2)] T>(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute<[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([Nullable(new byte[] { 2, 1 })] IEnumerable configs = null, [Nullable(new byte[] { 2, 1 })] IEnumerable customValues = null, [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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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, [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(); } } [HarmonyPatch] [<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(1)] [Nullable(0)] [PublicAPI] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; [Nullable(2)] private string displayName; [Nullable(2)] private string currentVersion; [Nullable(2)] private string minimumRequiredVersion; public bool ModRequired = true; [Nullable(2)] private string ReceivedCurrentVersion; [Nullable(2)] private string ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); [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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([Nullable(2)] ZRpc rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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, [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; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] 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)([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>NullableContext(0)] (ZRpc rpc, [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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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([<70e304f6-b6f3-47b6-9773-73e3ea39ca7c>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] [<7e3686e4-a8f6-46a9-8375-6420510d2b45>Embedded] internal sealed class <7e3686e4-a8f6-46a9-8375-6420510d2b45>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<7e3686e4-a8f6-46a9-8375-6420510d2b45>Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<7e3686e4-a8f6-46a9-8375-6420510d2b45>Embedded] internal sealed class <198a2ca5-29ee-4a3f-8541-78dde289ff8d>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <198a2ca5-29ee-4a3f-8541-78dde289ff8d>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <198a2ca5-29ee-4a3f-8541-78dde289ff8d>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [CompilerGenerated] [<7e3686e4-a8f6-46a9-8375-6420510d2b45>Embedded] internal sealed class <16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContextAttribute : Attribute { public readonly byte Flag; public <16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContextAttribute(byte P_0) { Flag = P_0; } } [<7e3686e4-a8f6-46a9-8375-6420510d2b45>Embedded] [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace YamlDotNet { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.Name) { this.provider = provider; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public override object GetFormat(Type formatType) { return provider.GetFormat(formatType); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class Polyfills { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool Contains(this string source, char c) { return source.IndexOf(c) != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EndsWith(this string source, char c) { if (source.Length > 0) { return source[source.Length - 1] == c; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool StartsWith(this string source, char c) { if (source.Length > 0) { return source[0] == c; } return false; } } internal static class PropertyInfoExtensions { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class ReflectionExtensions { private static readonly Func IsInstance = (PropertyInfo property) => !(property.GetMethod ?? property.SetMethod).IsStatic; private static readonly Func IsInstancePublic = (PropertyInfo property) => IsInstance(property) && (property.GetMethod ?? property.SetMethod).IsPublic; [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static Type GetImplementationOfOpenGenericInterface(this Type type, Type openGenericType) { if (!openGenericType.IsGenericType || !openGenericType.IsInterface) { throw new ArgumentException("The type must be a generic type definition and an interface", "openGenericType"); } if (IsGenericDefinitionOfType(type, openGenericType)) { return type; } return type.FindInterfaces([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Type t, object context) => IsGenericDefinitionOfType(t, context), openGenericType).FirstOrDefault(); static bool IsGenericDefinitionOfType(Type t, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object context) { if (t.IsGenericType) { return t.GetGenericTypeDefinition() == (Type)context; } return false; } } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsRequired(this MemberInfo member) { return member.GetCustomAttributes(inherit: true).Any([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.RequiredMemberAttribute"); } 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 bool IsAssignableFrom(this Type type, Type source) { return type.IsAssignableFrom(source.GetTypeInfo()); } public static bool IsAssignableFrom(this Type type, TypeInfo source) { return type.GetTypeInfo().IsAssignableFrom(source); } public static TypeCode GetTypeCode(this Type type) { if (type.IsEnum()) { type = Enum.GetUnderlyingType(type); } if (type == typeof(bool)) { return TypeCode.Boolean; } if (type == typeof(char)) { return TypeCode.Char; } if (type == typeof(sbyte)) { return TypeCode.SByte; } if (type == typeof(byte)) { return TypeCode.Byte; } if (type == typeof(short)) { return TypeCode.Int16; } if (type == typeof(ushort)) { return TypeCode.UInt16; } if (type == typeof(int)) { return TypeCode.Int32; } if (type == typeof(uint)) { return TypeCode.UInt32; } if (type == typeof(long)) { return TypeCode.Int64; } if (type == typeof(ulong)) { return TypeCode.UInt64; } if (type == typeof(float)) { return TypeCode.Single; } if (type == typeof(double)) { return TypeCode.Double; } if (type == typeof(decimal)) { return TypeCode.Decimal; } if (type == typeof(DateTime)) { return TypeCode.DateTime; } if (type == typeof(string)) { return TypeCode.String; } return TypeCode.Object; } public static bool IsDbNull(this object value) { return value?.GetType()?.FullName == "System.DBNull"; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (PropertyInfo p) => p.Name == name); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static FieldInfo GetPublicStaticField(this Type type, string name) { return type.GetRuntimeField(name); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { Func predicate = (includeNonPublic ? IsInstance : IsInstancePublic); if (!type.IsInterface()) { return type.GetRuntimeProperties().Where(predicate); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Type i) => i.GetRuntimeProperties().Where(predicate)); } public static IEnumerable GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return from f in type.GetRuntimeFields() where !f.IsStatic && f.IsPublic select f; } public static IEnumerable GetPublicStaticMethods(this Type type) { return from m in type.GetRuntimeMethods() where m.IsPublic && m.IsStatic select m; } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetRuntimeMethods().FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (MethodInfo m) => !m.IsPublic && m.IsStatic && m.Name.Equals(name)) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetRuntimeMethods().FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (MethodInfo m) => { if (m.IsPublic && m.IsStatic && m.Name.Equals(name)) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == parameterTypes.Length) { return parameters.Zip(parameterTypes, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (ParameterInfo pi, Type pt) => pi.ParameterType == pt).All((bool r) => r); } return false; } return false; }); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static MethodInfo GetPublicInstanceMethod(this Type type, string name) { return type.GetRuntimeMethods().FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (MethodInfo m) => m.IsPublic && !m.IsStatic && m.Name.Equals(name)); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static MethodInfo GetGetMethod(this PropertyInfo property, bool nonPublic) { MethodInfo methodInfo = property.GetMethod; if (!nonPublic && !methodInfo.IsPublic) { methodInfo = null; } return methodInfo; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static MethodInfo GetSetMethod(this PropertyInfo property) { return property.SetMethod; } public static IEnumerable GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static bool IsInstanceOf(this Type type, object o) { if (!(o.GetType() == type)) { return o.GetType().GetTypeInfo().IsSubclassOf(type); } return true; } public static Attribute[] GetAllCustomAttributes<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TAttribute>(this PropertyInfo member) { return Attribute.GetCustomAttributes(member, typeof(TAttribute), inherit: true); } public static bool AcceptsNull(this MemberInfo member) { object[] customAttributes = member.DeclaringType.GetCustomAttributes(inherit: true); object obj = customAttributes.FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); int num = 0; if (obj != null) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty("Flag"); num = (byte)property.GetValue(obj); } object[] customAttributes2 = member.GetCustomAttributes(inherit: true); object obj2 = customAttributes2.FirstOrDefault([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableAttribute"); PropertyInfo propertyInfo = (obj2?.GetType())?.GetProperty("NullableFlags"); byte[] source = (byte[])propertyInfo.GetValue(obj2); return source.Any((byte x) => x == 2) || num == 2; } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal abstract class BuilderSkeleton<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TBuilder> where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = 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; internal YamlFormatter yamlFormatter = YamlFormatter.Default; 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 WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention; 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TArgument, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(TextReader input) { return Deserialize(new Parser(input)); } public T Deserialize<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(IParser parser) { return (T)Deserialize(parser, typeof(T)); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Deserialize(string input) { return Deserialize(input); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Deserialize(TextReader input) { return Deserialize(input); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Deserialize(IParser parser) { return Deserialize(parser); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 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; private bool enforceNullability; private bool caseInsensitivePropertyMatching; private bool enforceRequiredProperties; 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, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer(enumNamingConvention, BuildTypeInspector()) }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value, enumNamingConvention, BuildTypeInspector()) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties, BuildTypeConverters()) }, { typeof(FsharpListNodeDeserializer), (Nothing _) => new FsharpListNodeDeserializer(BuildTypeInspector(), enumNamingConvention) } }; 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(); } public 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public DeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public DeserializerBuilder WithEnforceRequiredMembers() { enforceRequiredProperties = true; return this; } public DeserializerBuilder WithoutNodeTypeResolver<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TInterface, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 (!DictionaryExtensions.TryAdd(typeMappings, typeFromHandle, typeFromHandle2)) { typeMappings[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() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] T>() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IAliasProvider { AnchorName GetAlias(object target); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IDeserializer { T Deserialize<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(string input); T Deserialize<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(TextReader input); T Deserialize<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(IParser parser); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(string input); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(TextReader input); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(IParser parser); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(string input, Type type); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(TextReader input, Type type); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Deserialize(IParser parser, Type type); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface INamingConvention { string Apply(string value); string Reverse(string value); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface INodeTypeResolver { bool Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] NodeEvent nodeEvent, ref Type currentType); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IObjectAccessor { void Set(string name, object target, object value); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Read(string name, object target); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IObjectDescriptor { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object Value { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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."); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IObjectFactory { object Create(Type type); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out IDictionary dictionary, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments); Type GetValueType(Type type); void ExecuteOnDeserializing(object value); void ExecuteOnDeserialized(object value); void ExecuteOnSerializing(object value); void ExecuteOnSerialized(object value); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IObjectGraphTraversalStrategy { void Traverse<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext> { bool Enter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); void VisitScalar(IObjectDescriptor scalar, TContext context, ObjectSerializer serializer); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context, ObjectSerializer serializer); void VisitMappingEnd(IObjectDescriptor mapping, TContext context, ObjectSerializer serializer); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context, ObjectSerializer serializer); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context, ObjectSerializer serializer); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IPropertyDescriptor { string Name { get; } bool AllowNulls { get; } bool CanWrite { get; } Type Type { get; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } bool Required { get; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T GetCustomAttribute() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value); } internal interface IRegistrationLocationSelectionSyntax<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ISerializer { string Serialize([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph); string Serialize([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type); void Serialize(TextWriter writer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph); void Serialize(TextWriter writer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type); void Serialize(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph); void Serialize(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ITypeInspector { IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container); IPropertyDescriptor GetProperty(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching); string GetEnumName(Type enumType, string name); string GetEnumValue(object enumValue); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ITypeResolver { Type Resolve(Type staticType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object actualValue); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IValueDeserializer { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 2 })] event Action ValueAvailable; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] internal interface IValueSerializer { void SerializeValue([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] IEmitter emitter, object value, Type type); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] internal delegate object ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object value, Type type = null); [Obsolete("Please use IYamlConvertible instead")] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IYamlTypeConverter { bool Accepts(Type type); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer); void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class LazyComponentRegistrationList<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TArgument, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponent> : IEnumerable>, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] private readonly LazyComponentRegistrationList registrations; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 0, 0 })] private readonly LazyComponentRegistration newRegistration; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public RegistrationLocationSelector(LazyComponentRegistrationList registrations, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] private readonly LazyComponentRegistrationList registrations; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 0, 0 })] private readonly TrackingLazyComponentRegistration newRegistration; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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([<16ed2a80-a41e-45a7-8f08-0e42134982a5>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."); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TArgument, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { return registrations.InReverseOrder.Aggregate(innerComponent, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (TComponent inner, Func factory) => factory(argumentBuilder(inner))); } public static List BuildComponentList<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations) { return registrations.Select([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TArgument, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TComponent>(this LazyComponentRegistrationList registrations, TArgument argument) { return registrations.Select([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Func factory) => factory(argument)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class ObjectDescriptor : IObjectDescriptor { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Value { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public bool AllowNulls => baseDescriptor.AllowNulls; public string Name { get; set; } public bool Required => baseDescriptor.Required; public Type Type => baseDescriptor.Type; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return baseDescriptor.ConverterType; } } 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value) { baseDescriptor.Write(target, value); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public T GetCustomAttribute() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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 string Serialize([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public string Serialize([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph, type); return stringWriter.ToString(); } public void Serialize(TextWriter writer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public void Serialize(TextWriter writer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private void EmitDocument([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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()); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1 })] internal sealed class SerializerBuilder : BuilderSkeleton { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] public void SerializeValue([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new EmittingObjectGraphVisitor(eventEmitter), [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing), NestedObjectSerializer); } traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 Dictionary tagMappings = new Dictionary(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private ScalarStyle defaultScalarStyle; 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, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; 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 WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public SerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, BuildTypeInspector()))); return Self; } public SerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((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().WithUtf16SurrogatePairs(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(WrapperFactory, IObjectGraphVisitor, 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 typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } 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()); } public 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; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal abstract class StaticBuilderSkeleton<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TBuilder> where TBuilder : StaticBuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; 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 WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TTypeInspector>(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal abstract class StaticContext { public virtual bool IsKnownType(Type type) { throw new NotImplementedException(); } public virtual ITypeResolver GetTypeResolver() { throw new NotImplementedException(); } public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1 })] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; private bool enforceNullability; private bool caseInsensitivePropertyMatching; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base(context.GetTypeResolver()) { 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, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { 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, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties: false, BuildTypeConverters()) } }; 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(); } public 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public StaticDeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public StaticDeserializerBuilder WithoutNodeDeserializer<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TInterface, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 + "'."); } typeMappings[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, enumNamingConvention, BuildTypeInspector())); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1 })] internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] public void SerializeValue([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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), NestedObjectSerializer); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new EmittingObjectGraphVisitor(eventEmitter), [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 Dictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; private ScalarStyle defaultScalarStyle; 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, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory); } public StaticSerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public StaticSerializerBuilder WithQuotingNecessaryStrings() { quoteNecessaryStrings = true; return this; } public StaticSerializerBuilder WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TEventEmitter>(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public StaticSerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, BuildTypeInspector()))); return Self; } public StaticSerializerBuilder WithEventEmitter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings: false, ScalarStyle.Plain, YamlFormatter.Default, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((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().WithUtf16SurrogatePairs(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 WithPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(WrapperFactory, IObjectGraphVisitor, 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 typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TObjectGraphVisitor>(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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()); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class TagMappings { private readonly Dictionary 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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] internal Type GetMapping(string tag) { if (!mappings.TryGetValue(tag, out var value)) { return null; } return value; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class YamlAttributeOverrides { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] private readonly struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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()); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class YamlAttributeOverridesInspector : ReflectionTypeInspector { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 Required => baseDescriptor.Required; public bool AllowNulls => baseDescriptor.AllowNulls; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return GetCustomAttribute()?.ConverterType ?? baseDescriptor.ConverterType; } } 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value) { baseDescriptor.Write(target, value); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public T GetCustomAttribute() where T : Attribute { T attribute = overrides.GetAttribute(classType, Name); return attribute ?? 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { IEnumerable enumerable = innerTypeDescriptor.GetProperties(type, container); if (overrides != null) { enumerable = enumerable.Select((Func)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type))); } return enumerable; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class YamlConverterAttribute : Attribute { public Type ConverterType { get; } public YamlConverterAttribute(Type converterType) { ConverterType = converterType; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class YamlFormatter { public static YamlFormatter Default { get; } = new YamlFormatter(); public NumberFormatInfo NumberFormat { get; set; } = 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 virtual Func FormatEnum { get; set; } = delegate(object value, ITypeInspector typeInspector, INamingConvention enumNamingConvention) { string empty = string.Empty; empty = ((value != null) ? typeInspector.GetEnumValue(value) : string.Empty); return enumNamingConvention.Apply(empty); }; public virtual Func PotentiallyQuoteEnums { get; set; } = (object _) => true; public string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public string FormatNumber(double number) { return number.ToString("G", NumberFormat); } public string FormatNumber(float number) { return number.ToString("G", NumberFormat); } public string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public 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 { } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = true)] internal sealed class YamlSerializableAttribute : Attribute { public YamlSerializableAttribute() { } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public YamlSerializableAttribute(Type serializableType) { } } [AttributeUsage(AttributeTargets.Class)] internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class AliasValueDeserializer : IValueDeserializer { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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"); } } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] 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; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object value) { HasValue = true; this.value = value; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] private readonly IValueDeserializer innerDeserializer; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { AliasState aliasState = state.Get(); if (!aliasState.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 aliasState2 = state.Get(); if (!aliasState2.ContainsKey(anchorName)) { aliasState2[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState3 = state.Get(); if (!aliasState3.TryGetValue(anchorName, out var value2)) { aliasState3.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState3[anchorName] = new ValuePromise(obj); } } return obj; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; private readonly ITypeConverter typeConverter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public NodeValueDeserializer(IList deserializers, IList typeResolvers, ITypeConverter typeConverter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); this.typeInspector = typeInspector; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); ObjectDeserializer rootDeserializer = [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] (Type x) => DeserializeValue(parser, x, state, nestedObjectDeserializer); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out var value, rootDeserializer)) { return typeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } } 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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] NodeEvent nodeEvent, Type currentType) { foreach (INodeTypeResolver typeResolver in typeResolvers) { if (typeResolver.Resolve(nodeEvent, ref currentType)) { break; } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ITypeConverter { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector); } internal class NullTypeConverter : ITypeConverter { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return value; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class ObjectAnchorCollection { private readonly Dictionary objectsByAnchor = new Dictionary(); private readonly Dictionary 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, [MaybeNullWhen(false)][<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out string anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type expectedType, ITypeInspector typeInspector) { return ChangeType(value, expectedType, NullNamingConvention.Instance, typeInspector); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return TypeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } internal sealed class SerializerState : IDisposable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] private readonly Dictionary items = new Dictionary(); [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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(); } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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], CultureInfo.InvariantCulture) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal static class TypeConverter { public static T ChangeType<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return (T)ChangeType(value, typeof(T), enumNamingConvention, typeInspector); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type destinationType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture, enumNamingConvention, typeInspector); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type destinationType, IFormatProvider provider, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider), enumNamingConvention, typeInspector); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object ChangeType([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type destinationType, CultureInfo culture, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { 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()) { Type genericTypeDefinition = destinationType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>) || FsharpHelper.IsOptionType(genericTypeDefinition)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture, enumNamingConvention, typeInspector); return Activator.CreateInstance(destinationType, obj); } } if (destinationType.IsEnum()) { object result = value; if (value is string value2) { string name = enumNamingConvention.Reverse(value2); name = typeInspector.GetEnumName(destinationType, name); result = Enum.Parse(destinationType, name, ignoreCase: true); } return result; } 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 }; foreach (Type type2 in array) { foreach (MethodInfo publicStaticMethod2 in type2.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.InnerException; } } } } 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.InnerException; } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture, enumNamingConvention, typeInspector), CultureInfo.InvariantCulture); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] public static void RegisterTypeConverter<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TConvertible, TConverter>() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class TypeConverterCache { private readonly IYamlTypeConverter[] typeConverters; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 0, 2 })] private readonly ConcurrentDictionary cache = new ConcurrentDictionary(); public TypeConverterCache([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] IEnumerable typeConverters) : this(typeConverters?.ToArray() ?? Array.Empty()) { } public TypeConverterCache(IYamlTypeConverter[] typeConverters) { this.typeConverters = typeConverters; } public bool TryGetConverterForType(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)][NotNullWhen(true)] out IYamlTypeConverter typeConverter) { (bool, IYamlTypeConverter) orAdd = DictionaryExtensions.GetOrAdd(cache, type, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Type t, IYamlTypeConverter[] tc) => LookupTypeConverter(t, tc), typeConverters); typeConverter = orAdd.Item2; return orAdd.Item1; } public IYamlTypeConverter GetConverterByType(Type converter) { IYamlTypeConverter[] array = typeConverters; foreach (IYamlTypeConverter yamlTypeConverter in array) { if (yamlTypeConverter.GetType() == converter) { return yamlTypeConverter; } } throw new ArgumentException("IYamlTypeConverter of type " + converter.FullName + " not found", "converter"); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 2 })] private static (bool HasMatch, IYamlTypeConverter TypeConverter) LookupTypeConverter(Type type, IYamlTypeConverter[] typeConverters) { foreach (IYamlTypeConverter yamlTypeConverter in typeConverters) { if (yamlTypeConverter.Accepts(type)) { return (HasMatch: true, TypeConverter: yamlTypeConverter); } } return (HasMatch: false, TypeConverter: null); } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public Type Resolve(Type staticType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal class StaticTypeResolver : ITypeResolver { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public virtual Type Resolve(Type staticType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object actualValue) { if (actualValue != null) { if (actualValue.GetType().IsEnum) { return staticType; } switch (actualValue.GetType().GetTypeCode()) { case TypeCode.Boolean: return typeof(bool); case TypeCode.Char: return typeof(char); case TypeCode.SByte: return typeof(sbyte); case TypeCode.Byte: return typeof(byte); case TypeCode.Int16: return typeof(short); case TypeCode.UInt16: return typeof(ushort); case TypeCode.Int32: return typeof(int); case TypeCode.UInt32: return typeof(uint); case TypeCode.Int64: return typeof(long); case TypeCode.UInt64: return typeof(ulong); case TypeCode.Single: return typeof(float); case TypeCode.Double: return typeof(double); case TypeCode.Decimal: return typeof(decimal); case TypeCode.String: return typeof(string); case TypeCode.DateTime: return typeof(DateTime); } } return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); private readonly ConcurrentDictionary> enumNameCache = new ConcurrentDictionary>(); private readonly ConcurrentDictionary enumValueCache = new ConcurrentDictionary(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override string GetEnumName(Type enumType, string name) { ConcurrentDictionary orAdd = enumNameCache.GetOrAdd(enumType, (Type _) => new ConcurrentDictionary()); return DictionaryExtensions.GetOrAdd(orAdd, name, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (string n, (Type enumType, ITypeInspector innerTypeDescriptor) context) => { var (enumType2, typeInspector) = context; return typeInspector.GetEnumName(enumType2, n); }, (enumType, innerTypeDescriptor)); } public override string GetEnumValue(object enumValue) { return DictionaryExtensions.GetOrAdd(enumValueCache, enumValue, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (object _, (object enumValue, ITypeInspector innerTypeDescriptor) context) => { var (enumValue2, typeInspector) = context; return typeInspector.GetEnumValue(enumValue2); }, (enumValue, innerTypeDescriptor)); } public override IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return DictionaryExtensions.GetOrAdd(cache, type, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (Type t, (object container, ITypeInspector innerTypeDescriptor) context) => { var (container2, typeInspector) = context; return typeInspector.GetProperties(t, container2).ToList(); }, (container, innerTypeDescriptor)); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal 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 string GetEnumName(Type enumType, string name) { foreach (ITypeInspector typeInspector in typeInspectors) { try { return typeInspector.GetEnumName(enumType, name); } catch { } } throw new ArgumentOutOfRangeException("enumType,name", "Name not found on enum type"); } public override string GetEnumValue(object enumValue) { if (enumValue == null) { throw new ArgumentNullException("enumValue"); } foreach (ITypeInspector typeInspector in typeInspectors) { try { return typeInspector.GetEnumValue(enumValue); } catch { } } throw new ArgumentOutOfRangeException("enumValue", $"Value not found for ({enumValue})"); } public override IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return typeInspectors.SelectMany([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (ITypeInspector i) => i.GetProperties(type, container)); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal 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 string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return innerTypeDescriptor.GetProperties(type, container).Select([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (IPropertyDescriptor p) => { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class ReadableFieldsTypeInspector : ReflectionTypeInspector { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] protected class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public bool Required => fieldInfo.IsRequired(); public Type Type => fieldInfo.FieldType; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } public bool AllowNulls => fieldInfo.AcceptsNull(); 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; YamlConverterAttribute customAttribute = fieldInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } ScalarStyle = ScalarStyle.Any; } public void Write(object target, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value) { fieldInfo.SetValue(target, value); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public T GetCustomAttribute() where T : Attribute { object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(T), inherit: true); return (T)customAttributes.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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return type.GetPublicFields().Select((Func)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class ReadablePropertiesTypeInspector : ReflectionTypeInspector { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } public bool AllowNulls => propertyInfo.AcceptsNull(); 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; YamlConverterAttribute customAttribute = propertyInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } } public void Write(object target, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public T GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = propertyInfo.GetAllCustomAttributes(); return (T)allCustomAttributes.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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal abstract class ReflectionTypeInspector : TypeInspectorSkeleton { public override string GetEnumName(Type enumType, string name) { return name; } public override string GetEnumValue(object enumValue) { if (enumValue == null) { return string.Empty; } return enumValue.ToString(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal abstract class TypeInspectorSkeleton : ITypeInspector { public abstract string GetEnumName(Type enumType, string name); public abstract string GetEnumValue(object enumValue); public abstract IEnumerable GetProperties(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container); public IPropertyDescriptor GetProperty(Type type, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching) { IEnumerable enumerable = ((!caseInsensitivePropertyMatching) ? (from p in GetProperties(type, container) where p.Name == name select p) : (from p in GetProperties(type, container) where p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) 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([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class WritablePropertiesTypeInspector : ReflectionTypeInspector { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type TypeOverride { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type ConverterType { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } public bool AllowNulls => propertyInfo.AcceptsNull(); 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; YamlConverterAttribute customAttribute = propertyInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } } public void Write(object target, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public T GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = propertyInfo.GetAllCustomAttributes(); return (T)allCustomAttributes.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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] private class AnchorAssignment { public AnchorName Anchor; } private readonly Dictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value, ObjectSerializer serializer) { 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, ObjectSerializer serializer) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, ObjectSerializer serializer) { return true; } protected override void VisitScalar(IObjectDescriptor scalar, ObjectSerializer serializer) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, ObjectSerializer serializer) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping, ObjectSerializer serializer) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, ObjectSerializer serializer) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence, ObjectSerializer serializer) { } 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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 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(propertyDescriptor, value, context, serializer); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.Enter(propertyDescriptor, value, context, serializer); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitScalar(scalar, context, serializer); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context, serializer); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingEnd(mapping, context, serializer); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceStart(sequence, elementType, context, serializer); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceEnd(sequence, context, serializer); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 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, serializer); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly TypeConverterCache typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { this.typeConverters = new TypeConverterCache(typeConverters); this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (propertyDescriptor?.ConverterType != null) { IYamlTypeConverter converterByType = typeConverters.GetConverterByType(propertyDescriptor.ConverterType); converterByType.WriteYaml(context, value.Value, value.Type, serializer); return false; } if (typeConverters.TryGetConverterForType(value.Type, out var typeConverter)) { typeConverter.WriteYaml(context, value.Value, value.Type, serializer); 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(propertyDescriptor, value, context, serializer); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, ObjectSerializer serializer) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context, serializer); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 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, serializer); } return false; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private object GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { 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, serializer); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; private readonly TypeConverterCache typeConverterCache; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { typeConverterCache = new TypeConverterCache((IYamlTypeConverter[])(this.typeConverters = typeConverters?.ToArray() ?? Array.Empty())); } bool IObjectGraphVisitor.Enter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { if (typeConverterCache.TryGetConverterForType(value.Type, out var _)) { return false; } if (value.Value is IYamlConvertible) { return false; } if (value.Value is IYamlSerializable) { return false; } return Enter(value, serializer); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context, ObjectSerializer serializer) { VisitMappingEnd(mapping, serializer); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context, ObjectSerializer serializer) { VisitMappingStart(mapping, keyType, valueType, serializer); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context, ObjectSerializer serializer) { VisitScalar(scalar, serializer); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context, ObjectSerializer serializer) { VisitSequenceEnd(sequence, serializer); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context, ObjectSerializer serializer) { VisitSequenceStart(sequence, elementType, serializer); } protected abstract bool Enter(IObjectDescriptor value, ObjectSerializer serializer); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, ObjectSerializer serializer); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, ObjectSerializer serializer); protected abstract void VisitMappingEnd(IObjectDescriptor mapping, ObjectSerializer serializer); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, ObjectSerializer serializer); protected abstract void VisitScalar(IObjectDescriptor scalar, ObjectSerializer serializer); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence, ObjectSerializer serializer); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, ObjectSerializer serializer); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] protected readonly 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer) { Traverse(null, "", graph, visitor, context, new Stack(maxRecursion), serializer); } protected virtual void Traverse<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { 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(propertyDescriptor, value, context, serializer)) { 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, serializer); 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, serializer); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context, serializer); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); Type type = underlyingType ?? FsharpHelper.GetOptionUnderlyingType(value.Type); object obj = ((type != null) ? FsharpHelper.GetValue(value) : null); if (underlyingType != null) { Traverse(propertyDescriptor, "Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path, serializer); } else if (type != null && obj != null) { Traverse(propertyDescriptor, "Value", new ObjectDescriptor(FsharpHelper.GetValue(value), type, value.Type, value.ScalarStyle), visitor, context, path, serializer); } else { TraverseObject(propertyDescriptor, value, visitor, context, path, serializer); } } finally { path.Pop(); } } protected virtual void TraverseObject<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(propertyDescriptor, value, visitor, typeof(object), typeof(object), context, path, serializer); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(propertyDescriptor, new ObjectDescriptor(dictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path, serializer); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(propertyDescriptor, value, visitor, context, path, serializer); } else { TraverseProperties(value, visitor, context, path, serializer); } } protected virtual void TraverseDictionary<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path, ObjectSerializer serializer) { visitor.VisitMappingStart(dictionary, keyType, valueType, context, serializer); 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); ObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); ObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context, serializer)) { Traverse(propertyDescriptor, obj, objectDescriptor, visitor, context, path, serializer); Traverse(propertyDescriptor, obj, objectDescriptor2, visitor, context, path, serializer); } } visitor.VisitMappingEnd(dictionary, context, serializer); } private void TraverseList<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>(IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context, serializer); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(propertyDescriptor, num, GetObjectDescriptor(item, valueType), visitor, context, path, serializer); num++; } visitor.VisitSequenceEnd(value, context, serializer); } protected virtual void TraverseProperties<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (context.GetType() != typeof(Nothing)) { objectFactory.ExecuteOnSerializing(value.Value); } visitor.VisitMappingStart(value, typeof(string), typeof(object), context, serializer); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context, serializer)) { Traverse(null, property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string), ScalarStyle.Plain), visitor, context, path, serializer); Traverse(property, property.Name, value2, visitor, context, path, serializer); } } visitor.VisitMappingEnd(value, context, serializer); if (context.GetType() != typeof(Nothing)) { objectFactory.ExecuteOnSerialized(value.Value); } } private ObjectDescriptor GetObjectDescriptor([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly TypeConverterCache 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 = new TypeConverterCache(converters); this.settings = settings; } protected override void TraverseProperties<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (!value.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.TryGetConverterForType(value.Type, out var _)) { 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, serializer); } } } namespace YamlDotNet.Serialization.ObjectFactories { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class DefaultObjectFactory : ObjectFactoryBase { private readonly Dictionary> stateMethods = new Dictionary> { { typeof(YamlDotNet.Serialization.Callbacks.OnDeserializedAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnDeserializingAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnSerializedAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnSerializingAttribute), new ConcurrentDictionary() } }; 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) { string message = "Failed to create an instance of type '" + type.FullName + "'."; throw new InvalidOperationException(message, innerException); } } public override void ExecuteOnDeserialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializedAttribute), value); } public override void ExecuteOnDeserializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializingAttribute), value); } public override void ExecuteOnSerialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializedAttribute), value); } public override void ExecuteOnSerializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializingAttribute), value); } private void ExecuteState(Type attributeType, object value) { if (value != null) { Type type = value.GetType(); MethodInfo[] array = GetStateMethods(attributeType, type); MethodInfo[] array2 = array; foreach (MethodInfo methodInfo in array2) { methodInfo.Invoke(value, null); } } } private MethodInfo[] GetStateMethods(Type attributeType, Type valueType) { ConcurrentDictionary concurrentDictionary = stateMethods[attributeType]; return concurrentDictionary.GetOrAdd(valueType, delegate(Type type) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return methods.Where([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (MethodInfo x) => x.GetCustomAttributes(attributeType, inherit: true).Length != 0).ToArray(); }); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public virtual object CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual void ExecuteOnDeserialized(object value) { } public virtual void ExecuteOnDeserializing(object value) { } public virtual void ExecuteOnSerialized(object value) { } public virtual void ExecuteOnSerializing(object value) { } public virtual bool GetDictionary(IObjectDescriptor descriptor, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out IDictionary dictionary, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { Type implementationOfOpenGenericInterface = descriptor.Type.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); if (implementationOfOpenGenericInterface != null) { genericArguments = implementationOfOpenGenericInterface.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 implementationOfOpenGenericInterface = type.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); return (implementationOfOpenGenericInterface != null) ? implementationOfOpenGenericInterface.GetGenericArguments()[0] : typeof(object); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out IDictionary dictionary, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { dictionary = null; genericArguments = null; return false; } public abstract void ExecuteOnDeserializing(object value); public abstract void ExecuteOnDeserialized(object value); public abstract void ExecuteOnSerializing(object value); public abstract void ExecuteOnSerialized(object value); } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] bool INodeTypeResolver.Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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}'."); } } this.mappings = mappings; } public bool Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { if (mappings.TryGetValue(currentType, out var value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] bool INodeTypeResolver.Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] bool INodeTypeResolver.Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public bool Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public bool Resolve([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] NodeEvent nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class ArrayNodeDeserializer : INodeDeserializer { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] public object SyncRoot { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public ArrayNodeDeserializer(INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!expectedType.IsArray) { value = false; return false; } Type itemType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); Array array = null; CollectionNodeDeserializer.DeserializeHelper(itemType, parser, nestedObjectDeserializer, arrayList, canUpdate: true, enumNamingConvention, typeInspector, PromiseResolvedHandler); array = Array.CreateInstance(itemType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] void PromiseResolvedHandler(int index, object value2) { if (array == null) { throw new InvalidOperationException("Destination array is still null"); } array.SetValue(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(value2, itemType, enumNamingConvention, typeInspector), index); } } } internal abstract class CollectionDeserializer { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] protected static void DeserializeHelper(Type tItem, IParser parser, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public CollectionNodeDeserializer(IObjectFactory objectFactory, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { bool canUpdate = true; Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(ICollection<>)); Type type; IList list; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); type = genericArguments[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { Type implementationOfOpenGenericInterface2 = expectedType.GetImplementationOfOpenGenericInterface(typeof(IList<>)); canUpdate = implementationOfOpenGenericInterface2 != 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, enumNamingConvention, typeInspector); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, bool canUpdate, INamingConvention enumNamingConvention, ITypeInspector typeInspector, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] Action promiseResolvedHandler = null) { 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); if (promiseResolvedHandler != null) { valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { promiseResolvedHandler(index, v); }; } else { valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { result[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem, enumNamingConvention, typeInspector); }; } } else { result.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem, enumNamingConvention, typeInspector)); } } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IDictionary result, ObjectDeserializer rootDeserializer) { 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 += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { result[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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.", "tKey"); } if (valuePromise == null) { TryAssign(result, key, value, property); continue; } valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { result[key] = v; }; } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.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, rootDeserializer); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); if (implementationOfOpenGenericInterface != expectedType) { value = null; return false; } type = implementationOfOpenGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class FsharpListNodeDeserializer : INodeDeserializer { private readonly ITypeInspector typeInspector; private readonly INamingConvention enumNamingConvention; public FsharpListNodeDeserializer(ITypeInspector typeInspector, INamingConvention enumNamingConvention) { this.typeInspector = typeInspector; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!FsharpHelper.IsFsharpListType(expectedType)) { value = false; return false; } Type type = expectedType.GetGenericArguments()[0]; Type t = expectedType.GetGenericTypeDefinition().MakeGenericType(type); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(type, parser, nestedObjectDeserializer, arrayList, canUpdate: true, enumNamingConvention, typeInspector); Array array = Array.CreateInstance(type, arrayList.Count); arrayList.CopyTo(array, 0); object obj = FsharpHelper.CreateFsharpListFromArray(t, type, array); value = obj; return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] private static 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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly ITypeInspector typeInspector; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; private readonly INamingConvention enumNamingConvention; private readonly bool enforceNullability; private readonly bool caseInsensitivePropertyMatching; private readonly bool enforceRequiredProperties; private readonly TypeConverterCache typeConverters; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeInspector, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter, INamingConvention enumNamingConvention, bool enforceNullability, bool caseInsensitivePropertyMatching, bool enforceRequiredProperties, IEnumerable typeConverters) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeInspector = typeInspector ?? throw new ArgumentNullException("typeInspector"); this.ignoreUnmatched = ignoreUnmatched; this.duplicateKeyChecking = duplicateKeyChecking; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); this.enforceNullability = enforceNullability; this.caseInsensitivePropertyMatching = caseInsensitivePropertyMatching; this.enforceRequiredProperties = enforceRequiredProperties; this.typeConverters = new TypeConverterCache(typeConverters); } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? FsharpHelper.GetOptionUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); objectFactory.ExecuteOnDeserializing(value); HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); Mark start = Mark.Empty; MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar propertyName = parser.Consume(); if (duplicateKeyChecking && !hashSet.Add(propertyName.Value)) { throw new YamlException(propertyName.Start, propertyName.End, "Encountered duplicate key " + propertyName.Value); } try { IPropertyDescriptor property = typeInspector.GetProperty(type, null, propertyName.Value, ignoreUnmatched, caseInsensitivePropertyMatching); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } hashSet2.Add(property.Name); object obj; if (property.ConverterType != null) { IYamlTypeConverter converterByType = typeConverters.GetConverterByType(property.ConverterType); obj = converterByType.ReadYaml(parser, property.Type, rootDeserializer); } else { obj = nestedObjectDeserializer(parser, property.Type); } if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { object value3 = typeConverter.ChangeType(v, property.Type, enumNamingConvention, typeInspector); NullCheck(value3, property, propertyName); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type, enumNamingConvention, typeInspector); NullCheck(value2, property, propertyName); property.Write(value, value2); } } catch (SerializationException ex) { throw new YamlException(propertyName.Start, propertyName.End, ex.Message); } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(propertyName.Start, propertyName.End, "Exception during deserialization", innerException); } start = propertyName.End; } if (enforceRequiredProperties) { IEnumerable properties = typeInspector.GetProperties(type, value); List list = new List(); foreach (IPropertyDescriptor item in properties) { if (item.Required && !hashSet2.Contains(item.Name)) { list.Add(item.Name); } } if (list.Count > 0) { string text = string.Join(",", list); throw new YamlException(in start, in start, "Missing properties, '" + text + "' in source yaml."); } } objectFactory.ExecuteOnDeserialized(value); return true; } public void NullCheck(object value, IPropertyDescriptor property, YamlDotNet.Core.Events.Scalar propertyName) { if (enforceNullability && value == null && !property.AllowNulls) { throw new YamlException(propertyName.Start, propertyName.End, "Strict nullability enforcement error.", new NullReferenceException("Yaml value is null when target property requires non null values.")); } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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; private readonly ITypeInspector typeInspector; private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter, ITypeInspector typeInspector, YamlFormatter formatter, INamingConvention enumNamingConvention) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.typeInspector = typeInspector; this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? FsharpHelper.GetOptionUnderlyingType(expectedType) ?? expectedType; if (type.IsEnum()) { string name = enumNamingConvention.Reverse(@event.Value); name = typeInspector.GetEnumName(type, name); value = Enum.Parse(type, name, 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, formatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, formatter.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, enumNamingConvention, typeInspector); } break; } return true; } private static bool DeserializeBooleanHelper(string value) { if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { return true; } if (Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { return false; } throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } private 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, formatter.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("_", ""), CultureInfo.InvariantCulture); } } 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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private 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 "null": case "Null": case "NULL": case "~": case "": return null; case "true": case "True": case "TRUE": return true; case "False": case "FALSE": case "false": return false; default: if (Regex.IsMatch(v, "^0x[0-9a-fA-F]+$")) { v = v.Substring(2); if (byte.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result)) { return result; } if (short.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result2)) { return result2; } if (int.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result3)) { return result3; } if (long.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result4)) { return result4; } if (ulong.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result5)) { return result5; } return v; } if (Regex.IsMatch(v, "^0o[0-9a-fA-F]+$")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out var 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; } return value2; } if (Regex.IsMatch(v, "^[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$")) { if (byte.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result6)) { return result6; } if (short.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result7)) { return result7; } if (int.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result8)) { return result8; } if (long.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result9)) { return result9; } if (ulong.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result10)) { return result10; } if (float.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result11)) { return result11; } if (double.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result12)) { return result12; } return v; } if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (Polyfills.StartsWith(v, '-')) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } } private static bool TryAndSwallow(Func attempt, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value) { try { value = attempt(); return true; } catch { value = null; return false; } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] public object SyncRoot { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { 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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, IList result, IObjectFactory factory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser reader, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { 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, rootDeserializer); return true; } value = null; return false; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly TypeConverterCache converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = new TypeConverterCache(converters); } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!converters.TryGetConverterForType(expectedType, out var typeConverter)) { value = null; return false; } value = typeConverter.ReadYaml(parser, expectedType, rootDeserializer); return true; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser, expectedType, [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] (Type type) => nestedObjectDeserializer(parser, type)); value = yamlConvertible; return true; } value = null; return false; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { 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 { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class CamelCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase(); } public string Reverse(string value) { return value.ToPascalCase(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class HyphenatedNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("-"); } public string Reverse(string value) { return value.ToPascalCase(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class LowerCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase().ToLower(CultureInfo.InvariantCulture); } public string Reverse(string value) { if (string.IsNullOrEmpty(value)) { return value; } return char.ToUpperInvariant(value[0]) + value.Substring(1); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class NullNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } public string Apply(string value) { return value; } public string Reverse(string value) { return value; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class PascalCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } public string Apply(string value) { return value.ToPascalCase(); } public string Reverse(string value) { return value.ToPascalCase(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class UnderscoredNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("_"); } public string Reverse(string value) { return value.ToPascalCase(); } } } namespace YamlDotNet.Serialization.EventEmitters { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class JsonEventEmitter : ChainedEventEmitter { private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public JsonEventEmitter(IEventEmitter nextEmitter, YamlFormatter formatter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) : base(nextEmitter) { this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } 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 = formatter.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 = formatter.FormatEnum(value, typeInspector, enumNamingConvention); eventInfo.Style = ((!formatter.PotentiallyQuoteEnums(value)) ? ScalarStyle.Plain : ScalarStyle.DoubleQuoted); } else { eventInfo.RenderedValue = formatter.FormatNumber(value); } break; case TypeCode.Single: { float f = (float)value; eventInfo.RenderedValue = f.ToString("G", CultureInfo.InvariantCulture); if (float.IsNaN(f) || float.IsInfinity(f)) { eventInfo.Style = ScalarStyle.DoubleQuoted; } break; } case TypeCode.Double: { double d = (double)value; eventInfo.RenderedValue = d.ToString("G", CultureInfo.InvariantCulture); if (double.IsNaN(d) || double.IsInfinity(d)) { eventInfo.Style = ScalarStyle.DoubleQuoted; } break; } case TypeCode.Decimal: eventInfo.RenderedValue = ((decimal)value).ToString(CultureInfo.InvariantCulture); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = formatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = formatter.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); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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|\\s.*)$"; 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))$"; private readonly ScalarStyle defaultScalarStyle; private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, IDictionary tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings, ScalarStyle defaultScalarStyle, YamlFormatter formatter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) : base(nextEmitter) { this.defaultScalarStyle = defaultScalarStyle; this.formatter = formatter; this.tagMappings = tagMappings; this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(quoteYaml1_1Strings ? CombinedYaml1_1SpecialStrings_Pattern : SpecialStrings_Pattern, RegexOptions.Compiled); this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } 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 = formatter.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 = formatter.FormatEnum(value, typeInspector, enumNamingConvention); style = ((!quoteNecessaryStrings || !IsSpecialStringValue(eventInfo.RenderedValue) || !formatter.PotentiallyQuoteEnums(value)) ? defaultScalarStyle : ScalarStyle.DoubleQuoted); } else { eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = formatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((!quoteNecessaryStrings || !IsSpecialStringValue(eventInfo.RenderedValue)) ? defaultScalarStyle : ScalarStyle.DoubleQuoted); break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = formatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = formatter.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; } } private bool IsSpecialStringValue(string value) { if (value.Trim() == string.Empty) { return true; } return isSpecialStringValue_Regex?.IsMatch(value) ?? false; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class DateTime8601Converter : IYamlTypeConverter { private readonly ScalarStyle scalarStyle; public DateTime8601Converter() : this(ScalarStyle.Any) { } public DateTime8601Converter(ScalarStyle scalarStyle) { this.scalarStyle = scalarStyle; } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTime dateTime = DateTime.ParseExact(value, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); return dateTime; } public void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer) { string value2 = ((DateTime)value).ToString("O", CultureInfo.InvariantCulture); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, scalarStyle, isPlainImplicit: true, isQuotedImplicit: false)); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTimeStyles style = ((kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal); DateTime dt = DateTime.ParseExact(value, formats, provider, style); dt = EnsureDateTimeKind(dt, kind); return dt; } public void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer) { 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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class DateTimeOffsetConverter : IYamlTypeConverter { private readonly IFormatProvider provider; private readonly ScalarStyle style; private readonly DateTimeStyles dateStyle; private readonly string[] formats; public DateTimeOffsetConverter([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] IFormatProvider provider = null, ScalarStyle style = ScalarStyle.Any, DateTimeStyles dateStyle = DateTimeStyles.None, params string[] formats) { this.provider = provider ?? CultureInfo.InvariantCulture; this.style = style; this.dateStyle = dateStyle; this.formats = formats.DefaultIfEmpty("O").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTimeOffset); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTimeOffset dateTimeOffset = DateTimeOffset.ParseExact(value, formats, provider, dateStyle); return dateTimeOffset; } public void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer) { string value2 = ((DateTimeOffset)value).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, style, isPlainImplicit: true, isQuotedImplicit: false)); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; return new Guid(value); } public void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer) { 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)); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; return Type.GetType(value, throwOnError: true); } public void WriteYaml(IEmitter emitter, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object value, Type type, ObjectSerializer serializer) { 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.Callbacks { [AttributeUsage(AttributeTargets.Method)] internal sealed class OnDeserializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnDeserializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnSerializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnSerializingAttribute : Attribute { } } namespace YamlDotNet.Serialization.BufferedDeserialization { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : IParser { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] private readonly LinkedList buffer; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] private LinkedListNode current; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public ParsingEvent Current { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return current?.Value; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 1, 1, 2 })] Func nestedObjectDeserializer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!reader.Accept(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where([<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, rootDeserializer)) { return true; } } value = null; return false; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(IParser buffer, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out Type suggestedType); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class DocumentLoadingState { private readonly Dictionary anchors = new Dictionary(); private readonly List nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } anchors[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"); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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 static 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(">"); } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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."); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class YamlDocument { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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() { AnchorAssigningVisitor anchorAssigningVisitor = new AnchorAssigningVisitor(); 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); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); if (!children.TryAdd(yamlNode, yamlNode2)) { throw new YamlException(yamlNode.Start, yamlNode.End, $"Duplicate key {yamlNode}"); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 0, 1, 1 })] params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 = (child.Value.Anchor.IsEmpty ? YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value) : YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value.Anchor)); } 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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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) { string text = Convert.ToString(value, CultureInfo.InvariantCulture); yamlNode = text ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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)([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (string i) => i))); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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}")] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { private bool forceImplicitPlain; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private string value; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public string Value { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return value; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set { if (value == null) { forceImplicitPlain = true; } else { forceImplicitPlain = false; } this.value = value; } } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); string text = scalar.Value; if (scalar.Style == ScalarStyle.Plain && base.Tag.IsEmpty) { forceImplicitPlain = text.Length switch { 0 => true, 1 => text == "~", 4 => text == "null" || text == "Null" || text == "NULL", _ => false, }; } value = text; Style = scalar.Style; } public YamlScalarNode() { } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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) { TagName tag = base.Tag; bool isPlainImplicit = tag.IsEmpty; if (forceImplicitPlain && Style == ScalarStyle.Plain && (Value == null || Value == "")) { tag = JsonSchema.Tags.Null; isPlainImplicit = true; } else if (tag.IsEmpty && Value == null && (Style == ScalarStyle.Plain || Style == ScalarStyle.Any)) { tag = JsonSchema.Tags.Null; isPlainImplicit = true; } emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, tag, Value ?? string.Empty, Style, isPlainImplicit, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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()); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [DebuggerDisplay("Count = {children.Count}")] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class YamlSequenceNode : YamlNode, IEnumerable, IEnumerable, IYamlConvertible { private readonly List 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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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()); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class YamlStream : IEnumerable, IEnumerable { private readonly List 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(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class DefaultFsharpHelper : IFsharpHelper { private static bool IsFsharpCore(Type t) { return t.Namespace == "Microsoft.FSharp.Core"; } public bool IsOptionType(Type t) { if (IsFsharpCore(t)) { return t.Name == "FSharpOption`1"; } return false; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type GetOptionUnderlyingType(Type t) { if (!t.IsGenericType || !IsOptionType(t)) { return null; } return t.GenericTypeArguments[0]; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object GetValue(IObjectDescriptor objectDescriptor) { if (!IsOptionType(objectDescriptor.Type)) { throw new InvalidOperationException("Should not be called on non-Option<> type"); } if (objectDescriptor.Value == null) { return null; } return objectDescriptor.Type.GetProperty("Value").GetValue(objectDescriptor.Value); } public bool IsFsharpListType(Type t) { if (t.Namespace == "Microsoft.FSharp.Collections") { return t.Name == "FSharpList`1"; } return false; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { if (!IsFsharpListType(t)) { return null; } return t.Assembly.GetType("Microsoft.FSharp.Collections.ListModule").GetMethod("OfArray").MakeGenericMethod(itemsType) .Invoke(null, new object[1] { arr }); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class DictionaryExtensions { public static bool TryAdd<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] V>(this Dictionary dictionary, T key, V value) { if (dictionary.ContainsKey(key)) { return false; } dictionary.Add(key, value); return true; } public static TValue GetOrAdd<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TKey, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TValue, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] TArg>(this ConcurrentDictionary dictionary, TKey key, Func valueFactory, TArg arg) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } if (key == null) { throw new ArgumentNullException("key"); } if (valueFactory == null) { throw new ArgumentNullException("valueFactory"); } TValue value; do { if (dictionary.TryGetValue(key, out value)) { return value; } value = valueFactory(key, arg); } while (!dictionary.TryAdd(key, value)); return value; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class FsharpHelper { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static IFsharpHelper Instance { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] set; } public static bool IsOptionType(Type t) { return Instance?.IsOptionType(t) ?? false; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static Type GetOptionUnderlyingType(Type t) { return Instance?.GetOptionUnderlyingType(t); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object GetValue(IObjectDescriptor objectDescriptor) { return Instance?.GetValue(objectDescriptor); } public static bool IsFsharpListType(Type t) { return Instance?.IsFsharpListType(t) ?? false; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public static object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return Instance?.CreateFsharpListFromArray(t, itemsType, arr); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(1)] public object SyncRoot { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] get { throw new NotSupportedException(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public void CopyTo(Array array, int index) { throw new NotSupportedException(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class GenericDictionaryToNonGenericAdapterNullable(2)] TValue> : IDictionary, ICollection, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 0, 1, 1 })] private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object Value { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get { return enumerator.Current.Value; } } public object Current => Entry; public DictionaryEnumerator([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object this[object key] { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] get { throw new NotSupportedException(); } [param: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IFsharpHelper { bool IsOptionType(Type t); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] Type GetOptionUnderlyingType(Type t); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object GetValue(IObjectDescriptor objectDescriptor); bool IsFsharpListType(Type t); [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] object CreateFsharpListFromArray(Type t, Type itemsType, Array arr); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IOrderedDictionaryNullable(2)] TValue> : IDictionary, ICollection>, IEnumerable>, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair this[int index] { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] get; [param: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class NullFsharpHelper : IFsharpHelper { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return null; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Type GetOptionUnderlyingType(Type t) { return null; } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public object GetValue(IObjectDescriptor objectDescriptor) { return null; } public bool IsFsharpListType(Type t) { return false; } public bool IsOptionType(Type t) { return false; } } internal static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class OrderedDictionaryNullable(2)] TValue> : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 orderedDictionary.dictionary.ContainsKey(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([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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.ContainsValue(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([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] public KeyValuePair this[int index] { [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] get { return list[index]; } [param: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { if (!TryAdd(item)) { ThrowDuplicateKeyException(item.Key); } } public void Add(TKey key, TValue value) { if (!TryAdd(key, value)) { ThrowDuplicateKeyException(key); } } private static void ThrowDuplicateKeyException(TKey key) { throw new ArgumentException($"An item with the same key {key} has already been added."); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { if (DictionaryExtensions.TryAdd(dictionary, key, value)) { list.Add(new KeyValuePair(key, value)); return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { if (DictionaryExtensions.TryAdd(dictionary, item.Key, item.Value)) { list.Add(item); return true; } return false; } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 1, 0, 1, 1 })] KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); } [System.Runtime.Serialization.OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { dictionary = new Dictionary(); foreach (KeyValuePair item in list) { dictionary[item.Key] = item.Value; } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] T>(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionaryNullable(2)] TValue>(this Dictionary dictionary) { return dictionary; } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } } namespace YamlDotNet.Core { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal readonly struct AnchorName : IEquatable { public static readonly AnchorName Empty; private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] public static implicit operator AnchorName(string value) { if (value != null) { return new AnchorName(value); } return Empty; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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) { } } [DebuggerStepThrough] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal readonly struct CharacterAnalyzer<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] TBuffer> where TBuffer : ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } Buffer = 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 c = Buffer.Peek(offset); return Polyfills.Contains(expectedCharacters, c); } } internal static class Constants { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 long Index { get; private set; } public long Line { get; private set; } public long LineOffset { get; private set; } public Cursor() { Line = 1L; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 = 0L; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0L) { Line++; LineOffset = 0L; } } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class Emitter : IEmitter { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] private class AnchorData { public AnchorName Anchor; public bool IsAlias; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private class TagData { public string Handle; public string Suffix; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] private class ScalarData { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 bool useUtf16SurrogatePair; 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; useUtf16SurrogatePair = settings.UseUtf16SurrogatePairs; this.output = output; this.output.NewLine = settings.NewLine; 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; foreach (ParsingEvent @event in events) { switch (@event.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; } StringLookAheadBufferPool.BufferWrapper bufferWrapper = StringLookAheadBufferPool.Rent(value); try { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(bufferWrapper.Buffer); 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; } finally { ((IDisposable)bufferWrapper/*cast due to .constrained prefix*/).Dispose(); } } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); string text = output.Encoding.GetString(bytes, 0, bytes.Length); return text.Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private static 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; foreach (TagDirective value in defaultTagDirectives) { AppendTagDirectiveTo(value, allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; TagDirective[] defaultTagDirectives2 = Constants.DefaultTagDirectives; foreach (TagDirective value2 in defaultTagDirectives2) { AppendTagDirectiveTo(value2, 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 static TagDirectiveCollection NonDefaultTagsAmong([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 static 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; } if (scalarStyle == ScalarStyle.ForcePlain) { scalarStyle = ScalarStyle.Plain; } 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."); } if (useUtf16SurrogatePair) { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); Write('\\'); Write('u'); Write(((ushort)value[i + 1]).ToString("X04", CultureInfo.InvariantCulture)); } else { 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); WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } 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) { 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 static int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private static int SafeStringLength(string value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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) { StringLookAheadBufferPool.BufferWrapper bufferWrapper = StringLookAheadBufferPool.Rent(value); try { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(bufferWrapper.Buffer); 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); } } finally { ((IDisposable)bufferWrapper/*cast due to .constrained prefix*/).Dispose(); } } 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, [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] ([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(CultureInfo.InvariantCulture, "%{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.WriteLine(); } else { output.Write(breakCharacter); } column = 0; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 bool UseUtf16SurrogatePairs { get; } public EmitterSettings() { } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = false, string newLine = null, bool useUtf16SurrogatePairs = false) { 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; UseUtf16SurrogatePairs = useUtf16SurrogatePairs; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithNewLine(string newLine) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine, UseUtf16SurrogatePairs); } 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, UseUtf16SurrogatePairs); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithUtf16SurrogatePairs() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, useUtf16SurrogatePairs: true); } } internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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) { } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class InsertionQueue<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] internal interface IParser { ParsingEvent Current { get; } bool MoveNext(); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] internal interface IScanner { Mark CurrentPosition { get; } Token Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [DebuggerStepThrough] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(0L, 1L, 1L); public long Index { get; } public long Line { get; } public long Column { get; } public Mark(long index, long line, long 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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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())); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } public static bool operator ==(Mark left, Mark right) { return left.Equals(right); } public static bool operator !=(Mark left, Mark right) { return !(left == right); } public static bool operator <(Mark left, Mark right) { return left.CompareTo(right) < 0; } public static bool operator <=(Mark left, Mark right) { return left.CompareTo(right) <= 0; } public static bool operator >(Mark left, Mark right) { return left.CompareTo(right) > 0; } public static bool operator >=(Mark left, Mark right) { return left.CompareTo(right) >= 0; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal sealed class MergingParser : IParser { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 bool IsDeleted(LinkedListNode node) { return deleted.Contains(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 static IEnumerable> Enumerate([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] private sealed class ParsingEventCloner : IParsingEventVisitor { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public ParsingEvent Current { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 static 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) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable GetMappingEvents(AnchorName anchor) { ParsingEventCloner parsingEventCloner = new ParsingEventCloner(); int nesting = 0; return (from e in events.FromAnchor(anchor) where !events.IsDeleted(e) select e.Value).TakeWhile([<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(0)] (ParsingEvent e) => (nesting += e.NestingIncrease) >= 0).Select(parsingEventCloner.Clone); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class Parser : IParser { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private Token currentToken; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private VersionDirective version; private readonly EventQueue pendingEvents = new EventQueue(); [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public ParsingEvent Current { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private set; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 YamlDotNet.Core.Events.StreamStart 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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 YamlDotNet.Core.Events.Scalar 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(); ParsingEvent 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(); ParsingEvent 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.Current is FlowMappingEnd) && 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 YamlDotNet.Core.Events.DocumentEnd 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(); ParsingEvent 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(); ParsingEvent 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(); ParsingEvent result; 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; 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(); result = new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); Skip(); return result; } 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 MappingEnd 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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal static class ParserExtensions { public static T Consume<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] T>(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] T>(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [return: MaybeNull] public static T Allow<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [return: MaybeNull] public static T Peek<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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<[<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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, [MaybeNullWhen(false)][<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] out YamlDotNet.Core.Events.Scalar key, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 flag = selector(scalar); parser.MoveNext(); if (flag) { 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, ForcePlain } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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(); [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1 })] private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private bool flowCollectionFetched; private bool startFlowCollectionFetched; private long indent = -1L; private bool flowScalarFetched; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private Token previous; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private Anchor previousAnchor; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private YamlDotNet.Core.Tokens.Scalar lastScalar; private readonly int maxKeySize; private static readonly byte[] EmptyBytes = Array.Empty(); public bool SkipComments { get; private set; } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] [field: <198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] public Token Current { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] get; [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] private set; } public Mark CurrentPosition => cursor.Mark(); private bool IsDocumentStart() { if (!analyzer.EndOfInput && cursor.LineOffset == 0L && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0L && 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) : this(input, skipComments, 1024) { } public Scanner(TextReader input, bool skipComments, int maxKeySize) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; this.maxKeySize = maxKeySize; } 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 + maxKeySize < 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 == 0L && 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('\'')) { FetchQuotedScalar(isSingleQuoted: true); } else if (analyzer.Check('"')) { FetchQuotedScalar(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(long 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(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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(-1L); 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 item = ((!isSequenceToken) ? ((Token)new FlowMappingStart(in start, in start)) : ((Token)new FlowSequenceStart(in start, in start))); tokens.Enqueue(item); 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 == 0L && simpleKey.LineOffset == 0L) { 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(long 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 Tag 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 YamlDotNet.Core.Tokens.Scalar 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; long currentIndent = 0L; 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((object?)builder2); builder2.Length = 0; } builder.Append((object?)builder3); 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 long ScanBlockScalarBreaks(long currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { long num = 0L; long num2 = -1L; end = cursor.Mark(); while (true) { if ((currentIndent == 0L || 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) { long 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 == 0L && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1L)); } return currentIndent; } private void FetchQuotedScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; flowScalarFetched = flowLevel > 0; YamlDotNet.Core.Tokens.Scalar item = ScanFlowScalar(isSingleQuoted); tokens.Enqueue(item); lastScalar = item; 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 YamlDotNet.Core.Tokens.Scalar 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) { for (int j = 0; j < num; j++) { Skip(); } if (analyzer.Peek(0) != '\\' || (analyzer.Peek(1) != 'u' && analyzer.Peek(1) != 'U')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode surrogates."); } Skip(); num = ((analyzer.Peek(0) != 'u') ? 8 : 4); Skip(); int num3 = 0; for (int k = 0; k < num; k++) { if (!analyzer.IsHex(0)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, did not find expected hexadecimal number."); } num3 = (num3 << 4) + analyzer.AsHex(k); } for (int l = 0; l < num; l++) { Skip(); } num2 = char.ConvertToUtf32((char)num2, (char)num3); } else { if (num2 > 1114111) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode character escape code."); } for (int m = 0; m < num; m++) { Skip(); } } builder.Append(char.ConvertFromUtf32(num2)); } 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((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; } else { builder.Append((object?)builder2); 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; long 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 InvalidOperationException(); } 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 VersionDirective 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 TagDirective 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([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 (Polyfills.EndsWith(text, ',')) { 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); } } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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) { } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class SimpleKey { private readonly Cursor cursor; public bool IsPossible { get; private set; } public bool IsRequired { get; } public int TokenNumber { get; } public long Index => cursor.Index; public long Line => cursor.Line; public long 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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal sealed class StringLookAheadBuffer : ILookAheadBuffer, IResettable { public string Value { get; set; } = string.Empty; public int Position { get; private set; } public int Length => Value.Length; public bool EndOfInput => IsOutside(Position); 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; } public bool TryReset() { Position = 0; Value = string.Empty; return true; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1, 1 })] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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)); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal readonly struct TagName : IEquatable { public static readonly TagName Empty; [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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()); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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) { } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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"); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] 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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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) { } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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.ObjectPool { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 0, 1 })] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class DefaultObjectPool : ObjectPool where T : class { private readonly Func createFunc; private readonly Func returnFunc; private readonly int maxCapacity; private int numItems; private protected readonly ConcurrentQueue items = new ConcurrentQueue(); [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(2)] private protected T fastItem; public DefaultObjectPool(IPooledObjectPolicy policy) : this(policy, Environment.ProcessorCount * 2) { } public DefaultObjectPool(IPooledObjectPolicy policy, int maximumRetained) { createFunc = policy.Create; returnFunc = policy.Return; maxCapacity = maximumRetained - 1; } public override T Get() { T result = fastItem; if (result == null || Interlocked.CompareExchange(ref fastItem, null, result) != result) { if (items.TryDequeue(out result)) { Interlocked.Decrement(ref numItems); return result; } return createFunc(); } return result; } public override void Return(T obj) { ReturnCore(obj); } private protected bool ReturnCore(T obj) { if (!returnFunc(obj)) { return false; } if (fastItem != null || Interlocked.CompareExchange(ref fastItem, obj, null) != null) { if (Interlocked.Increment(ref numItems) <= maxCapacity) { items.Enqueue(obj); return true; } Interlocked.Decrement(ref numItems); return false; } return true; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal class DefaultPooledObjectPolicy : IPooledObjectPolicy where T : class, new() { public T Create() { return new T(); } public bool Return(T obj) { if (obj is IResettable resettable) { return resettable.TryReset(); } return true; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal interface IPooledObjectPolicy { T Create(); bool Return(T obj); } internal interface IResettable { bool TryReset(); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal abstract class ObjectPool where T : class { public abstract T Get(); public abstract void Return(T obj); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal static class ObjectPool { public static ObjectPool Create([<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] IPooledObjectPolicy policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy()); } public static ObjectPool Create(int maximumRetained, [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(new byte[] { 2, 1 })] IPooledObjectPolicy policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy(), maximumRetained); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [DebuggerStepThrough] internal static class StringBuilderPool { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ObjectPool pool; public BuilderWrapper(StringBuilder builder, ObjectPool pool) { Builder = builder; this.pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { pool.Return(Builder); } } private static readonly ObjectPool Pool = ObjectPool.Create(new StringBuilderPooledObjectPolicy { InitialCapacity = 16, MaximumRetainedCapacity = 1024 }); public static BuilderWrapper Rent() { StringBuilder builder = Pool.Get(); return new BuilderWrapper(builder, Pool); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal class StringBuilderPooledObjectPolicy : IPooledObjectPolicy { public int InitialCapacity { get; set; } = 100; public int MaximumRetainedCapacity { get; set; } = 4096; public StringBuilder Create() { return new StringBuilder(InitialCapacity); } public bool Return(StringBuilder obj) { if (obj.Capacity > MaximumRetainedCapacity) { return false; } obj.Clear(); return true; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] internal static class StringLookAheadBufferPool { [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] internal readonly struct BufferWrapper : IDisposable { public readonly StringLookAheadBuffer Buffer; private readonly ObjectPool pool; public BufferWrapper(StringLookAheadBuffer buffer, ObjectPool pool) { Buffer = buffer; this.pool = pool; } public override string ToString() { return Buffer.ToString(); } public void Dispose() { pool.Return(Buffer); } } private static readonly ObjectPool Pool = ObjectPool.Create(new DefaultPooledObjectPolicy()); public static BufferWrapper Rent(string value) { StringLookAheadBuffer stringLookAheadBuffer = Pool.Get(); stringLookAheadBuffer.Value = value; return new BufferWrapper(stringLookAheadBuffer, Pool); } } } namespace YamlDotNet.Core.Events { [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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 + "]"; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(2)] 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) { } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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 } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>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); } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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; } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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 } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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); } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>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.Diagnostics.CodeAnalysis { [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MaybeNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] 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; } } [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] 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; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [<198a2ca5-29ee-4a3f-8541-78dde289ff8d>Nullable(0)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [<16ed2a80-a41e-45a7-8f08-0e42134982a5>NullableContext(1)] [DebuggerNonUserCode] 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; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<2e0ad89f-2fc4-45a8-85ff-508b3549e9c5>Embedded] internal sealed class <2e0ad89f-2fc4-45a8-85ff-508b3549e9c5>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] [<2e0ad89f-2fc4-45a8-85ff-508b3549e9c5>Embedded] 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)] [<2e0ad89f-2fc4-45a8-85ff-508b3549e9c5>Embedded] internal sealed class <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContextAttribute : Attribute { public readonly byte Flag; public <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace AzuExtendedPlayerInventory { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] [Nullable(0)] [PublicAPI] internal class API { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(0)] public delegate void SlotAddedHandler(string slotName); [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(0)] public delegate void SlotRemovedHandler(string slotName); private static readonly Dictionary _slotAddedMap = new Dictionary(); private static readonly Dictionary _slotRemovedMap = new Dictionary(); private static readonly Dictionary, Action> _hudAwakeMap = new Dictionary, Action>(); private static readonly Dictionary, Action> _hudAwakeCompleteMap = new Dictionary, Action>(); private static readonly Dictionary, Action> _hudUpdateMap = new Dictionary, Action>(); private static readonly Dictionary, Action> _hudUpdateCompleteMap = new Dictionary, Action>(); [Nullable(2)] public static event SlotAddedHandler SlotAdded { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] add { if (value == null || _slotAddedMap.ContainsKey(value)) { return; } AzuEPI.API.SlotAddedHandler value2 = delegate(string s) { try { value(s); } catch { } }; _slotAddedMap[value] = value2; AzuEPI.API.SlotAdded += value2; } [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] remove { if (value != null && _slotAddedMap.TryGetValue(value, out var value2)) { AzuEPI.API.SlotAdded -= value2; _slotAddedMap.Remove(value); } } } [Nullable(2)] public static event SlotRemovedHandler SlotRemoved { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] add { if (value == null || _slotRemovedMap.ContainsKey(value)) { return; } AzuEPI.API.SlotRemovedHandler value2 = delegate(string s) { try { value(s); } catch { } }; _slotRemovedMap[value] = value2; AzuEPI.API.SlotRemoved += value2; } [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] remove { if (value != null && _slotRemovedMap.TryGetValue(value, out var value2)) { AzuEPI.API.SlotRemoved -= value2; _slotRemovedMap.Remove(value); } } } [Nullable(new byte[] { 2, 1 })] public static event Action OnHudAwake { [param: Nullable(new byte[] { 2, 1 })] add { AddHudEvent(value, _hudAwakeMap, delegate(Action h) { AzuEPI.API.OnHudAwake += h; }); } [param: Nullable(new byte[] { 2, 1 })] remove { RemoveHudEvent(value, _hudAwakeMap, delegate(Action h) { AzuEPI.API.OnHudAwake -= h; }); } } [Nullable(new byte[] { 2, 1 })] public static event Action OnHudAwakeComplete { [param: Nullable(new byte[] { 2, 1 })] add { AddHudEvent(value, _hudAwakeCompleteMap, delegate(Action h) { AzuEPI.API.OnHudAwakeComplete += h; }); } [param: Nullable(new byte[] { 2, 1 })] remove { RemoveHudEvent(value, _hudAwakeCompleteMap, delegate(Action h) { AzuEPI.API.OnHudAwakeComplete -= h; }); } } [Nullable(new byte[] { 2, 1 })] public static event Action OnHudUpdate { [param: Nullable(new byte[] { 2, 1 })] add { AddHudEvent(value, _hudUpdateMap, delegate(Action h) { AzuEPI.API.OnHudUpdate += h; }); } [param: Nullable(new byte[] { 2, 1 })] remove { RemoveHudEvent(value, _hudUpdateMap, delegate(Action h) { AzuEPI.API.OnHudUpdate -= h; }); } } [Nullable(new byte[] { 2, 1 })] public static event Action OnHudUpdateComplete { [param: Nullable(new byte[] { 2, 1 })] add { AddHudEvent(value, _hudUpdateCompleteMap, delegate(Action h) { AzuEPI.API.OnHudUpdateComplete += h; }); } [param: Nullable(new byte[] { 2, 1 })] remove { RemoveHudEvent(value, _hudUpdateCompleteMap, delegate(Action h) { AzuEPI.API.OnHudUpdateComplete -= h; }); } } private static void AddHudEvent([Nullable(new byte[] { 2, 1 })] Action handler, Dictionary, Action> map, Action> subscribe) { if (handler == null || map.ContainsKey(handler)) { return; } Action value = delegate(Hud h) { try { handler(h); } catch { } }; map[handler] = value; } private static void RemoveHudEvent([Nullable(new byte[] { 2, 1 })] Action handler, Dictionary, Action> map, Action> unsubscribe) { if (handler != null && map.TryGetValue(handler, out var _)) { map.Remove(handler); } } public static bool IsLoaded() { return AzuEPI.API.IsLoaded(); } public static bool AddSlot(string slotName, [Nullable(new byte[] { 1, 1, 2 })] Func getItem, Func isValid, int index = -1) { return false; } public static bool RemoveSlot(string slotName) { return AzuEPI.API.RemoveSlot(slotName); } public static SlotInfo GetSlots() { AzuEPI.SlotInfo slots = AzuEPI.API.GetSlots(); return new SlotInfo { SlotNames = (slots.SlotNames ?? Array.Empty()), SlotPositions = (slots.SlotPositions ?? Array.Empty()), GetItemFuncs = (slots.GetItemFuncs ?? Array.Empty>()), IsValidFuncs = (slots.IsValidFuncs ?? Array.Empty>()) }; } public static SlotInfo GetQuickSlots() { AzuEPI.SlotInfo quickSlots = AzuEPI.API.GetQuickSlots(); return new SlotInfo { SlotNames = (quickSlots.SlotNames ?? Array.Empty()), SlotPositions = (quickSlots.SlotPositions ?? Array.Empty()), GetItemFuncs = (quickSlots.GetItemFuncs ?? Array.Empty>()), IsValidFuncs = (quickSlots.IsValidFuncs ?? Array.Empty>()) }; } public static List GetQuickSlotsItems() { return AzuEPI.API.GetQuickSlotsItems(); } public static int GetAddedRows(int width) { return AzuEPI.API.GetAddedRows(width); } public static void HudAwake(Hud h) { } public static void HudAwakeComplete(Hud h) { } public static void HudUpdate(Hud h) { } public static void HudUpdateComplete(Hud h) { } private static void SafeInvoke(Action a) { try { a(); } catch { } } } [PublicAPI] [Nullable(0)] [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] internal class SlotInfo { public string[] SlotNames { get; set; } = Array.Empty(); public Vector2[] SlotPositions { get; set; } = Array.Empty(); [Nullable(new byte[] { 1, 2, 1, 2 })] [field: Nullable(new byte[] { 1, 2, 1, 2 })] public Func[] GetItemFuncs { [return: Nullable(new byte[] { 1, 2, 1, 2 })] get; [param: Nullable(new byte[] { 1, 2, 1, 2 })] set; } = Array.Empty>(); [Nullable(new byte[] { 1, 2, 1 })] [field: Nullable(new byte[] { 1, 2, 1 })] public Func[] IsValidFuncs { [return: Nullable(new byte[] { 1, 2, 1 })] get; [param: Nullable(new byte[] { 1, 2, 1 })] set; } = Array.Empty>(); } } namespace AzuEPI { [PublicAPI] [Nullable(0)] [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] internal class API { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(0)] public delegate void SlotAddedHandler(string slotName); [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(0)] public delegate void SlotRemovedHandler(string slotName); [Nullable(new byte[] { 1, 2 })] [field: Nullable(new byte[] { 1, 2 })] internal static HashSet CustomSlots { [return: Nullable(new byte[] { 1, 2 })] get; } = new HashSet(); [Nullable(new byte[] { 2, 1 })] [method: Nullable(new byte[] { 2, 1 })] [field: Nullable(new byte[] { 2, 1 })] public static event Action OnHudAwake; [Nullable(new byte[] { 2, 1 })] [method: Nullable(new byte[] { 2, 1 })] [field: Nullable(new byte[] { 2, 1 })] public static event Action OnHudAwakeComplete; [Nullable(new byte[] { 2, 1 })] [method: Nullable(new byte[] { 2, 1 })] [field: Nullable(new byte[] { 2, 1 })] public static event Action OnHudUpdate; [Nullable(new byte[] { 2, 1 })] [method: Nullable(new byte[] { 2, 1 })] [field: Nullable(new byte[] { 2, 1 })] public static event Action OnHudUpdateComplete; [Nullable(2)] [method: <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] [field: Nullable(2)] public static event Action OnBeforeQuickSlotsAdded; [Nullable(2)] [method: <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] [field: Nullable(2)] public static event Action OnQuickSlotsAdded; [Nullable(2)] [method: <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] [field: Nullable(2)] public static event SlotAddedHandler SlotAdded; [Nullable(2)] [method: <2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] [field: Nullable(2)] public static event SlotRemovedHandler SlotRemoved; [Nullable(new byte[] { 2, 1 })] [method: Nullable(new byte[] { 2, 1 })] [field: Nullable(new byte[] { 2, 1 })] public static event Action OnRegisterVisualPrefab; public static bool IsLoaded() { return false; } public static ItemType GetFakeItemType() { return (ItemType)0; } public static bool AddSlot(string slotName, [Nullable(new byte[] { 1, 1, 2 })] Func getItem, Func isValid, int index = -1) { return false; } public static bool AddSlot(string slotName, string prefabName, int index = -1) { return false; } public static bool AddSlot(string slotName, IEnumerable prefabNames, int index = -1) { return false; } public static bool AddSlot(string slotName, Func isValid, int index = -1, [Nullable(new byte[] { 2, 1 })] IEnumerable prefabNamesForVisuals = null) { return false; } public static bool AddQuickSlot(string slotName, bool showName = false, int index = -1) { return false; } public static bool RemoveSlot(string slotName) { return false; } public static SlotInfo GetSlots() { return BuildSlotInfo((Model.Slot _) => true); } public static SlotInfo GetQuickSlots() { return BuildSlotInfo((Model.Slot s) => s.IsQuickSlot); } public static SlotInfo GetEquipmentSlots() { return BuildSlotInfo((Model.Slot s) => !s.IsQuickSlot && s.EquipmentSlot != null); } private static SlotInfo BuildSlotInfo(Func filter) { return new SlotInfo(); } public static List GetQuickSlotsItems() { return new List(); } public static int GetAddedRows(int width) { return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetFullHeight(int width) { return 0; } public static void RegisterVisualPrefabs(string slotName, [Nullable(new byte[] { 1, 0, 1, 1 })] params (string prefabName, string visualName)[] pairs) { } public static int GetSlotCount() { return 0; } public static bool TryGetSlotIndexByName(string slotName, out int index, bool allowLocalized = true) { index = -1; return false; } public static bool TryGetSlotDescriptor(int index, out SlotDescriptor desc) { desc = default(SlotDescriptor); return false; } public static int GetSlotGridLinearIndex(Inventory inv, int slotIndex) { return -1; } public static Vector2i GetSlotGridPos(Inventory inv, int slotIndex) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return new Vector2i(-1, -1); } public static bool TryGetSlotIndexAtGridPos(Inventory inv, Vector2i gridPos, out int slotIndex) { slotIndex = -1; return false; } public static bool IsEquipmentCell(Inventory inv, int x, int y, out int slotIndex) { slotIndex = -1; return false; } public static bool IsQuickCell(Inventory inv, int x, int y, out int slotIndex) { slotIndex = -1; return false; } public static bool TryGetSlotSnapshot(Inventory inv, int slotIndex, out SlotSnapshot snapshot) { snapshot = default(SlotSnapshot); return false; } public static IEnumerable EnumerateSlots() { yield break; } public static IEnumerable GetAllSlotSnapshots(Inventory inv) { yield break; } public static IEnumerable GetQuickSlotSnapshots(Inventory inv) { yield break; } public static IEnumerable GetEquipmentSlotSnapshots(Inventory inv) { yield break; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryGetSlotIndexByItem(Player player, ItemData item, out int slotIndex) { slotIndex = -1; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryGetSlotIndexByItem(ItemData item, out int slotIndex) { slotIndex = -1; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryGetSlotDescriptorByItem(Player player, ItemData item, out SlotDescriptor desc) { desc = default(SlotDescriptor); return false; } public static bool SlotValidates(int slotIndex, ItemData item) { return false; } [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] public static bool TryGetEquippedItem(int slotIndex, out ItemData item) { item = null; return false; } public static bool TryGetSlotDescriptorByName(string slotName, out SlotDescriptor desc, bool allowLocalized = true) { desc = default(SlotDescriptor); if (!TryGetSlotIndexByName(slotName, out var index, allowLocalized)) { return false; } return TryGetSlotDescriptor(index, out desc); } } [PublicAPI] [Nullable(0)] [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] internal class SlotInfo { public string[] SlotNames { get; set; } = new string[0]; public string[] OriginalSlotNames { get; set; } = new string[0]; public Vector2[] SlotPositions { get; set; } = (Vector2[])(object)new Vector2[0]; [Nullable(new byte[] { 1, 2, 1, 2 })] [field: Nullable(new byte[] { 1, 2, 1, 2 })] public Func[] GetItemFuncs { [return: Nullable(new byte[] { 1, 2, 1, 2 })] get; [param: Nullable(new byte[] { 1, 2, 1, 2 })] set; } = new Func[0]; [Nullable(new byte[] { 1, 2, 1 })] [field: Nullable(new byte[] { 1, 2, 1 })] public Func[] IsValidFuncs { [return: Nullable(new byte[] { 1, 2, 1 })] get; [param: Nullable(new byte[] { 1, 2, 1 })] set; } = new Func[0]; } [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] [Nullable(0)] [PublicAPI] internal struct SlotDescriptor { public int Index { get; } public string Name { get; } public string OriginalName { get; } public bool IsQuickSlot { get; } public bool IsEquipmentSlot { get; } public bool IsCustom { get; } public Vector2 UiPosition { get; } public SlotDescriptor(int index, string name, string originalName, bool isQuickSlot, bool isEquipmentSlot, bool isCustom, Vector2 uiPosition) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) Index = index; Name = name ?? string.Empty; OriginalName = originalName ?? string.Empty; IsQuickSlot = isQuickSlot; IsEquipmentSlot = isEquipmentSlot; IsCustom = isCustom; UiPosition = uiPosition; } } [PublicAPI] internal struct SlotSnapshot { public SlotDescriptor Descriptor { get; } public bool Occupied { get; } public Vector2i GridPos { get; } public int LinearGridIndex { get; } public SlotSnapshot(SlotDescriptor descriptor, bool occupied, Vector2i gridPos, int linearGridIndex) { //IL_000f: 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) Descriptor = descriptor; Occupied = occupied; GridPos = gridPos; LinearGridIndex = linearGridIndex; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] public bool Validates(ItemData item) { return API.SlotValidates(Descriptor.Index, item); } } } namespace AzuEPI.Core.Slots { internal class Model { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(1)] [Nullable(0)] internal class Slot { public string Name; public string OriginalName; public Vector2 Position; public bool IsQuickSlot; public bool IsAPIAdded; public bool Occupied; [Nullable(2)] public EquipmentSlot EquipmentSlot { [<2f14ac51-6b6f-4c52-a5d6-b8cfbb80526b>NullableContext(2)] get { return this as EquipmentSlot; } } } internal class EquipmentSlot : Slot { [Nullable(new byte[] { 2, 1, 2 })] public Func Get; [Nullable(new byte[] { 2, 1 })] public Func Valid; } } } 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] [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; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace BiomeLockAPI { internal static class API { private const string ImplAssemblyName = "BiomeLock"; private const string ImplTypeName = "BiomeLock.BiomeLockAPI"; private const int ResolveRetryMs = 1000; private static Type? _impl; private static int _nextResolveTick; private static Func? _isReady; private static Func? _hasPrivateKey; private static Func? _hasProgressionKey; private static Func>? _getPrivateKeys; private static Func? _isBiomeLocked; private static Func? _isRestricted; private static readonly List<(string EventName, Delegate Handler)> Pending = new List<(string, Delegate)>(); public const string PrivatePrefix = "bl_"; public static bool IsLoaded => Resolve(); public static bool IsReady => Resolve() && _isReady(); public static event Action OnPrivateKeyAdded { add { Subscribe("OnPrivateKeyAdded", value); } remove { Unsubscribe("OnPrivateKeyAdded", value); } } public static event Action OnPrivateKeyRemoved { add { Subscribe("OnPrivateKeyRemoved", value); } remove { Unsubscribe("OnPrivateKeyRemoved", value); } } public static event Action OnPrivateKeysReset { add { Subscribe("OnPrivateKeysReset", value); } remove { Unsubscribe("OnPrivateKeysReset", value); } } public static event Action OnPrivateKeysLoaded { add { Subscribe("OnPrivateKeysLoaded", value); } remove { Unsubscribe("OnPrivateKeysLoaded", value); } } public static bool HasPrivateKey(string globalOrPrivateKey) { return globalOrPrivateKey != null && Resolve() && _hasPrivateKey(globalOrPrivateKey); } public static bool HasProgressionKey(string globalOrPrivateKey) { if (globalOrPrivateKey == null) { return false; } if (Resolve()) { return _hasProgressionKey(globalOrPrivateKey); } string text = ToGlobalKey(globalOrPrivateKey); return text.Length > 0 && (Object)(object)ZoneSystem.instance != (Object)null && ZoneSystem.instance.GetGlobalKey(text); } public static IReadOnlyList GetPrivateKeys() { IReadOnlyList result; if (!Resolve()) { IReadOnlyList readOnlyList = Array.Empty(); result = readOnlyList; } else { result = _getPrivateKeys(); } return result; } public static bool IsBiomeLocked(Biome biome) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) return Resolve() && _isBiomeLocked(biome); } public static bool IsRestricted() { return Resolve() && _isRestricted(); } public static string ToPrivateKey(string globalOrPrivateKey) { string text = Normalize(globalOrPrivateKey); if (text.Length == 0) { return string.Empty; } return text.StartsWith("bl_", StringComparison.Ordinal) ? text : ("bl_" + text); } public static string ToGlobalKey(string globalOrPrivateKey) { string text = Normalize(globalOrPrivateKey); return text.StartsWith("bl_", StringComparison.Ordinal) ? text.Substring("bl_".Length) : text; } private static string Normalize(string? key) { return (key ?? string.Empty).Trim().ToLowerInvariant(); } private static void Subscribe(string eventName, Delegate? handler) { if ((object)handler != null) { if (Resolve()) { _impl.GetEvent(eventName)?.AddEventHandler(null, handler); } else { Pending.Add((eventName, handler)); } } } private static void Unsubscribe(string eventName, Delegate? handler) { if ((object)handler != null) { Pending.RemoveAll(((string EventName, Delegate Handler) p) => p.EventName == eventName && p.Handler == handler); if (Resolve()) { _impl.GetEvent(eventName)?.RemoveEventHandler(null, handler); } } } private static bool Resolve() { if (_impl != null) { return true; } int tickCount = Environment.TickCount; if (tickCount - _nextResolveTick < 0) { return false; } _nextResolveTick = tickCount + 1000; Type type = FindImplType(); if (type == null) { return false; } try { _isReady = Getter(type, "IsReady"); _hasPrivateKey = Method>(type, "HasPrivateKey"); _hasProgressionKey = Method>(type, "HasProgressionKey"); _getPrivateKeys = Method>>(type, "GetPrivateKeys"); _isBiomeLocked = Method>(type, "IsBiomeLocked"); _isRestricted = Method>(type, "IsRestricted"); } catch { return false; } _impl = type; foreach (var (name, handler) in Pending) { type.GetEvent(name)?.AddEventHandler(null, handler); } Pending.Clear(); return true; } private static Type? FindImplType() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (!(assembly.GetName().Name != "BiomeLock")) { return assembly.GetType("BiomeLock.BiomeLockAPI", throwOnError: false); } } return null; } private static T Method(Type impl, string name) where T : Delegate { MethodInfo method = impl.GetMethod(name, BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMethodException("BiomeLock.BiomeLockAPI", name); return (T)Delegate.CreateDelegate(typeof(T), method); } private static Func Getter(Type impl, string name) { MethodInfo method = impl.GetProperty(name, BindingFlags.Static | BindingFlags.Public)?.GetGetMethod() ?? throw new MissingMemberException("BiomeLock.BiomeLockAPI", name); return (Func)Delegate.CreateDelegate(typeof(Func), method); } } }