Decompiled source of ServersideQoL BETA v1.2.2013

Valheim.ServersideQoL.dll

Decompiled 13 hours ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using MonoMod.Cil;
using MonoMod.Utils;
using SoftReferenceableAssets;
using UnityEngine;
using Valheim.ServersideQoL.HarmonyPatches;
using Valheim.ServersideQoL.Processors;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.TypeInspectors;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Valheim.ServersideQoL")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.2.0")]
[assembly: AssemblyInformationalVersion("1.2.2-beta.0.13+13856f8ec28527afde6aa1afc782e1986d8f1f8b")]
[assembly: AssemblyProduct("Valheim.ServersideQoL")]
[assembly: AssemblyTitle("Valheim.ServersideQoL")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 Valheim.ServersideQoL
{
	internal sealed class ConcurrentHashSet<T> : ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T> where T : notnull
	{
		private readonly ConcurrentDictionary<T, object?> _dict = new ConcurrentDictionary<T, object>();

		public int Count => _dict.Count;

		bool ICollection<T>.IsReadOnly => false;

		public bool Add(T value)
		{
			return _dict.TryAdd(value, null);
		}

		public bool Remove(T value)
		{
			object value2;
			return _dict.TryRemove(value, out value2);
		}

		void ICollection<T>.Add(T item)
		{
			if (!Add(item))
			{
				throw new InvalidOperationException();
			}
		}

		public void Clear()
		{
			_dict.Clear();
		}

		public bool Contains(T item)
		{
			return _dict.ContainsKey(item);
		}

		void ICollection<T>.CopyTo(T[] array, int arrayIndex)
		{
			throw new NotImplementedException();
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			return _dict.Keys.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _dict.Keys.GetEnumerator();
		}
	}
	internal static class EnumUtils
	{
		private static class Generic<T> where T : unmanaged, Enum
		{
			public static bool IsBitSet { get; } = OfType(typeof(T)).IsBitSet;


			public static Func<T, ulong> EnumToUInt64 { get; }

			public static Func<ulong, T> UInt64ToEnum { get; }

			public static Func<T, long> EnumToInt64 { get; }

			public static Func<long, T> Int64ToEnum { get; }

			static Generic()
			{
				ParameterExpression parameterExpression = Expression.Parameter(typeof(T));
				EnumToUInt64 = Expression.Lambda<Func<T, ulong>>(Expression.ConvertChecked(parameterExpression, typeof(ulong)), new ParameterExpression[1] { parameterExpression }).Compile();
				ParameterExpression parameterExpression2 = Expression.Parameter(typeof(ulong));
				UInt64ToEnum = Expression.Lambda<Func<ulong, T>>(Expression.ConvertChecked(parameterExpression2, typeof(T)), new ParameterExpression[1] { parameterExpression2 }).Compile();
				ParameterExpression parameterExpression3 = Expression.Parameter(typeof(T));
				EnumToInt64 = Expression.Lambda<Func<T, long>>(Expression.ConvertChecked(parameterExpression3, typeof(long)), new ParameterExpression[1] { parameterExpression3 }).Compile();
				ParameterExpression parameterExpression4 = Expression.Parameter(typeof(long));
				Int64ToEnum = Expression.Lambda<Func<long, T>>(Expression.ConvertChecked(parameterExpression4, typeof(T)), new ParameterExpression[1] { parameterExpression4 }).Compile();
			}
		}

		public sealed class ObjectEnumUtils
		{
			public bool IsBitSet { get; } = enumType.GetCustomAttribute<FlagsAttribute>() != null;


			public Func<object, ulong> EnumToUInt64 { get; }

			public Func<ulong, object> UInt64ToEnum { get; }

			public Func<object, long> EnumToInt64 { get; }

			public Func<long, object> Int64ToEnum { get; }

			public ObjectEnumUtils(Type enumType)
			{
				ParameterExpression parameterExpression = Expression.Parameter(typeof(object));
				EnumToUInt64 = Expression.Lambda<Func<object, ulong>>(Expression.ConvertChecked(Expression.Convert(parameterExpression, enumType), typeof(ulong)), new ParameterExpression[1] { parameterExpression }).Compile();
				ParameterExpression parameterExpression2 = Expression.Parameter(typeof(ulong));
				UInt64ToEnum = Expression.Lambda<Func<ulong, object>>(Expression.Convert(Expression.ConvertChecked(parameterExpression2, enumType), typeof(object)), new ParameterExpression[1] { parameterExpression2 }).Compile();
				ParameterExpression parameterExpression3 = Expression.Parameter(typeof(object));
				EnumToInt64 = Expression.Lambda<Func<object, long>>(Expression.ConvertChecked(Expression.Convert(parameterExpression3, enumType), typeof(long)), new ParameterExpression[1] { parameterExpression3 }).Compile();
				ParameterExpression parameterExpression4 = Expression.Parameter(typeof(long));
				Int64ToEnum = Expression.Lambda<Func<long, object>>(Expression.Convert(Expression.ConvertChecked(parameterExpression4, enumType), typeof(object)), new ParameterExpression[1] { parameterExpression4 }).Compile();
				base..ctor();
			}
		}

		private static readonly ConcurrentDictionary<Type, ObjectEnumUtils> __isBitSet = new ConcurrentDictionary<Type, ObjectEnumUtils>();

		public static ObjectEnumUtils OfType(Type type)
		{
			return __isBitSet.GetOrAdd(type, (Type t) => new ObjectEnumUtils(t));
		}

		public static bool IsBitSet<T>() where T : unmanaged, Enum
		{
			return Generic<T>.IsBitSet;
		}

		public static ulong ToUInt64<T>(this T value) where T : unmanaged, Enum
		{
			return Generic<T>.EnumToUInt64(value);
		}

		public static T ToEnum<T>(ulong value) where T : unmanaged, Enum
		{
			return Generic<T>.UInt64ToEnum(value);
		}

		public static long ToInt64<T>(this T value) where T : unmanaged, Enum
		{
			return Generic<T>.EnumToInt64(value);
		}

		public static T ToEnum<T>(long value) where T : unmanaged, Enum
		{
			return Generic<T>.Int64ToEnum(value);
		}

		public static bool ExactlyOneBitSet<T>(this T value) where T : unmanaged, Enum
		{
			bool flag = false;
			for (ulong num = value.ToUInt64(); num != 0L; num &= num - 1)
			{
				if (flag)
				{
					return false;
				}
				flag = true;
			}
			return flag;
		}
	}
	internal interface IZDOInventoryReadOnly
	{
		IReadOnlyList<ItemData> Items { get; }
	}
	internal interface IZDOInventory
	{
		Inventory Inventory { get; }

		IList<ItemData> Items { get; }

		int? PickupRange { get; set; }

		int? FeedRange { get; set; }

		void Save();
	}
	internal sealed class ExtendedZDO : ZDO
	{
		public delegate void RecreateHandler(ExtendedZDO oldZdo, ExtendedZDO newZdo);

		public readonly struct ZDOVars_
		{
			private readonly ExtendedZDO _zdo;

			private static int __intTag = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.IntTag");

			private static int __lastSpawnedTime = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.LastSpawnedTime");

			private static int __spawnedByTrophy = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.SpawnedByTrophy");

			private static int __portalHubId = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.PortalHubId");

			private static int __returnContentToCreator = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.ReturnContentToCreator");

			private static int __initialLevel = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.PortalHubId");

			public ZDOVars_(ExtendedZDO zdo)
			{
				_zdo = zdo;
			}

			private void ValidateOwnership(string filePath, int lineNo)
			{
				if (Main.Instance.Config.General.DiagnosticLogs.Value && _zdo.PrefabInfo.Container.HasValue && !_zdo.IsOwnerOrUnassigned() && !_zdo.IsModCreator())
				{
					Main.Instance.Logger.LogWarning((object)$"{Path.GetFileName(filePath)} L{lineNo}: Container was modified while it is owned by a client, which can lead to the loss of items.");
				}
			}

			public int GetState(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_state, defaultValue);
			}

			public void SetState(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_state, value, false);
			}

			public long GetCreator(long defaultValue = 0L)
			{
				return ((ZDO)_zdo).GetLong(ZDOVars.s_creator, defaultValue);
			}

			public void SetCreator(long value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_creator, value);
			}

			public bool GetInUse(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_inUse, defaultValue);
			}

			public void SetInUse(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_inUse, value);
			}

			public float GetFuel(float defaultValue = 0f)
			{
				return ((ZDO)_zdo).GetFloat(ZDOVars.s_fuel, defaultValue);
			}

			public void SetFuel(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_fuel, value);
			}

			public bool GetPiece(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_piece, defaultValue);
			}

			public void SetPiece(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_piece, value);
			}

			public string GetItems(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_items, defaultValue);
			}

			public void SetItems(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_items, value);
			}

			public string GetTag(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_tag, defaultValue);
			}

			public void SetTag(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_tag, value);
			}

			public byte[]? GetData(byte[]? defaultValue = null)
			{
				return ((ZDO)_zdo).GetByteArray(ZDOVars.s_data, defaultValue);
			}

			public void SetData(byte[]? value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_data, value);
			}

			public float GetStamina(float defaultValue = 0f)
			{
				return ((ZDO)_zdo).GetFloat(ZDOVars.s_stamina, defaultValue);
			}

			public void SetStamina(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_stamina, value);
			}

			public long GetPlayerID(long defaultValue = 0L)
			{
				return ((ZDO)_zdo).GetLong(ZDOVars.s_playerID, defaultValue);
			}

			public void SetPlayerID(long value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_playerID, value);
			}

			public string GetPlayerName(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_playerName, defaultValue);
			}

			public void SetPlayerName(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_playerName, value);
			}

			public string GetFollow(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_follow, defaultValue);
			}

			public void SetFollow(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_follow, value);
			}

			public int GetRightItem(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_rightItem, defaultValue);
			}

			public void SetRightItem(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_rightItem, value, false);
			}

			public string GetText(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_text, defaultValue);
			}

			public void SetText(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_text, value);
			}

			public string GetItem(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_item, defaultValue);
			}

			public void SetItem(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_item, value);
			}

			public string GetItem(int idx, string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(FormattableString.Invariant($"item{idx}"), defaultValue);
			}

			public void SetItem(int idx, string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(FormattableString.Invariant($"item{idx}"), value);
			}

			public int GetQueued(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_queued, defaultValue);
			}

			public void SetQueued(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_queued, value, false);
			}

			public bool GetTamed(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_tamed, defaultValue);
			}

			public void SetTamed(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_tamed, value);
			}

			public float GetTameTimeLeft(float defaultValue = 0f)
			{
				return ((ZDO)_zdo).GetFloat(ZDOVars.s_tameTimeLeft, defaultValue);
			}

			public void SetTameTimeLeft(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_tameTimeLeft, value);
			}

			public int GetAmmo(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_ammo, defaultValue);
			}

			public void SetAmmo(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_ammo, value, false);
			}

			public string GetAmmoType(string defaultValue = "")
			{
				return ((ZDO)_zdo).GetString(ZDOVars.s_ammoType, defaultValue);
			}

			public void SetAmmoType(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_ammoType, value);
			}

			public float GetGrowStart(float defaultValue = 0f)
			{
				return ((ZDO)_zdo).GetFloat(ZDOVars.s_growStart, defaultValue);
			}

			public void SetGrowStart(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_growStart, value);
			}

			public DateTime GetSpawnTime(DateTime defaultValue = default(DateTime))
			{
				return new DateTime(((ZDO)_zdo).GetLong(ZDOVars.s_spawnTime, defaultValue.Ticks));
			}

			public void SetSpawnTime(DateTime value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_spawnTime, value.Ticks);
			}

			public float GetHealth(float defaultValue = 0f)
			{
				return ((ZDO)_zdo).GetFloat(ZDOVars.s_health, defaultValue);
			}

			public void SetHealth(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_health, value);
			}

			public void RemoveHealth([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).RemoveFloat(ZDOVars.s_health);
			}

			public int GetPermitted(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_permitted, defaultValue);
			}

			public void SetPermitted(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_permitted, value, false);
			}

			public int GetLevel(int defaultValue = 1)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_level, defaultValue);
			}

			public void SetLevel(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_level, value, false);
			}

			public bool GetPatrol(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_patrol, defaultValue);
			}

			public void SetPatrol(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_patrol, value);
			}

			public Vector3 GetPatrolPoint(Vector3 defaultValue = default(Vector3))
			{
				//IL_000b: 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)
				return ((ZDO)_zdo).GetVec3(ZDOVars.s_patrolPoint, defaultValue);
			}

			public void SetPatrolPoint(Vector3 value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_patrolPoint, value);
			}

			public Vector3 GetSpawnPoint(Vector3 defaultValue = default(Vector3))
			{
				//IL_000b: 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)
				return ((ZDO)_zdo).GetVec3(ZDOVars.s_spawnPoint, defaultValue);
			}

			public void SetSpawnPoint(Vector3 value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				//IL_0013: Unknown result type (might be due to invalid IL or missing references)
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_spawnPoint, value);
			}

			public int GetEmoteID(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(ZDOVars.s_emoteID, defaultValue);
			}

			public Emotes GetEmote(Emotes defaultValue = -1)
			{
				//IL_0021: 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)
				if (!Enum.TryParse<Emotes>(((ZDO)_zdo).GetString(ZDOVars.s_emote, ""), ignoreCase: true, out Emotes result))
				{
					return defaultValue;
				}
				return result;
			}

			public bool GetAnimationIsEncumbered(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.CharacterAnimationHashEncumbered, defaultValue);
			}

			public bool GetAnimationInWater(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.CharacterAnimationHashInWater, defaultValue);
			}

			public bool GetAnimationIsCrouching(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.PlayerAnimationHashCrouching, defaultValue);
			}

			public DateTime GetTameLastFeeding(DateTime defaultValue = default(DateTime))
			{
				return new DateTime(((ZDO)_zdo).GetLong(ZDOVars.s_tameLastFeeding, defaultValue.Ticks));
			}

			public void SetTameLastFeeding(DateTime value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(ZDOVars.s_tameLastFeeding, value.Ticks);
			}

			public bool GetEventCreature(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_eventCreature, defaultValue);
			}

			public bool GetInBed(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(ZDOVars.s_inBed, defaultValue);
			}

			public int GetIntTag(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(__intTag, defaultValue);
			}

			public void SetIntTag(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__intTag, value, false);
			}

			public void RemoveIntTag([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).RemoveInt(__intTag);
			}

			public DateTimeOffset GetLastSpawnedTime(DateTimeOffset defaultValue = default(DateTimeOffset))
			{
				return new DateTimeOffset(((ZDO)_zdo).GetLong(__lastSpawnedTime, defaultValue.Ticks), default(TimeSpan));
			}

			public void SetLastSpawnedTime(DateTimeOffset value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__lastSpawnedTime, value.Ticks - value.Offset.Ticks);
			}

			public bool GetSpawnedByTrophy(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(__spawnedByTrophy, defaultValue);
			}

			public void SetSpawnedByTrophy(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__spawnedByTrophy, value);
			}

			public int GetPortalHubId(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(__portalHubId, defaultValue);
			}

			public void SetPortalHubId(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__portalHubId, value, false);
			}

			public bool GetReturnContentToCreator(bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool(__returnContentToCreator, defaultValue);
			}

			public void SetReturnContentToCreator(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__returnContentToCreator, value);
			}

			public int GetInitialLevel(int defaultValue = 0)
			{
				return ((ZDO)_zdo).GetInt(__initialLevel, defaultValue);
			}

			public void SetInitialLevel(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set(__initialLevel, value, false);
			}

			public void RemoveInitialLevel([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).RemoveInt(__initialLevel);
			}

			public bool GetSacrifiedMegingjord(long playerID, bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedMegingjord", defaultValue);
			}

			public void SetSacrifiedMegingjord(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set($"player{playerID}_SacrifiedMegingjord", value);
			}

			public bool GetSacrifiedCryptKey(long playerID, bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedCryptKey", defaultValue);
			}

			public void SetSacrifiedCryptKey(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set($"player{playerID}_SacrifiedCryptKey", value);
			}

			public bool GetSacrifiedWishbone(long playerID, bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedWishbone", defaultValue);
			}

			public void SetSacrifiedWishbone(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set($"player{playerID}_SacrifiedWishbone", value);
			}

			public bool GetSacrifiedTornSpirit(long playerID, bool defaultValue = false)
			{
				return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedTornSpirit", defaultValue);
			}

			public void SetSacrifiedTornSpirit(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0)
			{
				ValidateOwnership(filePath, lineNo);
				((ZDO)_zdo).Set($"player{playerID}_SacrifiedTornSpirit", value);
			}
		}

		private sealed class AdditionalData_
		{
			private static ConcurrentDictionary<int, IReadOnlyList<Processor>> _processors = new ConcurrentDictionary<int, IReadOnlyList<Processor>>();

			public IReadOnlyList<Processor> Processors { get; private set; } = Processor.DefaultProcessors;


			public PrefabInfo PrefabInfo { get; }

			public ConcurrentDictionary<Type, object>? ComponentFieldAccessors { get; set; }

			public Dictionary<Processor, (uint Data, uint Owner)>? ProcessorDataRevisions { get; set; }

			public ZDOInventory? Inventory { get; set; }

			public bool? HasFields { get; set; }

			public RecreateHandler? Recreated { get; set; }

			public Action<ExtendedZDO>? Destroyed { get; set; }

			public static AdditionalData_ Dummy { get; } = new AdditionalData_(Valheim.ServersideQoL.PrefabInfo.Dummy);


			public AdditionalData_(PrefabInfo prefabInfo)
			{
				PrefabInfo = prefabInfo;
				base..ctor();
			}

			public void Ungregister(IEnumerable<Processor> processors)
			{
				IEnumerable<Processor> processors2 = processors;
				int num = 0;
				foreach (Processor processor in Processors)
				{
					if (!processors2.Any((Processor x) => x == processor))
					{
						num = (num, processor.GetType()).GetHashCode();
					}
				}
				Processors = _processors.GetOrAdd(num, (int _) => Processors.Where((Processor x) => !processors2.Any((Processor y) => x == y)).ToList());
				foreach (Processor item in processors2)
				{
					ProcessorDataRevisions?.Remove(item);
				}
			}

			public void UnregisterAll()
			{
				Processors = Array.Empty<Processor>();
			}

			public void ReregisterAll()
			{
				Processors = Processor.DefaultProcessors;
			}
		}

		public sealed class ComponentFieldAccessor<TComponent>
		{
			private readonly ExtendedZDO _zdo;

			private readonly TComponent _component;

			private bool? _hasComponentFields;

			private static readonly int __hasComponentFieldsHash = StringExtensionMethods.GetStableHashCode(FormattableString.Invariant(FormattableStringFactory.Create("{0}{1}", "HasFields", typeof(TComponent).Name)));

			public bool HasFields
			{
				get
				{
					if (_zdo.HasFields)
					{
						bool valueOrDefault = _hasComponentFields.GetValueOrDefault();
						if (!_hasComponentFields.HasValue)
						{
							valueOrDefault = ((ZDO)_zdo).GetBool(__hasComponentFieldsHash, false);
							_hasComponentFields = valueOrDefault;
							return valueOrDefault;
						}
						return valueOrDefault;
					}
					return false;
				}
			}

			public ComponentFieldAccessor(ExtendedZDO zdo, TComponent component)
			{
				_zdo = zdo;
				_component = component;
				base..ctor();
			}

			private void SetHasFields(bool value)
			{
				if (value && !_zdo.HasFields)
				{
					_zdo.SetHasFields();
				}
				if (_hasComponentFields != value)
				{
					ExtendedZDO zdo = _zdo;
					int _hasComponentFieldsHash = __hasComponentFieldsHash;
					bool? flag = (_hasComponentFields = value);
					((ZDO)zdo).Set(_hasComponentFieldsHash, flag.Value);
				}
			}

			private static int GetHash<T>(Expression<Func<TComponent, T>> fieldExpression, out FieldInfo field)
			{
				MemberExpression memberExpression = (MemberExpression)fieldExpression.Body;
				field = (FieldInfo)memberExpression.Member;
				return StringExtensionMethods.GetStableHashCode(FormattableString.Invariant($"{typeof(TComponent).Name}.{field.Name}"));
			}

			private T Get<T>(Expression<Func<TComponent, T>> fieldExpression, Func<ZDO, int, T?, T> getter)
			{
				FieldInfo fieldInfo = (FieldInfo)((MemberExpression)fieldExpression.Body).Member;
				if (!HasFields)
				{
					return (T)fieldInfo.GetValue(_component);
				}
				int stableHashCode = StringExtensionMethods.GetStableHashCode(FormattableString.Invariant($"{typeof(TComponent).Name}.{fieldInfo.Name}"));
				return getter((ZDO)(object)_zdo, stableHashCode, (T)fieldInfo.GetValue(_component));
			}

			public bool GetBool(Expression<Func<TComponent, bool>> fieldExpression)
			{
				return Get(fieldExpression, (ZDO zdo, int hash, bool defaultValue) => zdo.GetBool(hash, defaultValue));
			}

			public float GetFloat(Expression<Func<TComponent, float>> fieldExpression)
			{
				return Get(fieldExpression, (ZDO zdo, int hash, float defaultValue) => zdo.GetFloat(hash, defaultValue));
			}

			public int GetInt(Expression<Func<TComponent, int>> fieldExpression)
			{
				return Get(fieldExpression, (ZDO zdo, int hash, int defaultValue) => zdo.GetInt(hash, defaultValue));
			}

			public string GetString(Expression<Func<TComponent, string>> fieldExpression)
			{
				return Get(fieldExpression, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue));
			}

			private ComponentFieldAccessor<TComponent> SetCore<TObj, T>(Expression<Func<TComponent, TObj>> fieldExpression, TObj valueObj, Action<ZDO, int>? remover, Action<ZDO, int, T> setter, Func<TObj, T> cast) where TObj : notnull where T : notnull
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				T arg = cast(valueObj);
				if (remover != null)
				{
					ref T reference = ref arg;
					T val = default(T);
					if (val == null)
					{
						val = reference;
						reference = ref val;
					}
					if (reference.Equals(cast((TObj)field.GetValue(_component))))
					{
						remover((ZDO)(object)_zdo, hash);
						goto IL_008b;
					}
				}
				if (!HasFields)
				{
					SetHasFields(value: true);
				}
				setter((ZDO)(object)_zdo, hash, arg);
				goto IL_008b;
				IL_008b:
				return this;
			}

			private ComponentFieldAccessor<TComponent> SetCore<T>(Expression<Func<TComponent, T>> fieldExpression, T value, Action<ZDO, int>? remover, Action<ZDO, int, T> setter) where T : notnull
			{
				return SetCore(fieldExpression, value, remover, setter, (T x) => x);
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, bool>> fieldExpression, bool value)
			{
				return SetCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				}, delegate(ZDO zdo, int hash, bool value)
				{
					zdo.Set(hash, value);
				});
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, float>> fieldExpression, float value)
			{
				return SetCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveFloat(hash);
				}, delegate(ZDO zdo, int hash, float value)
				{
					zdo.Set(hash, value);
				});
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, int>> fieldExpression, int value)
			{
				return SetCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				}, delegate(ZDO zdo, int hash, int value)
				{
					zdo.Set(hash, value, false);
				});
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, Vector3>> fieldExpression, Vector3 value)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				return SetCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveVec3(hash);
				}, delegate(ZDO zdo, int hash, Vector3 value)
				{
					//IL_0002: Unknown result type (might be due to invalid IL or missing references)
					zdo.Set(hash, value);
				});
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, string>> fieldExpression, string value)
			{
				return SetCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				});
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, GameObject>> fieldExpression, GameObject value)
			{
				return SetCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (GameObject x) => ((Object)x).name);
			}

			public ComponentFieldAccessor<TComponent> Set(Expression<Func<TComponent, ItemDrop>> fieldExpression, ItemDrop value)
			{
				return SetCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ItemDrop x) => ((Object)x).name);
			}

			private bool SetIfChangedCore<TObj, T>(Expression<Func<TComponent, TObj>> fieldExpression, TObj valueObj, Action<ZDO, int>? remover, Action<ZDO, int, T> setter, Func<ZDO, int, T?, T> getter, Func<TObj, T> cast) where TObj : notnull where T : notnull
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				T val = cast((TObj)field.GetValue(_component));
				T arg = cast(valueObj);
				ref T reference = ref arg;
				T val2 = default(T);
				if (val2 == null)
				{
					val2 = reference;
					reference = ref val2;
				}
				if (reference.Equals(getter((ZDO)(object)_zdo, hash, val)))
				{
					return false;
				}
				if (remover != null && arg.Equals(val))
				{
					remover((ZDO)(object)_zdo, hash);
				}
				else
				{
					if (!HasFields)
					{
						SetHasFields(value: true);
					}
					setter((ZDO)(object)_zdo, hash, arg);
				}
				return true;
			}

			private bool SetIfChangedCore<T>(Expression<Func<TComponent, T>> fieldExpression, T value, Action<ZDO, int>? remover, Action<ZDO, int, T> setter, Func<ZDO, int, T?, T> getter) where T : notnull
			{
				return SetIfChangedCore(fieldExpression, value, remover, setter, getter, (T x) => x);
			}

			public bool SetIfChanged(Expression<Func<TComponent, bool>> fieldExpression, bool value)
			{
				return SetIfChangedCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				}, delegate(ZDO zdo, int hash, bool value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, bool defaultValue) => zdo.GetBool(hash, defaultValue));
			}

			public bool SetIfChanged(Expression<Func<TComponent, float>> fieldExpression, float value)
			{
				return SetIfChangedCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveFloat(hash);
				}, delegate(ZDO zdo, int hash, float value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, float defaultValue) => zdo.GetFloat(hash, defaultValue));
			}

			public bool SetIfChanged(Expression<Func<TComponent, int>> fieldExpression, int value)
			{
				return SetIfChangedCore(fieldExpression, value, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				}, delegate(ZDO zdo, int hash, int value)
				{
					zdo.Set(hash, value, false);
				}, (ZDO zdo, int hash, int defaultValue) => zdo.GetInt(hash, defaultValue));
			}

			public bool SetIfChanged(Expression<Func<TComponent, string>> fieldExpression, string value)
			{
				return SetIfChangedCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue));
			}

			public bool SetIfChanged(Expression<Func<TComponent, GameObject>> fieldExpression, GameObject value)
			{
				return SetIfChangedCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue), (GameObject x) => ((Object)x).name);
			}

			public bool SetIfChanged(Expression<Func<TComponent, ItemDrop>> fieldExpression, ItemDrop value)
			{
				return SetIfChangedCore(fieldExpression, value, null, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue), (ItemDrop x) => ((Object)x).name);
			}

			private ComponentFieldAccessor<TComponent> ResetCore<T>(Expression<Func<TComponent, T>> fieldExpression, Action<ZDO, int> remover)
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				remover((ZDO)(object)_zdo, hash);
				return this;
			}

			private ComponentFieldAccessor<TComponent> ResetCore<TObj, T>(Expression<Func<TComponent, TObj>> fieldExpression, Action<ZDO, int, T> setter, Func<TObj, T> cast) where TObj : notnull where T : notnull
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				T arg = cast((TObj)field.GetValue(_component));
				setter((ZDO)(object)_zdo, hash, arg);
				return this;
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, bool>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				});
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, float>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveFloat(hash);
				});
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, int>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash)
				{
					zdo.RemoveInt(hash);
				});
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, string>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (string x) => x);
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, GameObject>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (GameObject x) => ((Object)x).name);
			}

			public ComponentFieldAccessor<TComponent> Reset(Expression<Func<TComponent, ItemDrop>> fieldExpression)
			{
				return ResetCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ItemDrop x) => ((Object)x).name);
			}

			private bool ResetIfChangedCore<T>(Expression<Func<TComponent, T>> fieldExpression, Func<ZDO, int, bool> remover)
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				return remover((ZDO)(object)_zdo, hash);
			}

			private bool ResetIfChangedCore<TObj, T>(Expression<Func<TComponent, TObj>> fieldExpression, Action<ZDO, int, T> setter, Func<ZDO, int, T?, T> getter, Func<TObj, T> cast) where TObj : notnull where T : notnull
			{
				FieldInfo field;
				int hash = GetHash(fieldExpression, out field);
				T val = cast((TObj)field.GetValue(_component));
				if (getter((ZDO)(object)_zdo, hash, val).Equals(val))
				{
					return false;
				}
				setter((ZDO)(object)_zdo, hash, val);
				return true;
			}

			public bool ResetIfChanged(Expression<Func<TComponent, bool>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, (ZDO zdo, int hash) => zdo.RemoveInt(hash));
			}

			public bool ResetIfChanged(Expression<Func<TComponent, float>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, (ZDO zdo, int hash) => zdo.RemoveFloat(hash));
			}

			public bool ResetIfChanged(Expression<Func<TComponent, int>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, (ZDO zdo, int hash) => zdo.RemoveInt(hash));
			}

			public bool ResetIfChanged(Expression<Func<TComponent, string>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue), (string x) => x);
			}

			public bool ResetIfChanged(Expression<Func<TComponent, GameObject>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue), (GameObject x) => ((Object)x).name);
			}

			public bool ResetIfChanged(Expression<Func<TComponent, ItemDrop>> fieldExpression)
			{
				return ResetIfChangedCore(fieldExpression, delegate(ZDO zdo, int hash, string value)
				{
					zdo.Set(hash, value);
				}, (ZDO zdo, int hash, string? defaultValue) => zdo.GetString(hash, defaultValue), (ItemDrop x) => ((Object)x).name);
			}

			public bool SetOrReset(Expression<Func<TComponent, bool>> fieldExpression, bool set, bool setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}

			public bool SetOrReset(Expression<Func<TComponent, float>> fieldExpression, bool set, float setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}

			public bool SetOrReset(Expression<Func<TComponent, int>> fieldExpression, bool set, int setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}

			public bool SetOrReset(Expression<Func<TComponent, string>> fieldExpression, bool set, string setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}

			public bool SetOrReset(Expression<Func<TComponent, GameObject>> fieldExpression, bool set, GameObject setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}

			public bool SetOrReset(Expression<Func<TComponent, ItemDrop>> fieldExpression, bool set, ItemDrop setValue)
			{
				if (!set)
				{
					return ResetIfChanged(fieldExpression);
				}
				return SetIfChanged(fieldExpression, setValue);
			}
		}

		private sealed class ZDOInventory : IZDOInventory, IZDOInventoryReadOnly
		{
			private List<ItemData>? _items;

			private uint _dataRevision;

			private string? _lastData;

			public Inventory Inventory { get; private set; }

			public ExtendedZDO ZDO { get; private set; }

			public int? PickupRange { get; set; }

			public int? FeedRange { get; set; }

			private List<ItemData> Items
			{
				get
				{
					if (_items == null)
					{
						_items = Inventory.GetAllItems();
					}
					else if (_items != Inventory.GetAllItems())
					{
						throw new Exception("Assumption violated");
					}
					return _items;
				}
			}

			IList<ItemData> IZDOInventory.Items => Items;

			IReadOnlyList<ItemData> IZDOInventoryReadOnly.Items => Items;

			public ZDOInventory(ExtendedZDO zdo)
			{
				ZDO = zdo;
				_dataRevision = uint.MaxValue;
				base..ctor();
			}

			public ZDOInventory Update()
			{
				//IL_0135: Unknown result type (might be due to invalid IL or missing references)
				//IL_013f: Expected O, but got Unknown
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0165: Expected O, but got Unknown
				if (_dataRevision == ((ZDO)ZDO).DataRevision)
				{
					return this;
				}
				string items = ZDO.Vars.GetItems();
				if (_lastData == items)
				{
					return this;
				}
				ComponentFieldAccessor<Container> componentFieldAccessor = ZDO.Fields<Container>(getUnknownComponent: false);
				int @int = componentFieldAccessor.GetInt((Expression<Func<Container, int>>)((Container x) => x.m_width));
				int int2 = componentFieldAccessor.GetInt((Expression<Func<Container, int>>)((Container x) => x.m_height));
				if (Inventory == null || Inventory.GetWidth() != @int || Inventory.GetHeight() != int2)
				{
					Inventory = new Inventory(ZDO.PrefabInfo.Container.Value.Container.m_name, ZDO.PrefabInfo.Container.Value.Container.m_bkg, @int, int2);
				}
				if (string.IsNullOrEmpty(items))
				{
					Items.Clear();
				}
				else
				{
					Inventory.Load(new ZPackage(items));
				}
				_dataRevision = ((ZDO)ZDO).DataRevision;
				_lastData = items;
				return this;
			}

			public void UpdateZDO(ExtendedZDO zdo)
			{
				ZDO = zdo;
				_items = null;
				_dataRevision = 0u;
				_lastData = null;
				Update();
			}

			public void Save()
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Expected O, but got Unknown
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				ZPackage val = new ZPackage();
				Inventory.Save(val);
				uint dataRevision = ((ZDO)ZDO).DataRevision;
				string @base = val.GetBase64();
				ZDO.Vars.SetItems(@base, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.cs", 662);
				if (dataRevision != ((ZDO)ZDO).DataRevision)
				{
					(Container, Piece, PieceTable, PrefabInfo.Optional<Incinerator>, PrefabInfo.Optional<ZSyncTransform>)? container = ZDO.PrefabInfo.Container;
					if (container.HasValue)
					{
						PrefabInfo.Optional<ZSyncTransform> item = container.GetValueOrDefault().Item5;
						if (item.Value != null)
						{
							ExtendedZDO zDO = ZDO;
							((ZDO)zDO).DataRevision = ((ZDO)zDO).DataRevision + 120;
						}
					}
					ZDOMan.instance.ForceSendZDO(((ZDO)ZDO).m_uid);
				}
				_dataRevision = ((ZDO)ZDO).DataRevision;
				_lastData = @base;
			}
		}

		private ZDOID _lastId = ZDOID.None;

		private AdditionalData_? _addData;

		private static readonly int __hasFieldsHash = StringExtensionMethods.GetStableHashCode("HasFields");

		private static bool _onZdoDestroyedRegistered;

		private AdditionalData_ AddData
		{
			get
			{
				//IL_0001: 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_001d: 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)
				//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)
				if (_lastId != base.m_uid || _addData == null)
				{
					_lastId = base.m_uid;
					if (base.m_uid != ZDOID.None)
					{
						PrefabInfo prefabInfo = SharedProcessorState.GetPrefabInfo(((ZDO)this).GetPrefab());
						if ((object)prefabInfo != null)
						{
							_addData = new AdditionalData_(prefabInfo);
							goto IL_0061;
						}
					}
					_addData = AdditionalData_.Dummy;
				}
				goto IL_0061;
				IL_0061:
				return _addData;
			}
		}

		public PrefabInfo PrefabInfo => AddData.PrefabInfo;

		public IZDOInventory Inventory
		{
			get
			{
				AdditionalData_ addData = AddData;
				ZDOInventory zDOInventory = addData.Inventory;
				if (zDOInventory == null)
				{
					if (!PrefabInfo.Container.HasValue)
					{
						throw new InvalidOperationException();
					}
					ZDOInventory zDOInventory3 = (addData.Inventory = new ZDOInventory(this));
					zDOInventory = zDOInventory3;
				}
				return zDOInventory.Update();
			}
		}

		public IZDOInventoryReadOnly InventoryReadOnly
		{
			get
			{
				AdditionalData_ addData = AddData;
				ZDOInventory zDOInventory = addData.Inventory;
				if (zDOInventory == null)
				{
					if (!PrefabInfo.Container.HasValue)
					{
						throw new InvalidOperationException();
					}
					ZDOInventory zDOInventory3 = (addData.Inventory = new ZDOInventory(this));
					zDOInventory = zDOInventory3;
				}
				return zDOInventory;
			}
		}

		public bool HasFields
		{
			get
			{
				AdditionalData_ addData = AddData;
				bool? hasFields = addData.HasFields;
				bool valueOrDefault = hasFields.GetValueOrDefault();
				if (!hasFields.HasValue)
				{
					valueOrDefault = ((ZDO)this).GetBool(__hasFieldsHash, false);
					bool? hasFields2 = valueOrDefault;
					addData.HasFields = hasFields2;
					return valueOrDefault;
				}
				return valueOrDefault;
			}
		}

		public ZDOVars_ Vars => new ZDOVars_(this);

		public IReadOnlyList<Processor> Processors => AddData.Processors;

		public DateTimeOffset OwnerTimestamp { get; private set; }

		public event RecreateHandler? Recreated
		{
			add
			{
				AdditionalData_ addData = AddData;
				addData.Recreated = (RecreateHandler)Delegate.Combine(addData.Recreated, value);
			}
			remove
			{
				AdditionalData_ addData = AddData;
				addData.Recreated = (RecreateHandler)Delegate.Remove(addData.Recreated, value);
			}
		}

		public event Action<ExtendedZDO>? Destroyed
		{
			add
			{
				if (!_onZdoDestroyedRegistered)
				{
					ZDOMan instance = ZDOMan.instance;
					instance.m_onZDODestroyed = (Action<ZDO>)Delegate.Combine(instance.m_onZDODestroyed, new Action<ZDO>(OnZdoDestroyed));
					_onZdoDestroyedRegistered = true;
				}
				AdditionalData_ addData = AddData;
				addData.Destroyed = (Action<ExtendedZDO>)Delegate.Combine(addData.Destroyed, value);
			}
			remove
			{
				AdditionalData_ addData = AddData;
				addData.Destroyed = (Action<ExtendedZDO>)Delegate.Remove(addData.Destroyed, value);
			}
		}

		public void SetModAsCreator(Processor.CreatorMarkers marker = Processor.CreatorMarkers.None)
		{
			Vars.SetCreator((long)Main.PluginGuidHash | (long)((ulong)marker << 32), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.cs", 47);
		}

		public bool IsModCreator(out Processor.CreatorMarkers marker)
		{
			marker = Processor.CreatorMarkers.None;
			if ((int)Vars.GetCreator(0L) != Main.PluginGuidHash)
			{
				return false;
			}
			marker = (Processor.CreatorMarkers)((ulong)Vars.GetCreator(0L) >> 32);
			return true;
		}

		public bool IsModCreator()
		{
			Processor.CreatorMarkers marker;
			return IsModCreator(out marker);
		}

		private static void OnZdoDestroyed(ZDO zdo)
		{
			ExtendedZDO extendedZDO = (ExtendedZDO)(object)zdo;
			extendedZDO._addData?.Destroyed?.Invoke(extendedZDO);
			extendedZDO._addData = null;
		}

		private void SetHasFields()
		{
			if ((!AddData.HasFields) ?? true)
			{
				((ZDO)this).Set(__hasFieldsHash, true);
				AddData.HasFields = true;
			}
		}

		public void UnregisterProcessors(IEnumerable<Processor> processors)
		{
			AddData.Ungregister(processors);
		}

		public void UnregisterAllProcessors()
		{
			AddData.UnregisterAll();
		}

		public void ReregisterAllProcessors()
		{
			_addData?.ReregisterAll();
		}

		public void UpdateProcessorDataRevision(Processor processor)
		{
			AdditionalData_ addData = AddData;
			(addData.ProcessorDataRevisions ?? (addData.ProcessorDataRevisions = new Dictionary<Processor, (uint, uint)>()))[processor] = (((ZDO)this).DataRevision, ((ZDO)this).OwnerRevision);
		}

		public void ResetProcessorDataRevision(Processor processor)
		{
			AddData.ProcessorDataRevisions?.Remove(processor);
		}

		public bool CheckProcessorDataRevisionChanged(Processor processor)
		{
			if (AddData.ProcessorDataRevisions != null && AddData.ProcessorDataRevisions.TryGetValue(processor, out (uint, uint) value))
			{
				(uint, uint) tuple = value;
				uint dataRevision = ((ZDO)this).DataRevision;
				ushort ownerRevision = ((ZDO)this).OwnerRevision;
				if (tuple.Item1 == dataRevision && tuple.Item2 == ownerRevision)
				{
					return false;
				}
			}
			return true;
		}

		public void Destroy()
		{
			ClaimOwnershipInternal();
			ZDOMan.instance.DestroyZDO((ZDO)(object)this);
		}

		public ExtendedZDO CreateClone()
		{
			//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_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0027: 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_0044: Expected O, but got Unknown
			int prefab = ((ZDO)this).GetPrefab();
			Vector3 position = ((ZDO)this).GetPosition();
			long owner = ((ZDO)this).GetOwner();
			ZPackage val = new ZPackage();
			((ZDO)this).Serialize(val);
			ExtendedZDO obj = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(position, prefab);
			((ZDO)obj).Deserialize(new ZPackage(val.GetArray()));
			obj.SetOwnerInternal(owner);
			return obj;
		}

		public ExtendedZDO Recreate()
		{
			ExtendedZDO extendedZDO = CreateClone();
			_addData?.Recreated?.Invoke(this, extendedZDO);
			Destroy();
			return extendedZDO;
		}

		public void SetOwner(long uid)
		{
			OwnerTimestamp = DateTimeOffset.UtcNow;
			((ZDO)this).SetOwner(uid);
		}

		public void SetOwnerInternal(long uid)
		{
			OwnerTimestamp = DateTimeOffset.UtcNow;
			((ZDO)this).SetOwnerInternal(uid);
		}

		public void ClaimOwnership()
		{
			SetOwner(ZDOMan.GetSessionID());
		}

		public void ClaimOwnershipInternal()
		{
			SetOwnerInternal(ZDOMan.GetSessionID());
		}

		public void ReleaseOwnership()
		{
			SetOwner(0L);
		}

		public void ReleaseOwnershipInternal()
		{
			SetOwnerInternal(0L);
		}

		public bool IsOwnerOrUnassigned()
		{
			if (((ZDO)this).HasOwner())
			{
				return ((ZDO)this).IsOwner();
			}
			return true;
		}

		public TimeSpan GetTimeSinceSpawned()
		{
			return ZNet.instance.GetTime() - Vars.GetSpawnTime();
		}

		public ComponentFieldAccessor<TComponent> Fields<TComponent>(bool getUnknownComponent = false) where TComponent : MonoBehaviour
		{
			if (AddData != AdditionalData_.Dummy)
			{
				AdditionalData_ addData = AddData;
				return (ComponentFieldAccessor<TComponent>)(addData.ComponentFieldAccessors ?? (addData.ComponentFieldAccessors = new ConcurrentDictionary<Type, object>())).GetOrAdd(typeof(TComponent), delegate(Type key)
				{
					if (!PrefabInfo.Components.TryGetValue(key, out MonoBehaviour value) && getUnknownComponent)
					{
						value = (MonoBehaviour)(object)PrefabInfo.Prefab.GetComponentInChildren<TComponent>();
					}
					if (value == null)
					{
						throw new KeyNotFoundException();
					}
					return new ComponentFieldAccessor<TComponent>(this, (TComponent)(object)value);
				});
			}
			if (getUnknownComponent)
			{
				GameObject prefab = ZNetScene.instance.GetPrefab(((ZDO)this).GetPrefab());
				TComponent val = ((prefab != null) ? prefab.GetComponentInChildren<TComponent>() : default(TComponent));
				if (val == null)
				{
					throw new KeyNotFoundException();
				}
				return new ComponentFieldAccessor<TComponent>(this, val);
			}
			throw new InvalidOperationException();
		}
	}
	internal static class ExtensionMethods
	{
		public static ExtendedZDO? GetExtendedZDO(this ZDOMan instance, ZDOID id)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return (ExtendedZDO)(object)instance.GetZDO(id);
		}

		public static int GetActiveArea(this ZoneSystem instance)
		{
			return instance.m_activeArea - 1;
		}

		public static int GetLoadedArea(this ZoneSystem instance)
		{
			return instance.m_activeArea;
		}

		public static ConfigEntry<T> BindEx<T>(this ConfigFile config, string section, T defaultValue, string description, [CallerMemberName] string key = null)
		{
			return config.Bind<T>(section, key, defaultValue, description);
		}

		public static ConfigEntry<T> BindEx<T>(this ConfigFile config, string section, T defaultValue, string description, AcceptableValueBase? acceptableValues, [CallerMemberName] string key = null)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Expected O, but got Unknown
			return config.Bind<T>(section, key, defaultValue, new ConfigDescription(description, acceptableValues, Array.Empty<object>()));
		}

		[Conditional("DEBUG")]
		public static void DevLog(this ManualLogSource logger, string text, LogLevel logLevel = 4)
		{
		}

		[Conditional("DEBUG")]
		public static void AssertIs<T>(this ExtendedZDO zdo) where T : MonoBehaviour
		{
		}
	}
	[BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.2.2")]
	public sealed class Main : BaseUnityPlugin
	{
		private record SectorInfo(List<Peer> Peers, List<ZDO> ZDOs)
		{
			public int InverseWeight { get; set; }
		}

		private sealed class PeersEnumerable : IEnumerable<Peer>, IEnumerable
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__6 : IEnumerator<Peer>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private Peer <>2__current;

				public PeersEnumerable <>4__this;

				private IEnumerator<ZNetPeer> <>7__wrap1;

				Peer IEnumerator<Peer>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

				object IEnumerator.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

				[DebuggerHidden]
				public <GetEnumerator>d__6(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					int num = <>1__state;
					if (num == -3 || num == 2)
					{
						try
						{
						}
						finally
						{
							<>m__Finally1();
						}
					}
					<>7__wrap1 = null;
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					try
					{
						int num = <>1__state;
						PeersEnumerable peersEnumerable = <>4__this;
						switch (num)
						{
						default:
							return false;
						case 0:
							<>1__state = -1;
							if (peersEnumerable._localPeer != null)
							{
								<>2__current = new Peer(peersEnumerable._localPeer);
								<>1__state = 1;
								return true;
							}
							goto IL_0059;
						case 1:
							<>1__state = -1;
							goto IL_0059;
						case 2:
							{
								<>1__state = -3;
								break;
							}
							IL_0059:
							<>7__wrap1 = peersEnumerable._peers.GetEnumerator();
							<>1__state = -3;
							break;
						}
						if (<>7__wrap1.MoveNext())
						{
							ZNetPeer current = <>7__wrap1.Current;
							<>2__current = new Peer(current);
							<>1__state = 2;
							return true;
						}
						<>m__Finally1();
						<>7__wrap1 = null;
						return false;
					}
					catch
					{
						//try-fault
						((IDisposable)this).Dispose();
						throw;
					}
				}

				bool IEnumerator.MoveNext()
				{
					//ILSpy generated this explicit interface implementation from .override directive in MoveNext
					return this.MoveNext();
				}

				private void <>m__Finally1()
				{
					<>1__state = -1;
					if (<>7__wrap1 != null)
					{
						<>7__wrap1.Dispose();
					}
				}

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			private readonly ZNetPeer? _localPeer;

			private IReadOnlyList<ZNetPeer> _peers;

			public int Count => _peers.Count + ((_localPeer != null) ? 1 : 0);

			public PeersEnumerable(ZNetPeer? localPeer)
			{
				_localPeer = localPeer;
				_peers = Array.Empty<ZNetPeer>();
				base..ctor();
			}

			public void Update()
			{
				//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)
				if (_localPeer != null)
				{
					_localPeer.m_refPos = ZNet.instance.GetReferencePosition();
				}
				_peers = ZNet.instance.GetPeers();
			}

			[IteratorStateMachine(typeof(<GetEnumerator>d__6))]
			public IEnumerator<Peer> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__6(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private sealed class MyTerminal : Terminal
		{
			private sealed class MyConsoleEventArgs : ConsoleEventArgs
			{
				public MyConsoleEventArgs(string command, params string[] args)
					: base("", (Terminal)null)
				{
					int num = 0;
					string[] array = new string[1 + args.Length];
					array[num] = command;
					num++;
					ReadOnlySpan<string> readOnlySpan = new ReadOnlySpan<string>(args);
					readOnlySpan.CopyTo(new Span<string>(array).Slice(num, readOnlySpan.Length));
					num += readOnlySpan.Length;
					base.Args = array;
				}
			}

			protected override Terminal m_terminalInstance
			{
				get
				{
					throw new NotImplementedException();
				}
			}

			public static void ExecuteCommand(string command, params string[] args)
			{
				ConsoleCommand command2 = Terminal.commands[command];
				ConsoleEvent action = command2.GetAction();
				if (action != null)
				{
					action.Invoke((ConsoleEventArgs)(object)new MyConsoleEventArgs(command, args));
					return;
				}
				ConsoleEventFailable actionFailable = command2.GetActionFailable();
				if (actionFailable != null)
				{
					object obj = actionFailable.Invoke((ConsoleEventArgs)(object)new MyConsoleEventArgs(command, args));
					if (obj is bool && (bool)obj)
					{
						return;
					}
					throw new Exception(obj.ToString());
				}
				throw new ArgumentException("command");
			}
		}

		private sealed class DummySocket : ISocket
		{
			public ISocket Accept()
			{
				throw new NotImplementedException();
			}

			public void Close()
			{
			}

			public void Dispose()
			{
			}

			public bool Flush()
			{
				throw new NotImplementedException();
			}

			public void GetAndResetStats(out int totalSent, out int totalRecv)
			{
				throw new NotImplementedException();
			}

			public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
			{
				throw new NotImplementedException();
			}

			public int GetCurrentSendRate()
			{
				throw new NotImplementedException();
			}

			public string GetEndPointString()
			{
				throw new NotImplementedException();
			}

			public string GetHostName()
			{
				return "";
			}

			public int GetHostPort()
			{
				throw new NotImplementedException();
			}

			public int GetSendQueueSize()
			{
				throw new NotImplementedException();
			}

			public bool GotNewData()
			{
				throw new NotImplementedException();
			}

			public bool IsConnected()
			{
				return true;
			}

			public bool IsHost()
			{
				throw new NotImplementedException();
			}

			public ZPackage Recv()
			{
				throw new NotImplementedException();
			}

			public void Send(ZPackage pkg)
			{
				throw new NotImplementedException();
			}

			public void VersionMatch()
			{
				throw new NotImplementedException();
			}
		}

		[CompilerGenerated]
		private sealed class <<Start>g__CallExecute|35_0>d : IEnumerator<YieldInstruction>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private YieldInstruction <>2__current;

			public Main <>4__this;

			private PeersEnumerable <peers>5__2;

			YieldInstruction IEnumerator<YieldInstruction>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <<Start>g__CallExecute|35_0>d(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<peers>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_0041: Unknown result type (might be due to invalid IL or missing references)
				//IL_004b: Expected O, but got Unknown
				//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00b0: Expected O, but got Unknown
				//IL_0118: Unknown result type (might be due to invalid IL or missing references)
				//IL_0122: Expected O, but got Unknown
				//IL_013f: 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)
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0155: Unknown result type (might be due to invalid IL or missing references)
				//IL_015a: Unknown result type (might be due to invalid IL or missing references)
				//IL_015f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0167: Expected O, but got Unknown
				//IL_0084: Unknown result type (might be due to invalid IL or missing references)
				//IL_008e: Expected O, but got Unknown
				//IL_018f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0199: Expected O, but got Unknown
				//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00ed: Expected O, but got Unknown
				int num = <>1__state;
				Main main = <>4__this;
				ZNetPeer localPeer;
				switch (num)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					goto IL_005b;
				case 1:
					<>1__state = -1;
					goto IL_005b;
				case 2:
					<>1__state = -1;
					goto IL_005b;
				case 3:
					<>1__state = -1;
					goto IL_00c0;
				case 4:
					<>1__state = -1;
					goto IL_005b;
				case 5:
					<>1__state = -1;
					goto IL_0132;
				case 6:
					{
						<>1__state = -1;
						if (ZNet.instance != null)
						{
							try
							{
								main.Execute(<peers>5__2);
							}
							catch (OperationCanceledException)
							{
								return false;
							}
							catch (Exception ex2)
							{
								main.Logger.LogError((object)ex2);
								return false;
							}
							break;
						}
						<peers>5__2 = null;
						goto IL_005b;
					}
					IL_00c0:
					if (ZDOMan.instance == null || ZNetScene.instance == null || ZNet.World == null)
					{
						<>2__current = (YieldInstruction)new WaitForSeconds(0.2f);
						<>1__state = 3;
						return true;
					}
					if (!main.Initialize())
					{
						<>2__current = (YieldInstruction)new WaitForSeconds(5f);
						<>1__state = 4;
						return true;
					}
					localPeer = null;
					if (!ZNet.instance.IsDedicated())
					{
						goto IL_0132;
					}
					goto IL_0167;
					IL_0132:
					if (Player.m_localPlayer == null)
					{
						<>2__current = (YieldInstruction)new WaitForSeconds(0.2f);
						<>1__state = 5;
						return true;
					}
					localPeer = new ZNetPeer((ISocket)(object)new DummySocket(), true)
					{
						m_uid = ZDOMan.GetSessionID(),
						m_characterID = ((Character)Player.m_localPlayer).GetZDOID(),
						m_server = true
					};
					goto IL_0167;
					IL_005b:
					if (ZNet.instance == null)
					{
						<>2__current = (YieldInstruction)new WaitForSeconds(0.2f);
						<>1__state = 1;
						return true;
					}
					if (!ZNet.instance.IsServer())
					{
						main.Logger.LogWarning((object)"Mod should only be installed on the host");
						<>2__current = (YieldInstruction)new WaitForSeconds(5f);
						<>1__state = 2;
						return true;
					}
					goto IL_00c0;
					IL_0167:
					<peers>5__2 = new PeersEnumerable(localPeer);
					break;
				}
				<>2__current = (YieldInstruction)new WaitForSeconds(1f / main.Config.General.Frequency.Value);
				<>1__state = 6;
				return true;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		internal const string PluginName = "ServersideQoL";

		internal const string PluginGuid = "argusmagnus.ServersideQoL";

		private ModConfig? _mainConfig;

		private ModConfig? _worldConfig;

		private readonly Stopwatch _watch = new Stopwatch();

		private ulong _executeCounter;

		private uint _unfinishedProcessingInRow;

		private readonly Stack<SectorInfo> _sectorInfoPool = new Stack<SectorInfo>();

		private Dictionary<Vector2i, SectorInfo> _playerSectors = new Dictionary<Vector2i, SectorInfo>();

		private Dictionary<Vector2i, SectorInfo> _playerSectorsOld = new Dictionary<Vector2i, SectorInfo>();

		private readonly List<Processor> _unregister = new List<Processor>();

		private bool _configChanged = true;

		private readonly GameVersion ExpectedGameVersion = GameVersion.ParseGameVersion("0.221.4");

		private const uint ExpectedNetworkVersion = 35u;

		private const uint ExpectedItemDataVersion = 106u;

		private const uint ExpectedWorldVersion = 36u;

		internal const string DummyConfigSection = "Z - Dummy";

		private const string PluginVersion = "1.2.2";

		internal const string PluginInformationalVersion = "1.2.2-beta.0.13";

		internal static int PluginGuidHash { get; } = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL");


		internal static Main Instance { get; private set; } = null;


		internal static Harmony HarmonyInstance { get; } = new Harmony("argusmagnus.ServersideQoL");


		internal ManualLogSource Logger { get; } = Logger.CreateLogSource("ServersideQoL");


		internal ModConfig Config => _worldConfig ?? _mainConfig ?? (_mainConfig = new ModConfig(((BaseUnityPlugin)this).Config));

		public Main()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			Instance = this;
		}

		private void Awake()
		{
			Logger.LogWarning((object)"You are running a pre-release version: 1.2.2-beta.0.13");
			HarmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
		}

		private void Start()
		{
			((MonoBehaviour)this).StartCoroutine((IEnumerator)CallExecute());
			[IteratorStateMachine(typeof(<<Start>g__CallExecute|35_0>d))]
			IEnumerator<YieldInstruction> CallExecute()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <<Start>g__CallExecute|35_0>d(0)
				{
					<>4__this = this
				};
			}
		}

		private bool Initialize()
		{
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Expected O, but got Unknown
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Expected O, but got Unknown
			//IL_02b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ee: Unknown result type (might be due to invalid IL or missing references)
			if ((object)_mainConfig != null)
			{
				_mainConfig.ConfigFile.SettingChanged -= OnConfigChanged;
			}
			if ((object)_worldConfig != null)
			{
				_worldConfig.ConfigFile.SettingChanged -= OnConfigChanged;
			}
			_worldConfig = null;
			_executeCounter = 0uL;
			if (Config.General.ConfigPerWorld.Value)
			{
				string rootPath = ZNet.World.GetRootPath((FileSource)1);
				rootPath += ".ServersideQoL.cfg";
				if (!File.Exists(rootPath) && File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath))
				{
					File.Copy(((BaseUnityPlugin)this).Config.ConfigFilePath, rootPath);
				}
				string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileNameWithoutExtension(((BaseUnityPlugin)this).Config.ConfigFilePath));
				if (Directory.Exists(path))
				{
					string text = Path.Combine(Path.GetDirectoryName(rootPath), Path.GetFileNameWithoutExtension(rootPath));
					Directory.CreateDirectory(text);
					foreach (string item in Directory.EnumerateFiles(path))
					{
						string text2 = Path.Combine(text, Path.GetFileName(item));
						if (!File.Exists(text2))
						{
							File.Copy(item, text2);
						}
					}
				}
				Logger.LogInfo((object)"Using world config file");
				_worldConfig = new ModConfig(new ConfigFile(rootPath, false, new BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.2.2")));
			}
			Logger.LogInfo((object)FormattableString.Invariant($"Enabled: {Config.General.Enabled.Value}, DiagnosticLogs: {Config.General.DiagnosticLogs.Value}"));
			if (!Config.General.Enabled.Value)
			{
				return false;
			}
			if (Chainloader.PluginInfos.TryGetValue("org.bepinex.plugins.dedicatedserver", out var value))
			{
				Logger.LogWarning((object)("Many features are incompatible with " + value.Metadata.Name));
			}
			if (Config.General.DiagnosticLogs.Value)
			{
				ManualLogSource logger = Logger;
				string separator = Environment.NewLine + "  ";
				List<string> list = new List<string>();
				list.Add("Config:");
				list.AddRange(((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Config.ConfigFile).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> x) => FormattableString.Invariant($"[{x.Key.Section}].[{x.Key.Key}] = {x.Value.BoxedValue}")));
				logger.LogInfo((object)string.Join(separator, list.ToArray()));
			}
			bool flag = false;
			bool flag2 = false;
			if (RuntimeInformation.Instance.GameVersion != ExpectedGameVersion)
			{
				Logger.LogWarning((object)FormattableString.Invariant($"Unsupported game version: {RuntimeInformation.Instance.GameVersion}, expected: {ExpectedGameVersion}"));
				flag = true;
				flag2 |= !Config.General.IgnoreGameVersionCheck.Value;
			}
			if (RuntimeInformation.Instance.NetworkVersion != 35)
			{
				Logger.LogWarning((object)FormattableString.Invariant($"Unsupported network version: {RuntimeInformation.Instance.NetworkVersion}, expected: {35u}"));
				flag = true;
				flag2 |= !Config.General.IgnoreNetworkVersionCheck.Value;
			}
			if ((long)RuntimeInformation.Instance.ItemDataVersion != 106)
			{
				Logger.LogWarning((object)FormattableString.Invariant($"Unsupported item data version: {RuntimeInformation.Instance.ItemDataVersion}, expected: {106u}"));
				flag = true;
				flag2 |= !Config.General.IgnoreItemDataVersionCheck.Value;
			}
			if ((long)RuntimeInformation.Instance.WorldVersion != 36)
			{
				Logger.LogWarning((object)FormattableString.Invariant($"Unsupported world version: {RuntimeInformation.Instance.WorldVersion}, expected: {36u}"));
				flag = true;
				flag2 |= !Config.General.IgnoreWorldVersionCheck.Value;
			}
			if (flag)
			{
				if (flag2)
				{
					Logger.LogError((object)"Version checks failed. Mod execution is stopped");
					return false;
				}
				Logger.LogError((object)"Version checks failed, but you chose to ignore the checks (config). Continuing...");
			}
			return true;
		}

		private void OnConfigChanged(object sender, SettingChangedEventArgs e)
		{
			_configChanged = true;
			if (Config.General.DiagnosticLogs.Value || e.ChangedSetting == Config.General.DiagnosticLogs)
			{
				Logger.LogInfo((object)$"Config changed: [{e.ChangedSetting.Definition.Section}].[{e.ChangedSetting.Definition.Key}] = {e.ChangedSetting.BoxedValue}");
			}
			if (e.ChangedSetting == Config.General.DiagnosticLogs && Config.General.DiagnosticLogs.Value)
			{
				ManualLogSource logger = Logger;
				string separator = Environment.NewLine + "  ";
				List<string> list = new List<string>();
				list.Add("Config:");
				list.AddRange(((IEnumerable<KeyValuePair<ConfigDefinition, ConfigEntryBase>>)Config.ConfigFile).Select((KeyValuePair<ConfigDefinition, ConfigEntryBase> x) => FormattableString.Invariant($"[{x.Key.Section}].[{x.Key.Key}] = {x.Value.BoxedValue}")));
				logger.LogInfo((object)string.Join(separator, list.ToArray()));
			}
		}

		private void Execute(PeersEnumerable peers)
		{
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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)
			//IL_020d: Unknown result type (might be due to invalid IL or missing references)
			//IL_020f: 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)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: 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_0239: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_03cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_04fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_03f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_0469: Unknown result type (might be due to invalid IL or missing references)
			//IL_0436: Unknown result type (might be due to invalid IL or missing references)
			//IL_04c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_05d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_05de: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0715: Unknown result type (might be due to invalid IL or missing references)
			//IL_0717: Unknown result type (might be due to invalid IL or missing references)
			//IL_0620: Unknown result type (might be due to invalid IL or missing references)
			//IL_0625: Unknown result type (might be due to invalid IL or missing references)
			//IL_062c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0633: Unknown result type (might be due to invalid IL or missing references)
			//IL_063d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0644: Unknown result type (might be due to invalid IL or missing references)
			//IL_0768: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a85: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a8d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b06: Unknown result type (might be due to invalid IL or missing references)
			//IL_0860: Unknown result type (might be due to invalid IL or missing references)
			_executeCounter++;
			if (_configChanged)
			{
				_configChanged = false;
				if (Config.GlobalsKeys.SetGlobalKeysFromConfig.Value)
				{
					ZoneSystem.instance.ResetWorldKeys();
				}
				if (Config.WorldModifiers.SetPresetFromConfig.Value)
				{
					try
					{
						MyTerminal.ExecuteCommand("setworldpreset", FormattableString.Invariant($"{Config.WorldModifiers.Preset.Value}"));
					}
					catch (Exception ex)
					{
						Logger.LogError((object)ex);
					}
				}
				if (Config.WorldModifiers.SetModifiersFromConfig.Value)
				{
					foreach (var (val, val2) in Config.WorldModifiers.Modifiers.Select<KeyValuePair<WorldModifiers, ConfigEntry<WorldModifierOption>>, (WorldModifiers, WorldModifierOption)>((KeyValuePair<WorldModifiers, ConfigEntry<WorldModifierOption>> x) => (x.Key, x.Value.Value)))
					{
						try
						{
							MyTerminal.ExecuteCommand("setworldmodifier", FormattableString.Invariant($"{val}"), FormattableString.Invariant($"{val2}"));
						}
						catch (Exception ex2)
						{
							Logger.LogError((object)ex2);
						}
					}
				}
				if (Config.GlobalsKeys.SetGlobalKeysFromConfig.Value)
				{
					foreach (KeyValuePair<GlobalKeys, ConfigEntryBase> item3 in Config.GlobalsKeys.KeyConfigs.Where<KeyValuePair<GlobalKeys, ConfigEntryBase>>((KeyValuePair<GlobalKeys, ConfigEntryBase> x) => !object.Equals(x.Value.BoxedValue, x.Value.DefaultValue)))
					{
						item3.Deconstruct(out var key, out var value);
						GlobalKeys val3 = key;
						ConfigEntryBase val4 = value;
						object boxedValue = val4.BoxedValue;
						if (boxedValue is bool)
						{
							if ((bool)boxedValue)
							{
								ZoneSystem.instance.SetGlobalKey(val3);
							}
							else
							{
								ZoneSystem.instance.RemoveGlobalKey(val3);
							}
							continue;
						}
						float num;
						try
						{
							num = (float)Convert.ChangeType(val4.BoxedValue, typeof(float));
						}
						catch (Exception ex3)
						{
							Logger.LogError((object)ex3);
							continue;
						}
						ZoneSystem.instance.SetGlobalKey(val3, num);
					}
				}
				foreach (Processor defaultProcessor in Processor.DefaultProcessors)
				{
					defaultProcessor.Initialize(_executeCounter == 1);
				}
				if (_executeCounter == 1)
				{
					Config.ConfigFile.SettingChanged -= OnConfigChanged;
					Config.ConfigFile.SettingChanged += OnConfigChanged;
					return;
				}
				{
					foreach (ExtendedZDO item4 in ZDOMan.instance.GetObjectsByID().Values.Cast<ExtendedZDO>())
					{
						item4.ReregisterAllProcessors();
					}
					return;
				}
			}
			_watch.Restart();
			peers.Update();
			SharedProcessorState.CleanUp(peers);
			if (peers.Count == 0)
			{
				return;
			}
			Dictionary<Vector2i, SectorInfo> playerSectorsOld = _playerSectorsOld;
			Dictionary<Vector2i, SectorInfo> playerSectors = _playerSectors;
			_playerSectors = playerSectorsOld;
			_playerSectorsOld = playerSectors;
			Vector2i key2 = default(Vector2i);
			foreach (Peer peer in peers)
			{
				Vector2i zone = ZoneSystem.GetZone(peer.m_refPos);
				for (int i = zone.x - Config.General.ZonesAroundPlayers.Value; i <= zone.x + Config.General.ZonesAroundPlayers.Value; i++)
				{
					for (int j = zone.y - Config.General.ZonesAroundPlayers.Value; j <= zone.y + Config.General.ZonesAroundPlayers.Value; j++)
					{
						((Vector2i)(ref key2))..ctor(i, j);
						if (_playerSectorsOld.Remove(key2, out SectorInfo value2))
						{
							_playerSectors.Add(key2, value2);
							value2.InverseWeight = 0;
							value2.Peers.Clear();
							value2.Peers.Add(peer);
							continue;
						}
						if (_playerSectors.TryGetValue(key2, out value2))
						{
							value2.Peers.Add(peer);
							continue;
						}
						if (_sectorInfoPool.TryPop(out value2))
						{
							value2.Peers.Add(peer);
						}
						else
						{
							value2 = new SectorInfo(new List<Peer>(1) { peer }, new List<ZDO>());
						}
						_playerSectors.Add(key2, value2);
					}
				}
			}
			foreach (SectorInfo value3 in _playerSectorsOld.Values)
			{
				value3.InverseWeight = 0;
				value3.Peers.Clear();
				value3.ZDOs.Clear();
				_sectorInfoPool.Push(value3);
			}
			_playerSectorsOld.Clear();
			IEnumerable<KeyValuePair<Vector2i, SectorInfo>> enumerable = _playerSectors.AsEnumerable();
			if (_unfinishedProcessingInRow > 10)
			{
				foreach (Peer peer2 in peers)
				{
					Vector2i zone2 = ZoneSystem.GetZone(peer2.m_refPos);
					foreach (var item5 in _playerSectors.Select<KeyValuePair<Vector2i, SectorInfo>, (Vector2i, SectorInfo)>((KeyValuePair<Vector2i, SectorInfo> x) => (x.Key, x.Value)))
					{
						Vector2i item = item5.Item1;
						SectorInfo item2 = item5.Item2;
						int num2 = item.x - zone2.x;
						int num3 = item.y - zone2.y;
						item2.InverseWeight += num2 * num2 + num3 * num3;
					}
				}
				enumerable = enumerable.OrderBy((KeyValuePair<Vector2i, SectorInfo> x) => x.Value.InverseWeight);
			}
			foreach (Processor defaultProcessor2 in Processor.DefaultProcessors)
			{
				defaultProcessor2.PreProcess(peers);
			}
			int num4 = 0;
			int num5 = 0;
			int num6 = 0;
			foreach (var (val6, sectorInfo2) in enumerable)
			{
				if (_watch.ElapsedMilliseconds >= Config.General.MaxProcessingTime.Value)
				{
					break;
				}
				num4++;
				if ((object)sectorInfo2 != null)
				{
					List<ZDO> zDOs = sectorInfo2.ZDOs;
					if (zDOs != null && zDOs.Count == 0)
					{
						ZDOMan.instance.FindSectorObjects(val6, 0, 0, sectorInfo2.ZDOs, (List<ZDO>)null);
					}
				}
				num6 += sectorInfo2.ZDOs.Count;
				while ((object)sectorInfo2 != null)
				{
					List<ZDO> zDOs = sectorInfo2.ZDOs;
					if (zDOs == null || zDOs.Count <= 0 || _watch.ElapsedMilliseconds >= Config.General.MaxProcessingTime.Value)
					{
						break;
					}
					num5++;
					ExtendedZDO extendedZDO = (ExtendedZDO)(object)sectorInfo2.ZDOs[sectorInfo2.ZDOs.Count - 1];
					sectorInfo2.ZDOs.RemoveAt(sectorInfo2.ZDOs.Count - 1);
					if (!((ZDO)extendedZDO).IsValid())
					{
						continue;
					}
					if (extendedZDO.Processors.Count > 1)
					{
						Processor claimedExclusiveBy = null;
						foreach (Processor processor in extendedZDO.Processors)
						{
							if (processor.ClaimExclusive(extendedZDO))
							{
								if (claimedExclusiveBy == null)
								{
									claimedExclusiveBy = processor;
								}
								else if (Config.General.DiagnosticLogs.Value)
								{
									Logger.LogError((object)FormattableString.Invariant($"ZDO {((ZDO)extendedZDO).m_uid} claimed exclusive by {processor.GetType().Name} while already claimed by {claimedExclusiveBy.GetType().Name}"));
								}
							}
						}
						if (claimedExclusiveBy != null)
						{
							extendedZDO.UnregisterProcessors(extendedZDO.Processors.Where((Processor x) => x != claimedExclusiveBy));
						}
					}
					bool flag = false;
					bool flag2 = false;
					_unregister.Clear();
					foreach (Processor processor2 in extendedZDO.Processors)
					{
						processor2.Process(extendedZDO, sectorInfo2.Peers);
						if (processor2.UnregisterZdoProcessor)
						{
							_unregister.Add(processor2);
						}
						if (flag = processor2.DestroyZdo)
						{
							extendedZDO.Destroy();
							break;
						}
						flag2 = flag2 || processor2.RecreateZdo;
					}
					if (!flag && flag2)
					{
						extendedZDO.Recreate();
					}
					else if (!flag && _unregister.Count > 0)
					{
						extendedZDO.UnregisterProcessors(_unregister);
					}
				}
			}
			foreach (Processor defaultProcessor3 in Processor.DefaultProcessors)
			{
				defaultProcessor3.PostProcess();
			}
			if (num4 < _playerSectors.Count || num5 < num6)
			{
				_unfinishedProcessingInRow++;
			}
			else
			{
				_unfinishedProcessingInRow = 0u;
			}
			_watch.Stop();
			if (Config.General.DiagnosticLogs.Value)
			{
				LogLevel val7 = (LogLevel)((_unfinishedProcessingInRow == 0) ? 32 : 16);
				Logger.Log(val7, (object)FormattableString.Invariant(FormattableStringFactory.Create("{0} took {1} ms to process {2} of {3} ZDOs in {4} of {5} zones. Incomplete runs in row: {6}", "Execute", _watch.ElapsedMilliseconds, num5, num6, num4, _playerSectors.Count, _unfinishedProcessingInRow)));
				Logger.Log(val7, (object)FormattableString.Invariant(FormattableStringFactory.Create("Processing Time: {0}", string.Join(", ", from x in Processor.DefaultProcessors
					where x.ProcessingTime.Ticks > 0
					orderby x.ProcessingTime.Ticks descending
					select FormattableString.Invariant($"{x.GetType().Name}: {x.ProcessingTime.TotalMilliseconds}ms")))));
			}
		}
	}
	public enum MessageTypes
	{
		None,
		TopLeftNear,
		TopLeftFar,
		CenterNear,
		CenterFar,
		InWorld
	}
	internal sealed record ModConfig(ConfigFile ConfigFile)
	{
		public sealed class GeneralConfig
		{
			public ConfigEntry<bool> Enabled { get; } = cfg.BindEx(section, defaultValue: true, "Enables/disables the entire mod", "Enabled");


			public ConfigEntry<bool> ConfigPerWorld { get; } = cfg.BindEx(section, defaultValue: false, "Use one config file per world. The file is saved next to the world file", "ConfigPerWorld");


			public ConfigEntry<bool> InWorldConfigRoom { get; } = cfg.BindEx(section, defaultValue: false, "True to generate an in-world room which admins can enter to configure this mod by editing signs. A portal is placed at the start location", "InWorldConfigRoom");


			public ConfigEntry<float> FarMessageRange { get; } = cfg.BindEx(section, 64f, $"Max distance a player can have to a modified object to receive messages of type {MessageTypes.TopLeftFar} or {MessageTypes.CenterFar}", "FarMessageRange");


			public ConfigEntry<bool> DiagnosticLogs { get; } = cfg.BindEx(section, defaultValue: false, "Enables/disables diagnostic logs", "DiagnosticLogs");


			public ConfigEntry<float> Frequency { get; } = cfg.BindEx(section, 5f, "How many times per second the mod processes the world", (AcceptableValueBase?)(object)new AcceptableValueRange<float>(0f, float.PositiveInfinity), "Frequency");


			public ConfigEntry<int> MaxProcessingTime { get; } = cfg.BindEx(section, 20, "Max processing time (in ms) per update", "MaxProcessingTime");


			public ConfigEntry<int> ZonesAroundPlayers { get; } = cfg.BindEx(section, ZoneSystem.instance.GetActiveArea(), "Zones to process around each player", "ZonesAroundPlayers");


			public ConfigEntry<float> MinPlayerDistance { get; } = cfg.BindEx(section, 4f, "Min distance all players must have to a ZDO for it to be modified", "MinPlayerDistance");


			public ConfigEntry<bool> IgnoreGameVersionCheck { get; } = cfg.BindEx(section, defaultValue: true, "True to ignore the game version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", "IgnoreGameVersionCheck");


			public ConfigEntry<bool> IgnoreNetworkVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the network version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", "IgnoreNetworkVersionCheck");


			public ConfigEntry<bool> IgnoreItemDataVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the item data version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", "IgnoreItemDataVersionCheck");


			public ConfigEntry<bool> IgnoreWorldVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the world version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", "IgnoreWorldVersionCheck");


			public GeneralConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class SignsConfig
		{
			public ConfigEntry<string> DefaultColor { get; } = cfg.BindEx(section, "", "Default color for signs. Can be a color name or hex code (e.g. #FF0000 for red)", "DefaultColor");


			public ConfigEntry<bool> TimeSigns { get; } = cfg.BindEx(section, defaultValue: false, FormattableString.Invariant($"True to update sign texts which contain time emojis (any of {string.Concat(SignProcessor.ClockEmojis)}) with the in-game time"), "TimeSigns");


			public SignsConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class MapTableConfig
		{
			public ConfigEntry<bool> AutoUpdatePortals { get; } = cfg.BindEx(section, defaultValue: false, "True to update map tables with portal pins", "AutoUpdatePortals");


			public ConfigEntry<string> AutoUpdatePortalsExclude { get; } = cfg.BindEx(section, "", "Portals with a tag that matches this filter are not added to map tables", "AutoUpdatePortalsExclude");


			public ConfigEntry<string> AutoUpdatePortalsInclude { get; } = cfg.BindEx(section, "*", "Only portals with a tag that matches this filter are added to map tables", "AutoUpdatePortalsInclude");


			public ConfigEntry<bool> AutoUpdateShips { get; } = cfg.BindEx(section, defaultValue: false, "True to update map tables with ship pins", "AutoUpdateShips");


			public ConfigEntry<MessageTypes> UpdatedMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of message to show when a map table is updated", (AcceptableValueBase?)(object)AcceptableEnum<MessageTypes>.Default, "UpdatedMessageType");


			public MapTableConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class TamesConfig
		{
			public ConfigEntry<bool> MakeCommandable { get; } = cfg.BindEx(section, defaultValue: false, "True to make all tames commandable (like wolves)", "MakeCommandable");


			public ConfigEntry<MessageTypes> TamingProgressMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of taming progress messages to show", (AcceptableValueBase?)(object)AcceptableEnum<MessageTypes>.Default, "TamingProgressMessageType");


			public ConfigEntry<MessageTypes> GrowingProgressMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of growing progress messages to show", (AcceptableValueBase?)(object)AcceptableEnum<MessageTypes>.Default, "GrowingProgressMessageType");


			public ConfigEntry<float> FedDurationMultiplier { get; } = cfg.BindEx(section, 1f, FormattableString.Invariant($"Multiply the time tames stay fed after they have eaten by this factor. {float.PositiveInfinity} to keep them fed indefinitely"), "FedDurationMultiplier");


			public ConfigEntry<float> TamingTimeMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the time it takes to tame a tameable creature by this factor.\r\nE.g. a value of 0.5 means that the taming time is halved.", "TamingTimeMultiplier");


			public ConfigEntry<float> PotionTamingBoostMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the taming boost from the animal whispers potion by this factor.\r\nE.g. a value of 2 means that the effect of the potion is doubled and the resulting taming time is reduced by a factor of 4 per player.", "PotionTamingBoostMultiplier");


			public ConfigEntry<bool> TeleportFollow { get; } = cfg.BindEx(section, defaultValue: false, "True to teleport following tames to the players location if the player gets too far away from them", "TeleportFollow");


			public ConfigEntry<bool> TakeIntoDungeons { get; } = cfg.BindEx(section, defaultValue: false, "True to take following tames into (and out of) dungeons with you", "TakeIntoDungeons");


			public TamesConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class CreaturesConfig
		{
			[Flags]
			public enum ShowHigherLevelAuraOptions
			{
				Never = 0,
				Wild = 1,
				Tamed = 2
			}

			public ConfigEntry<bool> ShowHigherLevelStars { get; } = cfg.BindEx(section, defaultValue: false, "True to show stars for higher level creatures (> 2 stars)", "ShowHigherLevelStars");


			public ConfigEntry<ShowHigherLevelAuraOptions> ShowHigherLevelAura { get; } = cfg.BindEx(section, ShowHigherLevelAuraOptions.Never, "Show an aura for higher level creatures (> 2 stars)", (AcceptableValueBase?)(object)AcceptableEnum<ShowHigherLevelAuraOptions>.Default, "ShowHigherLevelAura");


			public ConfigEntry<int> MaxLevelIncrease { get; } = cfg.BindEx(section, 0, "Amount the max level of creatures is incremented throughout the world.\r\nThe level up chance increases with the max level.\r\nExample: if this value is set to 2, a creature will spawn with 4 stars with the same probability as it would spawn with 2 stars without this setting.", "MaxLevelIncrease");


			public ConfigEntry<int> MaxLevelIncreasePerDefeatedBoss { get; } = cfg.BindEx(section, 0, "Amount the max level of creatures is incremented per defeated boss.\r\nThe respective boss's biome and previous biomes are affected and the level up chance increases with the max level.\r\nExample: If this value is set to 1 and Eikthyr and the Elder is defeated, the max creature level in the Black Forest will be raised by 1 and in the Meadows by 2.", "MaxLevelIncreasePerDefeatedBoss");


			public ConfigEntry<Biome> TreatOceanAs { get; } = cfg.BindEx<Biome>(section, (Biome)8, "Biome to treat the ocean as for the purpose of leveling up creatures", (AcceptableValueBase?)(object)new AcceptableEnum<Biome>(AcceptableEnum<Biome>.Default.AcceptableValues.Where((Biome x) => (int)x != 256)), "TreatOceanAs");


			public ConfigEntry<bool> LevelUpBosses { get; } = cfg.BindEx(section, defaultValue: false, "True to also level up bosses", "LevelUpBosses");


			public ConfigEntry<float> RespawnOneTimeSpawnsAfter { get; } = cfg.BindEx(section, 0f, "Time after one-time spawns are respawned in minutes", "RespawnOneTimeSpawnsAfter");


			public CreaturesConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class FireplacesConfig
		{
			public enum IgnoreRainOptions
			{
				Never,
				Always,
				InsideShield
			}

			public ConfigEntry<bool> MakeToggleable { get; } = cfg.BindEx(section, defaultValue: false, "True to make all fireplaces (including torches, braziers, etc.) toggleable", "MakeToggleable");


			public ConfigEntry<bool> InfiniteFuel { get; } = cfg.BindEx(section, defaultValue: false, "True to make all fireplaces have infinite fuel", "InfiniteFuel");


			public ConfigEntry<IgnoreRainOptions> IgnoreRain { get; } = cfg.BindEx(section, IgnoreRainOptions.Never, "Options to make all fireplaces ignore rain", (AcceptableValueBase?)(object)AcceptableEnum<IgnoreRainOptions>.Default, "IgnoreRain");


			public FireplacesConfig(ConfigFile cfg, string section)
			{
			}
		}

		public sealed class ContainersConfig
		{
			public enum ObliteratorItemTeleporterOptions
			{
				Disabled = 0,
				Enabled = 1,
				EnabledAllItems = 2,
				[Obsolete]
				False = 0,
				[Obsolete]
				True = 1
			}

			[Flags]
			public enum SignOptions
			{
				None = 0,
				Left = 1,
				Right = 2,
				Front = 4,
				Back = 8,
				TopLongitudinal = 0x10,
				TopLateral = 0x20
			}

			private const string ChestSignItemNamesFileName = "ChestSignItemNames.yml";

			private const string DefaultPlaceholderString = "•";

			public ConfigEntry<bool> AutoSort { get; }

			public ConfigEntry<MessageTypes> SortedMessageType { get; }

			public ConfigEntry<bool> AutoPickup { get; }

			public ConfigEntry<float> AutoPickupRange { get; }

			public ConfigEntry<int> AutoPickupMaxRange { get; }

			public ConfigEntry<float> AutoPickupMinPlayerDistance { get; }

			public ConfigEntry<bool> AutoPickupExcludeFodder { get; }

			public ConfigEntry<bool> AutoPickupRequestOwnership { get; }

			public ConfigEntry<MessageTypes> PickedUpMessageType { get; }

			public ConfigEntry<string> ChestSignsDefaultText { get; }

			public ConfigEntry<string> ChestSignsContentListPlaceholder { get; }

			public ConfigEntry<int> ChestSignsContentListMaxCount { get; }

			public ConfigEntry<string> ChestSignsContentListSeparator { get; }

			public ConfigEntry<string> ChestSignsContentListNameRest { get; }

			public ConfigEntry<string> ChestSignsContentListEntryFormat { get; }

			public ConfigEntry<SignOptions> WoodChestSigns { get; }

			public ConfigEntry<SignOptions> ReinforcedChestSigns { get; }

			public ConfigEntry<SignOptions> BlackmetalChestSigns { get; }

			public ConfigEntry<SignOptions> ObliteratorSigns { get; }

			public ConfigEntry<ObliteratorItemTeleporterOptions> ObliteratorItemTeleporter { get; }

			public ConfigEntry<MessageTypes> ObliteratorItemTeleporterMessageType { get; }

			public IReadOnlyDictionary<int, ConfigEntry<string>> ContainerSizes { get; }

			public IReadOnlyDictionary<string, string> ItemNames { get; }

			public ContainersConfig(ConfigFile cfg, string section)
			{
				ConfigFile cfg2 = cfg;
				string section2 = section;
				AutoSort = cfg2.BindEx(section2, defaultValue: false, "True to auto sort container inventories", "AutoSort");
				SortedMessageType = cfg2.BindEx(section2, MessageTypes.None, "Type of message to show when a container was sorted", (AcceptableValueBase?)(object)AcceptableEnum<MessageTypes>.Default, "SortedMessageType");
				AutoPickup = cfg2.BindEx(section2, defaultValue: false, "True to automatically put dropped items into containers if they already contain said item", "AutoPickup");
				AutoPickupRange = cfg2.BindEx(section2, 64f, "Required proximity of a container to a dropped item to be considered as auto pickup target. Can be overridden per chest by putting '\ud83e\uddf2<Range>' on a chest sign", "AutoPickupRange");
				AutoPickupMaxRange = cfg2

Valheim.ServersideQoL.YamlDotNet.dll

Decompiled 13 hours ago
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.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.CodeAnalysis;
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: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("YamlDotNet")]
[assembly: AssemblyDescription("The YamlDotNet library.")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("YamlDotNet")]
[assembly: AssemblyCopyright("Copyright (c) Antoine Aubry and contributors 2008 - 2019")]
[assembly: AssemblyTrademark("")]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("YamlDotNet.Test, PublicKey=002400000480000094000000060200000024000052534131000400000100010065e52a453dde5c5b4be5bbe2205755727fce80244b79b894faf8793d80f7db9a96d360b51c220782db32aacee4cb5b8a91bee33aeec700e1f21895c4baadef501eeeac609220d1651603b378173811ee5bb6a002df973d38821bd2fef820c00c174a69faec326a1983b570f07ec66147026b9c8753465de3a8d0c44b613b02af")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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]
	[Microsoft.CodeAnalysis.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 YamlDotNet
{
	internal sealed class CultureInfoAdapter : CultureInfo
	{
		private readonly IFormatProvider provider;

		public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider)
			: base(baseCulture.Name)
		{
			this.provider = provider;
		}

		public override object GetFormat(Type? formatType)
		{
			return provider.GetFormat(formatType);
		}
	}
	internal static class Polyfills
	{
	}
	internal static class PropertyInfoExtensions
	{
		public static object? ReadValue(this PropertyInfo property, object target)
		{
			return property.GetValue(target, null);
		}
	}
	internal static class ReflectionExtensions
	{
		private static readonly Func<PropertyInfo, bool> IsInstance = (PropertyInfo property) => !(property.GetMethod ?? property.SetMethod).IsStatic;

		private static readonly Func<PropertyInfo, bool> IsInstancePublic = (PropertyInfo property) => IsInstance(property) && (property.GetMethod ?? property.SetMethod).IsPublic;

		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;
		}

		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((Type t, object context) => IsGenericDefinitionOfType(t, context), openGenericType).FirstOrDefault();
			static bool IsGenericDefinitionOfType(Type t, 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((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;
		}

		public static PropertyInfo? GetPublicProperty(this Type type, string name)
		{
			string name2 = name;
			return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).FirstOrDefault((PropertyInfo p) => p.Name == name2);
		}

		public static FieldInfo? GetPublicStaticField(this Type type, string name)
		{
			return type.GetRuntimeField(name);
		}

		public static IEnumerable<PropertyInfo> GetProperties(this Type type, bool includeNonPublic)
		{
			Func<PropertyInfo, bool> predicate = (includeNonPublic ? IsInstance : IsInstancePublic);
			if (!type.IsInterface())
			{
				return type.GetRuntimeProperties().Where(predicate);
			}
			return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetRuntimeProperties().Where(predicate));
		}

		public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)
		{
			return type.GetProperties(includeNonPublic: false);
		}

		public static IEnumerable<FieldInfo> GetPublicFields(this Type type)
		{
			return from f in type.GetRuntimeFields()
				where !f.IsStatic && f.IsPublic
				select f;
		}

		public static IEnumerable<MethodInfo> 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)
		{
			string name2 = name;
			return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => !m.IsPublic && m.IsStatic && m.Name.Equals(name2)) ?? throw new MissingMethodException("Expected to find a method named '" + name2 + "' in '" + type.FullName + "'.");
		}

		public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes)
		{
			string name2 = name;
			Type[] parameterTypes2 = parameterTypes;
			return type.GetRuntimeMethods().FirstOrDefault(delegate(MethodInfo m)
			{
				if (m.IsPublic && m.IsStatic && m.Name.Equals(name2))
				{
					ParameterInfo[] parameters = m.GetParameters();
					if (parameters.Length == parameterTypes2.Length)
					{
						return parameters.Zip(parameterTypes2, (ParameterInfo pi, Type pt) => pi.ParameterType == pt).All((bool r) => r);
					}
					return false;
				}
				return false;
			});
		}

		public static MethodInfo? GetPublicInstanceMethod(this Type type, string name)
		{
			string name2 = name;
			return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => m.IsPublic && !m.IsStatic && m.Name.Equals(name2));
		}

		public static MethodInfo? GetGetMethod(this PropertyInfo property, bool nonPublic)
		{
			MethodInfo methodInfo = property.GetMethod;
			if (!nonPublic && !methodInfo.IsPublic)
			{
				methodInfo = null;
			}
			return methodInfo;
		}

		public static MethodInfo? GetSetMethod(this PropertyInfo property)
		{
			return property.SetMethod;
		}

		public static IEnumerable<Type> 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<TAttribute>(this PropertyInfo member)
		{
			return Attribute.GetCustomAttributes(member, typeof(TAttribute), inherit: true);
		}

		public static bool AcceptsNull(this MemberInfo member)
		{
			object obj = member.DeclaringType.GetCustomAttributes(inherit: true).FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableContextAttribute");
			int num = 0;
			if (obj != null)
			{
				num = (byte)obj.GetType().GetProperty("Flag").GetValue(obj);
			}
			object obj2 = member.GetCustomAttributes(inherit: true).FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableAttribute");
			if (!((byte[])((obj2?.GetType())?.GetProperty("NullableFlags")).GetValue(obj2)).Any((byte x) => x == 2))
			{
				return num == 2;
			}
			return true;
		}
	}
	internal static class StandardRegexOptions
	{
		public const RegexOptions Compiled = RegexOptions.Compiled;
	}
}
namespace YamlDotNet.Serialization
{
	public abstract class BuilderSkeleton<TBuilder> where TBuilder : BuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal INamingConvention enumNamingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly YamlAttributeOverrides overrides;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> 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<Nothing, IYamlTypeConverter>
			{
				{
					typeof(YamlDotNet.Serialization.Converters.GuidConverter),
					(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
				},
				{
					typeof(SystemTypeConverter),
					(Nothing _) => new SystemTypeConverter()
				}
			};
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			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<TClass>(Expression<Func<TClass, object>> 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<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			IYamlTypeConverter typeConverter2 = typeConverter;
			if (typeConverter2 == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory;
			if (typeConverterFactory2 == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<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<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<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<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	public delegate TComponent WrapperFactory<TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase;
	public delegate TComponent WrapperFactory<TArgument, TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase;
	[Flags]
	public enum DefaultValuesHandling
	{
		Preserve = 0,
		OmitNull = 1,
		OmitDefaults = 2,
		OmitEmptyCollections = 4
	}
	public 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<T>(string input)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize<T>(input2);
		}

		public T Deserialize<T>(TextReader input)
		{
			return Deserialize<T>(new Parser(input));
		}

		public T Deserialize<T>(IParser parser)
		{
			return (T)Deserialize(parser, typeof(T));
		}

		public object? Deserialize(string input)
		{
			return Deserialize<object>(input);
		}

		public object? Deserialize(TextReader input)
		{
			return Deserialize<object>(input);
		}

		public object? Deserialize(IParser parser)
		{
			return Deserialize<object>(parser);
		}

		public object? Deserialize(string input, Type type)
		{
			using StringReader input2 = new StringReader(input);
			return Deserialize(input2, type);
		}

		public object? Deserialize(TextReader input, Type type)
		{
			return Deserialize(new Parser(input), type);
		}

		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<YamlDotNet.Core.Events.StreamStart>(out @event);
			YamlDotNet.Core.Events.DocumentStart event2;
			bool flag2 = parser.TryConsume<YamlDotNet.Core.Events.DocumentStart>(out event2);
			object result = null;
			if (!parser.Accept<YamlDotNet.Core.Events.DocumentEnd>(out var _) && !parser.Accept<YamlDotNet.Core.Events.StreamEnd>(out var _))
			{
				using SerializerState serializerState = new SerializerState();
				result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer);
				serializerState.OnDeserialization();
			}
			if (flag2)
			{
				parser.Consume<YamlDotNet.Core.Events.DocumentEnd>();
			}
			if (flag)
			{
				parser.Consume<YamlDotNet.Core.Events.StreamEnd>();
			}
			return result;
		}
	}
	public sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder>
	{
		private Lazy<IObjectFactory> objectFactory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly Dictionary<Type, Type> 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<Type, Type>();
			objectFactory = new Lazy<IObjectFactory>(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true);
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					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<Nothing, INodeDeserializer>
			{
				{
					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<Nothing, INodeTypeResolver>
			{
				{
					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)
		{
			IObjectFactory objectFactory2 = objectFactory;
			if (objectFactory2 == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			this.objectFactory = new Lazy<IObjectFactory>(() => objectFactory2, isThreadSafe: true);
			return this;
		}

		public DeserializerBuilder WithObjectFactory(Func<Type, object> objectFactory)
		{
			if (objectFactory == null)
			{
				throw new ArgumentNullException("objectFactory");
			}
			return WithObjectFactory(new LambdaObjectFactory(objectFactory));
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer)
		{
			return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			INodeDeserializer nodeDeserializer2 = nodeDeserializer;
			if (nodeDeserializer2 == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2));
			return this;
		}

		public DeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory;
			if (nodeDeserializerFactory2 == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped)));
			return this;
		}

		public DeserializerBuilder WithoutNodeDeserializer<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<ITypeDiscriminatingNodeDeserializerOptions> 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<INodeDeserializer> s)
			{
				s.Before<DictionaryNodeDeserializer>();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver;
			if (nodeTypeResolver2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2));
			return this;
		}

		public DeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory;
			if (nodeTypeResolverFactory2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(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<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 Type 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<TInterface, TConcrete>() where TConcrete : TInterface
		{
			Type typeFromHandle = typeof(TInterface);
			Type typeFromHandle2 = typeof(TConcrete);
			if (!typeFromHandle.IsAssignableFrom(typeFromHandle2))
			{
				throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'.");
			}
			if (!typeMappings.TryAdd(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()));
		}
	}
	public sealed class EmissionPhaseObjectGraphVisitorArgs
	{
		private readonly IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors;

		public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; }

		public IEventEmitter EventEmitter { get; private set; }

		public ObjectSerializer NestedObjectSerializer { get; private set; }

		public IEnumerable<IYamlTypeConverter> TypeConverters { get; private set; }

		public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<Nothing>> preProcessingPhaseVisitors, IEnumerable<IYamlTypeConverter> 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<T>() where T : IObjectGraphVisitor<Nothing>
		{
			return preProcessingPhaseVisitors.OfType<T>().Single();
		}
	}
	public abstract class EventInfo
	{
		public IObjectDescriptor Source { get; }

		protected EventInfo(IObjectDescriptor source)
		{
			Source = source ?? throw new ArgumentNullException("source");
		}
	}
	public class AliasEventInfo : EventInfo
	{
		public AnchorName Alias { get; }

		public bool NeedsExpansion { get; set; }

		public AliasEventInfo(IObjectDescriptor source, AnchorName alias)
			: base(source)
		{
			if (alias.IsEmpty)
			{
				throw new ArgumentNullException("alias");
			}
			Alias = alias;
		}
	}
	public class ObjectEventInfo : EventInfo
	{
		public AnchorName Anchor { get; set; }

		public TagName Tag { get; set; }

		protected ObjectEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public 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;
		}
	}
	public sealed class MappingStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public MappingStyle Style { get; set; }

		public MappingStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class MappingEndEventInfo : EventInfo
	{
		public MappingEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceStartEventInfo : ObjectEventInfo
	{
		public bool IsImplicit { get; set; }

		public SequenceStyle Style { get; set; }

		public SequenceStartEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public sealed class SequenceEndEventInfo : EventInfo
	{
		public SequenceEndEventInfo(IObjectDescriptor source)
			: base(source)
		{
		}
	}
	public interface IAliasProvider
	{
		AnchorName GetAlias(object target);
	}
	public interface IDeserializer
	{
		T Deserialize<T>(string input);

		T Deserialize<T>(TextReader input);

		T Deserialize<T>(IParser parser);

		object? Deserialize(string input);

		object? Deserialize(TextReader input);

		object? Deserialize(IParser parser);

		object? Deserialize(string input, Type type);

		object? Deserialize(TextReader input, Type type);

		object? Deserialize(IParser parser, Type type);
	}
	public 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);
	}
	public interface INamingConvention
	{
		string Apply(string value);

		string Reverse(string value);
	}
	public interface INodeDeserializer
	{
		bool Deserialize(IParser reader, Type expectedType, Func<IParser, Type, object?> nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer);
	}
	public interface INodeTypeResolver
	{
		bool Resolve(NodeEvent? nodeEvent, ref Type currentType);
	}
	public interface IObjectAccessor
	{
		void Set(string name, object target, object value);

		object? Read(string name, object target);
	}
	public interface IObjectDescriptor
	{
		object? Value { get; }

		Type Type { get; }

		Type StaticType { get; }

		ScalarStyle ScalarStyle { get; }
	}
	public static class ObjectDescriptorExtensions
	{
		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.");
		}
	}
	public interface IObjectFactory
	{
		object Create(Type type);

		object? CreatePrimitive(Type type);

		bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments);

		Type GetValueType(Type type);

		void ExecuteOnDeserializing(object value);

		void ExecuteOnDeserialized(object value);

		void ExecuteOnSerializing(object value);

		void ExecuteOnSerialized(object value);
	}
	public interface IObjectGraphTraversalStrategy
	{
		void Traverse<TContext>(IObjectDescriptor graph, IObjectGraphVisitor<TContext> visitor, TContext context, ObjectSerializer serializer);
	}
	public interface IObjectGraphVisitor<TContext>
	{
		bool Enter(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);
	}
	public interface IPropertyDescriptor
	{
		string Name { get; }

		bool AllowNulls { get; }

		bool CanWrite { get; }

		Type Type { get; }

		Type? TypeOverride { get; set; }

		int Order { get; set; }

		ScalarStyle ScalarStyle { get; set; }

		bool Required { get; }

		Type? ConverterType { get; }

		T? GetCustomAttribute<T>() where T : Attribute;

		IObjectDescriptor Read(object target);

		void Write(object target, object? value);
	}
	public interface IRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void Before<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void After<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;

		void OnTop();

		void OnBottom();
	}
	public interface ITrackingRegistrationLocationSelectionSyntax<TBaseRegistrationType>
	{
		void InsteadOf<TRegistrationType>() where TRegistrationType : TBaseRegistrationType;
	}
	public interface ISerializer
	{
		string Serialize(object? graph);

		string Serialize(object? graph, Type type);

		void Serialize(TextWriter writer, object? graph);

		void Serialize(TextWriter writer, object? graph, Type type);

		void Serialize(IEmitter emitter, object? graph);

		void Serialize(IEmitter emitter, object? graph, Type type);
	}
	public interface ITypeInspector
	{
		IEnumerable<IPropertyDescriptor> GetProperties(Type type, object? container);

		IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching);

		string GetEnumName(Type enumType, string name);

		string GetEnumValue(object enumValue);
	}
	public interface ITypeResolver
	{
		Type Resolve(Type staticType, object? actualValue);
	}
	public interface IValueDeserializer
	{
		object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer);
	}
	public interface IValuePromise
	{
		event Action<object?> ValueAvailable;
	}
	public interface IValueSerializer
	{
		void SerializeValue(IEmitter emitter, object? value, Type? type);
	}
	public interface IYamlConvertible
	{
		void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer);

		void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer);
	}
	public delegate object? ObjectDeserializer(Type type);
	public delegate void ObjectSerializer(object? value, Type? type = null);
	[Obsolete("Please use IYamlConvertible instead")]
	public interface IYamlSerializable
	{
		void ReadYaml(IParser parser);

		void WriteYaml(IEmitter emitter);
	}
	public interface IYamlTypeConverter
	{
		bool Accepts(Type type);

		object? ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer);

		void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer);
	}
	internal sealed class LazyComponentRegistrationList<TArgument, TComponent> : IEnumerable<Func<TArgument, TComponent>>, IEnumerable
	{
		public sealed class LazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TArgument, TComponent> Factory;

			public LazyComponentRegistration(Type componentType, Func<TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		public sealed class TrackingLazyComponentRegistration
		{
			public readonly Type ComponentType;

			public readonly Func<TComponent, TArgument, TComponent> Factory;

			public TrackingLazyComponentRegistration(Type componentType, Func<TComponent, TArgument, TComponent> factory)
			{
				ComponentType = componentType;
				Factory = factory;
			}
		}

		private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly LazyComponentRegistration newRegistration;

			public RegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, LazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries[index] = newRegistration;
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.After<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int num = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(num + 1, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.Before<TRegistrationType>()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				registrations.entries.Insert(index, newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnBottom()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Add(newRegistration);
			}

			void IRegistrationLocationSelectionSyntax<TComponent>.OnTop()
			{
				registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				registrations.entries.Insert(0, newRegistration);
			}
		}

		private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax<TComponent>
		{
			private readonly LazyComponentRegistrationList<TArgument, TComponent> registrations;

			private readonly TrackingLazyComponentRegistration newRegistration;

			public TrackingRegistrationLocationSelector(LazyComponentRegistrationList<TArgument, TComponent> registrations, TrackingLazyComponentRegistration newRegistration)
			{
				this.registrations = registrations;
				this.newRegistration = newRegistration;
			}

			void ITrackingRegistrationLocationSelectionSyntax<TComponent>.InsteadOf<TRegistrationType>()
			{
				if (newRegistration.ComponentType != typeof(TRegistrationType))
				{
					registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType);
				}
				int index = registrations.EnsureRegistrationExists<TRegistrationType>();
				Func<TArgument, TComponent> innerComponentFactory = registrations.entries[index].Factory;
				registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg));
			}
		}

		[CompilerGenerated]
		private sealed class <get_InReverseOrder>d__10 : IEnumerable<Func<TArgument, TComponent>>, IEnumerable, IEnumerator<Func<TArgument, TComponent>>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private Func<TArgument, TComponent> <>2__current;

			private int <>l__initialThreadId;

			public LazyComponentRegistrationList<TArgument, TComponent> <>4__this;

			private int <i>5__2;

			Func<TArgument, TComponent> IEnumerator<Func<TArgument, TComponent>>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			object IEnumerator.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <get_InReverseOrder>d__10(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = <>4__this;
				switch (num)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<i>5__2 = lazyComponentRegistrationList.entries.Count - 1;
					break;
				case 1:
				{
					<>1__state = -1;
					int num2 = <i>5__2 - 1;
					<i>5__2 = num2;
					break;
				}
				}
				if (<i>5__2 >= 0)
				{
					<>2__current = lazyComponentRegistrationList.entries[<i>5__2].Factory;
					<>1__state = 1;
					return true;
				}
				return false;
			}

			bool IEnumerator.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				return this.MoveNext();
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<Func<TArgument, TComponent>> IEnumerable<Func<TArgument, TComponent>>.GetEnumerator()
			{
				<get_InReverseOrder>d__10 result;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					result = this;
				}
				else
				{
					result = new <get_InReverseOrder>d__10(0)
					{
						<>4__this = <>4__this
					};
				}
				return result;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<Func<TArgument, TComponent>>)this).GetEnumerator();
			}
		}

		private readonly List<LazyComponentRegistration> entries = new List<LazyComponentRegistration>();

		public int Count => entries.Count;

		public IEnumerable<Func<TArgument, TComponent>> InReverseOrder
		{
			[IteratorStateMachine(typeof(LazyComponentRegistrationList<, >.<get_InReverseOrder>d__10))]
			get
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <get_InReverseOrder>d__10(-2)
				{
					<>4__this = this
				};
			}
		}

		public LazyComponentRegistrationList<TArgument, TComponent> Clone()
		{
			LazyComponentRegistrationList<TArgument, TComponent> lazyComponentRegistrationList = new LazyComponentRegistrationList<TArgument, TComponent>();
			foreach (LazyComponentRegistration entry in entries)
			{
				lazyComponentRegistrationList.entries.Add(entry);
			}
			return lazyComponentRegistrationList;
		}

		public void Clear()
		{
			entries.Clear();
		}

		public void Add(Type componentType, Func<TArgument, TComponent> 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<TComponent> CreateRegistrationLocationSelector(Type componentType, Func<TArgument, TComponent> factory)
		{
			return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory));
		}

		public ITrackingRegistrationLocationSelectionSyntax<TComponent> CreateTrackingRegistrationLocationSelector(Type componentType, Func<TComponent, TArgument, TComponent> factory)
		{
			return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory));
		}

		public IEnumerator<Func<TArgument, TComponent>> GetEnumerator()
		{
			return entries.Select((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.");
			}
		}

		private int EnsureRegistrationExists<TRegistrationType>()
		{
			int num = IndexOfRegistration(typeof(TRegistrationType));
			if (num == -1)
			{
				throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered.");
			}
			return num;
		}
	}
	internal static class LazyComponentRegistrationListExtensions
	{
		public static TComponent BuildComponentChain<TComponent>(this LazyComponentRegistrationList<TComponent, TComponent> registrations, TComponent innerComponent)
		{
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TComponent, TComponent> factory) => factory(inner));
		}

		public static TComponent BuildComponentChain<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TComponent innerComponent, Func<TComponent, TArgument> argumentBuilder)
		{
			Func<TComponent, TArgument> argumentBuilder2 = argumentBuilder;
			return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func<TArgument, TComponent> factory) => factory(argumentBuilder2(inner)));
		}

		public static List<TComponent> BuildComponentList<TComponent>(this LazyComponentRegistrationList<Nothing, TComponent> registrations)
		{
			return registrations.Select((Func<Nothing, TComponent> factory) => factory(default(Nothing))).ToList();
		}

		public static List<TComponent> BuildComponentList<TArgument, TComponent>(this LazyComponentRegistrationList<TArgument, TComponent> registrations, TArgument argument)
		{
			TArgument argument2 = argument;
			return registrations.Select((Func<TArgument, TComponent> factory) => factory(argument2)).ToList();
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct Nothing
	{
	}
	public sealed class ObjectDescriptor : IObjectDescriptor
	{
		public object? Value { get; private set; }

		public Type Type { get; private set; }

		public Type StaticType { get; private set; }

		public ScalarStyle ScalarStyle { get; private set; }

		public ObjectDescriptor(object? value, Type type, Type staticType)
			: this(value, type, staticType, ScalarStyle.Any)
		{
		}

		public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle)
		{
			Value = value;
			Type = type ?? throw new ArgumentNullException("type");
			StaticType = staticType ?? throw new ArgumentNullException("staticType");
			ScalarStyle = scalarStyle;
		}
	}
	public delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> typeConverters, int maximumRecursion);
	public 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;

		public Type? TypeOverride
		{
			get
			{
				return baseDescriptor.TypeOverride;
			}
			set
			{
				baseDescriptor.TypeOverride = value;
			}
		}

		public Type? ConverterType => 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, object? value)
		{
			baseDescriptor.Write(target, value);
		}

		public T? GetCustomAttribute<T>() where T : Attribute
		{
			return baseDescriptor.GetCustomAttribute<T>();
		}

		public IObjectDescriptor Read(object target)
		{
			return baseDescriptor.Read(target);
		}
	}
	public 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(object? graph)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph);
			return stringWriter.ToString();
		}

		public string Serialize(object? graph, Type type)
		{
			using StringWriter stringWriter = new StringWriter();
			Serialize(stringWriter, graph, type);
			return stringWriter.ToString();
		}

		public void Serialize(TextWriter writer, object? graph)
		{
			Serialize(new Emitter(writer, emitterSettings), graph);
		}

		public void Serialize(TextWriter writer, object? graph, Type type)
		{
			Serialize(new Emitter(writer, emitterSettings), graph, type);
		}

		public void Serialize(IEmitter emitter, object? graph)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			EmitDocument(emitter, graph, null);
		}

		public void Serialize(IEmitter emitter, object? graph, Type type)
		{
			if (emitter == null)
			{
				throw new ArgumentNullException("emitter");
			}
			if (type == null)
			{
				throw new ArgumentNullException("type");
			}
			EmitDocument(emitter, graph, type);
		}

		private void EmitDocument(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());
		}
	}
	public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
	{
		private class ValueSerializer : IValueSerializer
		{
			private readonly IObjectGraphTraversalStrategy traversalStrategy;

			private readonly IEventEmitter eventEmitter;

			private readonly IEnumerable<IYamlTypeConverter> typeConverters;

			private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

			private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

			public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<IYamlTypeConverter> typeConverters, LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories)
			{
				this.traversalStrategy = traversalStrategy;
				this.eventEmitter = eventEmitter;
				this.typeConverters = typeConverters;
				this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
				this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
			}

			public void SerializeValue(IEmitter emitter, object? value, Type? type)
			{
				IEmitter emitter2 = emitter;
				Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object));
				Type staticType = type ?? typeof(object);
				ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType);
				List<IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters);
				IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor<IEmitter> inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer));
				foreach (IObjectGraphVisitor<Nothing> item in preProcessingPhaseObjectGraphVisitors)
				{
					traversalStrategy.Traverse(graph, item, default(Nothing), NestedObjectSerializer);
				}
				traversalStrategy.Traverse(graph, visitor, emitter2, NestedObjectSerializer);
				void NestedObjectSerializer(object? v, Type? t)
				{
					SerializeValue(emitter2, v, t);
				}
			}
		}

		private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory;

		private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;

		private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories;

		private readonly Dictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>();

		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<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> { 
			{
				typeof(AnchorAssigner),
				(IEnumerable<IYamlTypeConverter> typeConverters) => new AnchorAssigner(typeConverters)
			} };
			emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>
			{
				{
					typeof(CustomSerializationObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)
				},
				{
					typeof(AnchorAssigningObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>())
				},
				{
					typeof(DefaultValuesObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory())
				},
				{
					typeof(CommentsObjectGraphVisitor),
					(EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor)
				}
			};
			eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { 
			{
				typeof(TypeAssigningEventEmitter),
				(IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector())
			} };
			objectFactory = new DefaultObjectFactory();
			objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable<IYamlTypeConverter> 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<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter
		{
			return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter
		{
			return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			Func<IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory;
			return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory2(e), where);
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory, Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory;
			if (eventEmitterFactory2 == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner, BuildTypeInspector())));
			return Self;
		}

		public SerializerBuilder WithEventEmitter<TEventEmitter>(WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter
		{
			WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory2 = eventEmitterFactory;
			if (eventEmitterFactory2 == null)
			{
				throw new ArgumentNullException("eventEmitterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner)));
			return Self;
		}

		public SerializerBuilder WithoutEventEmitter<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<IYamlTypeConverter> 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<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
			return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> 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<IYamlTypeConverter> w)
			{
				w.InsteadOf<YamlDotNet.Serialization.Converters.GuidConverter>();
			}).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax<IEventEmitter> loc)
			{
				loc.InsteadOf<TypeAssigningEventEmitter>();
			});
		}

		public SerializerBuilder WithNewLine(string newLine)
		{
			emitterSettings = emitterSettings.WithNewLine(newLine);
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor;
			if (objectGraphVisitor2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitor");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> _) => objectGraphVisitor2));
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory2(typeConverters)));
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> _) => objectGraphVisitorFactory2(wrapped)));
			return this;
		}

		public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			WrapperFactory<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<Nothing> wrapped, IEnumerable<IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory2(wrapped, typeConverters)));
			return this;
		}

		public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
		{
			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<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w)
			{
				w.OnTop();
			});
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args)));
			return this;
		}

		public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory;
			if (objectGraphVisitorFactory2 == null)
			{
				throw new ArgumentNullException("objectGraphVisitorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args)));
			return this;
		}

		public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
		{
			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<IYamlTypeConverter> 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);
		}
	}
	public class Settings
	{
		public bool AllowPrivateConstructors { get; set; }
	}
	public abstract class StaticBuilderSkeleton<TBuilder> where TBuilder : StaticBuilderSkeleton<TBuilder>
	{
		internal INamingConvention namingConvention = NullNamingConvention.Instance;

		internal INamingConvention enumNamingConvention = NullNamingConvention.Instance;

		internal ITypeResolver typeResolver;

		internal readonly LazyComponentRegistrationList<Nothing, IYamlTypeConverter> typeConverterFactories;

		internal readonly LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories;

		internal bool includeNonPublicProperties;

		internal Settings settings;

		internal YamlFormatter yamlFormatter = YamlFormatter.Default;

		protected abstract TBuilder Self { get; }

		internal StaticBuilderSkeleton(ITypeResolver typeResolver)
		{
			typeConverterFactories = new LazyComponentRegistrationList<Nothing, IYamlTypeConverter> { 
			{
				typeof(YamlDotNet.Serialization.Converters.GuidConverter),
				(Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false)
			} };
			typeInspectorFactories = new LazyComponentRegistrationList<ITypeInspector, ITypeInspector>();
			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<IYamlTypeConverter> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action<IRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where)
		{
			IYamlTypeConverter typeConverter2 = typeConverter;
			if (typeConverter2 == null)
			{
				throw new ArgumentNullException("typeConverter");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2));
			return Self;
		}

		public TBuilder WithTypeConverter<TYamlTypeConverter>(WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IYamlTypeConverter>> where) where TYamlTypeConverter : IYamlTypeConverter
		{
			WrapperFactory<IYamlTypeConverter, IYamlTypeConverter> typeConverterFactory2 = typeConverterFactory;
			if (typeConverterFactory2 == null)
			{
				throw new ArgumentNullException("typeConverterFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped)));
			return Self;
		}

		public TBuilder WithoutTypeConverter<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<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector
		{
			return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax<ITypeInspector> w)
			{
				w.OnTop();
			});
		}

		public TBuilder WithTypeInspector<TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<IRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			Func<ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner)));
			return Self;
		}

		public TBuilder WithTypeInspector<TTypeInspector>(WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> where) where TTypeInspector : ITypeInspector
		{
			WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory2 = typeInspectorFactory;
			if (typeInspectorFactory2 == null)
			{
				throw new ArgumentNullException("typeInspectorFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner)));
			return Self;
		}

		public TBuilder WithoutTypeInspector<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<IYamlTypeConverter> BuildTypeConverters()
		{
			return typeConverterFactories.BuildComponentList();
		}
	}
	public 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();
		}
	}
	public sealed class StaticDeserializerBuilder : StaticBuilderSkeleton<StaticDeserializerBuilder>
	{
		private readonly StaticContext context;

		private readonly StaticObjectFactory factory;

		private readonly LazyComponentRegistrationList<Nothing, INodeDeserializer> nodeDeserializerFactories;

		private readonly LazyComponentRegistrationList<Nothing, INodeTypeResolver> nodeTypeResolverFactories;

		private readonly Dictionary<TagName, Type> tagMappings;

		private readonly ITypeConverter typeConverter;

		private readonly Dictionary<Type, Type> 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<Type, Type>();
			tagMappings = new Dictionary<TagName, Type>
			{
				{
					FailsafeSchema.Tags.Map,
					typeof(Dictionary<object, object>)
				},
				{
					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<Nothing, INodeDeserializer>
			{
				{
					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<Nothing, INodeTypeResolver>
			{
				{
					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<INodeDeserializer> w)
			{
				w.OnTop();
			});
		}

		public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<IRegistrationLocationSelectionSyntax<INodeDeserializer>> where)
		{
			INodeDeserializer nodeDeserializer2 = nodeDeserializer;
			if (nodeDeserializer2 == null)
			{
				throw new ArgumentNullException("nodeDeserializer");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2));
			return this;
		}

		public StaticDeserializerBuilder WithNodeDeserializer<TNodeDeserializer>(WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> where) where TNodeDeserializer : INodeDeserializer
		{
			WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory2 = nodeDeserializerFactory;
			if (nodeDeserializerFactory2 == null)
			{
				throw new ArgumentNullException("nodeDeserializerFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped)));
			return this;
		}

		public StaticDeserializerBuilder WithCaseInsensitivePropertyMatching()
		{
			caseInsensitivePropertyMatching = true;
			return this;
		}

		public StaticDeserializerBuilder WithEnforceNullability()
		{
			enforceNullability = true;
			return this;
		}

		public StaticDeserializerBuilder WithoutNodeDeserializer<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<ITypeDiscriminatingNodeDeserializerOptions> 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<INodeDeserializer> s)
			{
				s.Before<DictionaryNodeDeserializer>();
			});
		}

		public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver)
		{
			return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax<INodeTypeResolver> w)
			{
				w.OnTop();
			});
		}

		public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where)
		{
			INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver;
			if (nodeTypeResolver2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolver");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2));
			return this;
		}

		public StaticDeserializerBuilder WithNodeTypeResolver<TNodeTypeResolver>(WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) where TNodeTypeResolver : INodeTypeResolver
		{
			WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory2 = nodeTypeResolverFactory;
			if (nodeTypeResolverFactory2 == null)
			{
				throw new ArgumentNullException("nodeTypeResolverFactory");
			}
			if (where == null)
			{
				throw new ArgumentNullException("where");
			}
			where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped)));
			return this;
		}

		public StaticDeserializerBuilder WithoutNodeTypeResolver<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 Type 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<TInterface, 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()));
		}
	}
	public sealed class StaticSerial