Please disclose if your mod was created primarily using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ServersideQoL v1.8.0
Valheim.ServersideQoL.CodeAnalysis.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Text; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")] [assembly: AssemblyCompany("Valheim.ServersideQoL.CodeAnalysis")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+84dc0492e275b3d83ce816332bffbd112083f1f1")] [assembly: AssemblyProduct("Valheim.ServersideQoL.CodeAnalysis")] [assembly: AssemblyTitle("Valheim.ServersideQoL.CodeAnalysis")] [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] [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.CodeAnalysis { [DiagnosticAnalyzer("C#", new string[] { })] public sealed class ExpressionCacheAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "ARG0001"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor("ARG0001", "Caller line not unique", "Each call to this method must be on its own line", "Usage", (DiagnosticSeverity)3, true, (string)null, (string)null, Array.Empty<string>()); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableCollectionsMarshal.AsImmutableArray<DiagnosticDescriptor>((DiagnosticDescriptor[])(object)new DiagnosticDescriptor[1] { Rule }); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis((GeneratedCodeAnalysisFlags)0); context.RegisterSyntaxNodeAction<SyntaxKind>((Action<SyntaxNodeAnalysisContext>)delegate(SyntaxNodeAnalysisContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) MethodDeclarationSyntax val = (MethodDeclarationSyntax)((SyntaxNodeAnalysisContext)(ref context)).Node; HashSet<(ISymbol, int)> hashSet = null; foreach (InvocationExpressionSyntax item in ((SyntaxNode)val).DescendantNodes((Func<SyntaxNode, bool>)null, false).OfType<InvocationExpressionSyntax>()) { SymbolInfo symbolInfo = CSharpExtensions.GetSymbolInfo(((SyntaxNodeAnalysisContext)(ref context)).SemanticModel, (ExpressionSyntax)(object)item, default(CancellationToken)); ISymbol symbol = ((SymbolInfo)(ref symbolInfo)).Symbol; if (symbol != null && symbol.GetAttributes().Any(delegate(AttributeData x) { INamedTypeSymbol attributeClass = x.AttributeClass; return ((attributeClass != null) ? ((ISymbol)attributeClass).Name : null) == "MustBeOnUniqueLineAttribute"; })) { Location location = ((CSharpSyntaxNode)item).GetLocation(); FileLinePositionSpan lineSpan = location.GetLineSpan(); HashSet<(ISymbol, int)> obj = hashSet ?? (hashSet = new HashSet<(ISymbol, int)>()); LinePosition endLinePosition = ((FileLinePositionSpan)(ref lineSpan)).EndLinePosition; if (!obj.Add((symbol, ((LinePosition)(ref endLinePosition)).Line))) { ((SyntaxNodeAnalysisContext)(ref context)).ReportDiagnostic(Diagnostic.Create(Rule, location, Array.Empty<object>())); } } } }, (SyntaxKind[])(object)new SyntaxKind[1] { (SyntaxKind)8875 }); } } [AttributeUsage(AttributeTargets.Method)] public sealed class MustBeOnUniqueLineAttribute : Attribute { } [DiagnosticAnalyzer("C#", new string[] { })] public sealed class ExpressionFactoryAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "ARG0002"; private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor("ARG0002", "Expression factories must be static", "Expression factories must be static", "Usage", (DiagnosticSeverity)3, true, (string)null, (string)null, Array.Empty<string>()); private static readonly string __expressionTypeStartsWith = typeof(Expression).FullName + "<"; public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableCollectionsMarshal.AsImmutableArray<DiagnosticDescriptor>((DiagnosticDescriptor[])(object)new DiagnosticDescriptor[1] { Rule }); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis((GeneratedCodeAnalysisFlags)0); context.RegisterSyntaxNodeAction<SyntaxKind>((Action<SyntaxNodeAnalysisContext>)delegate(SyntaxNodeAnalysisContext context) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) ParenthesizedLambdaExpressionSyntax val = (ParenthesizedLambdaExpressionSyntax)((SyntaxNodeAnalysisContext)(ref context)).Node; CSharpSyntaxNode body = ((AnonymousFunctionExpressionSyntax)val).Body; SimpleLambdaExpressionSyntax val2 = (SimpleLambdaExpressionSyntax)(object)((body is SimpleLambdaExpressionSyntax) ? body : null); if (val2 != null) { SymbolInfo symbolInfo = CSharpExtensions.GetSymbolInfo(((SyntaxNodeAnalysisContext)(ref context)).SemanticModel, (ExpressionSyntax)(object)val, default(CancellationToken)); ISymbol symbol = ((SymbolInfo)(ref symbolInfo)).Symbol; IMethodSymbol val3 = (IMethodSymbol)(object)((symbol is IMethodSymbol) ? symbol : null); if (val3 != null && !symbol.IsStatic && ((ISymbol)val3.ReturnType).ToDisplayString((SymbolDisplayFormat)null).StartsWith(__expressionTypeStartsWith)) { ((SyntaxNodeAnalysisContext)(ref context)).ReportDiagnostic(Diagnostic.Create(Rule, ((CSharpSyntaxNode)val).GetLocation(), Array.Empty<object>())); } } }, (SyntaxKind[])(object)new SyntaxKind[1] { (SyntaxKind)8643 }); } } }
Valheim.ServersideQoL.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
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.Drawing; using System.Globalization; 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.CodeAnalysis; 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.8.0.0")] [assembly: AssemblyInformationalVersion("1.8.0+84dc0492e275b3d83ce816332bffbd112083f1f1")] [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 ReadOnlyDictionary<TKey, TValue> { public static IReadOnlyDictionary<TKey, TValue> Empty { get; } = new System.Collections.ObjectModel.ReadOnlyDictionary<TKey, TValue>(new Dictionary<TKey, TValue>(0)); } 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 sealed class ExtendedZDO : ZDO { private sealed class AdditionalData { [CompilerGenerated] private IReadOnlyList<Processor> <Processors>k__BackingField; private static readonly Dictionary<int, IReadOnlyList<Processor>> _processors = new Dictionary<int, IReadOnlyList<Processor>>(); public bool HasProcessors { get; private set; } = true; public IReadOnlyList<Processor> Processors { get { return <Processors>k__BackingField ?? (<Processors>k__BackingField = Processor.DefaultProcessors); } private set { <Processors>k__BackingField = value; HasProcessors = value.Count > 0; } } 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(IReadOnlyList<Processor> processors) { int num = 0; foreach (Processor item in Processors.AsEnumerable()) { bool flag = true; foreach (Processor item2 in processors.AsEnumerable()) { if (item == item2) { flag = false; break; } } if (flag) { num = (num, item.GetType()).GetHashCode(); } } if (!_processors.TryGetValue(num, out IReadOnlyList<Processor> value)) { List<Processor> list = new List<Processor>(); _processors.Add(num, value = list); foreach (Processor item3 in Processors.AsEnumerable()) { bool flag2 = true; foreach (Processor item4 in processors.AsEnumerable()) { if (item3 == item4) { flag2 = false; break; } } if (flag2) { list.Add(item3); } } } Processors = value; if (ProcessorDataRevisions == null) { return; } foreach (Processor item5 in processors.AsEnumerable()) { ProcessorDataRevisions.Remove(item5); } } public void UnregisterAllExcept(Processor keep) { int hashCode = (0, keep.GetType()).GetHashCode(); if (!_processors.TryGetValue(hashCode, out IReadOnlyList<Processor> value)) { _processors.Add(hashCode, value = new <>z__ReadOnlySingleElementList<Processor>(keep)); } if (ProcessorDataRevisions != null) { foreach (Processor item in Processors.AsEnumerable()) { if (item != keep) { ProcessorDataRevisions.Remove(item); } } } Processors = value; } public void UnregisterAll() { Processors = Array.Empty<Processor>(); } public void ReregisterAll() { Processors = Processor.DefaultProcessors; } } private sealed class UnityObjectEqualityComparer<T> : EqualityComparer<T> where T : Object { public static UnityObjectEqualityComparer<T> Instance { get; } = new UnityObjectEqualityComparer<T>(); public override bool Equals(T x, T y) { object obj = x; string obj2 = ((obj != null) ? ((Object)obj).name : null); object obj3 = y; return obj2 == ((obj3 != null) ? ((Object)obj3).name : null); } public override int GetHashCode(T obj) { return ((Object)obj).name.GetHashCode(); } } private delegate T GetHandler<T>(ZDO zdo, int hash, T defaultValue) where T : notnull; private delegate void SetHandler<T>(ZDO zdo, int hash, T value) where T : notnull; private delegate bool RemoveHandler<T>(ZDO zdo, int hash) where T : notnull; public sealed class ComponentFieldAccessor<TComponent> { private static class ExpressionCache<T> where T : notnull { private static readonly Dictionary<(string, int), Expression<Func<TComponent, T>>> __cache = new Dictionary<(string, int), Expression<Func<TComponent, T>>>(); public static Expression<Func<TComponent, T>> Get(Func<Expression<Func<TComponent, T>>> factory, string callerFilePath, int callerLineNo) { if (!__cache.TryGetValue((callerFilePath, callerLineNo), out Expression<Func<TComponent, T>> value)) { __cache.Add((callerFilePath, callerLineNo), value = factory()); } return value; } } private sealed class FieldReference<T> where T : notnull { private readonly int _hash; private readonly Func<TComponent, T> _getFieldValue; private static readonly Dictionary<string, FieldReference<T>> __cacheByFieldName = new Dictionary<string, FieldReference<T>>(); private static readonly Dictionary<(string, int), FieldReference<T>> __cacheByLocation = new Dictionary<(string, int), FieldReference<T>>(); private static readonly (GetHandler<T> Getter, SetHandler<T> Setter, RemoveHandler<T>? Remover, IEqualityComparer<T> EqualityComparer) Accessors = ((Func<(GetHandler<T>, SetHandler<T>, RemoveHandler<T>, IEqualityComparer<T>)>)delegate { if (typeof(T) == typeof(bool)) { return ((GetHandler<T>)(object)(GetHandler<bool>)((ZDO zdo, int hash, bool defaultValue) => zdo.GetBool(hash, defaultValue)), (SetHandler<T>)(object)(SetHandler<bool>)delegate(ZDO zdo, int hash, bool value) { zdo.Set(hash, value); }, (RemoveHandler<T>)(object)(RemoveHandler<bool>)((ZDO zdo, int hash) => zdo.RemoveInt(hash)), (IEqualityComparer<T>)EqualityComparer<bool>.Default); } if (typeof(T) == typeof(int)) { return ((GetHandler<T>)(object)(GetHandler<int>)((ZDO zdo, int hash, int defaultValue) => zdo.GetInt(hash, defaultValue)), (SetHandler<T>)(object)(SetHandler<int>)delegate(ZDO zdo, int hash, int value) { zdo.Set(hash, value, false); }, (RemoveHandler<T>)(object)(RemoveHandler<int>)((ZDO zdo, int hash) => zdo.RemoveInt(hash)), (IEqualityComparer<T>)EqualityComparer<int>.Default); } if (typeof(T) == typeof(float)) { return ((GetHandler<T>)(object)(GetHandler<float>)((ZDO zdo, int hash, float defaultValue) => zdo.GetFloat(hash, defaultValue)), (SetHandler<T>)(object)(SetHandler<float>)delegate(ZDO zdo, int hash, float value) { zdo.Set(hash, value); }, (RemoveHandler<T>)(object)(RemoveHandler<float>)((ZDO zdo, int hash) => zdo.RemoveFloat(hash)), (IEqualityComparer<T>)EqualityComparer<float>.Default); } if (typeof(T) == typeof(string)) { return ((GetHandler<T>)(object)(GetHandler<string>)((ZDO zdo, int hash, string defaultValue) => zdo.GetString(hash, defaultValue)), (SetHandler<T>)(object)(SetHandler<string>)delegate(ZDO zdo, int hash, string value) { zdo.Set(hash, value); }, null, (IEqualityComparer<T>)EqualityComparer<string>.Default); } if (typeof(T) == typeof(Vector3)) { return ((GetHandler<T>)(object)(GetHandler<Vector3>)((ZDO zdo, int hash, Vector3 defaultValue) => zdo.GetVec3(hash, defaultValue)), (SetHandler<T>)(object)(SetHandler<Vector3>)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); }, (RemoveHandler<T>)(object)(RemoveHandler<Vector3>)((ZDO zdo, int hash) => zdo.RemoveVec3(hash)), (IEqualityComparer<T>)EqualityComparer<Vector3>.Default); } if (typeof(T) == typeof(GameObject)) { return ((GetHandler<T>)(object)new GetHandler<GameObject>(GetGameObject), (SetHandler<T>)(object)(SetHandler<GameObject>)delegate(ZDO zdo, int hash, GameObject value) { zdo.Set(hash, ((Object)value).name); }, null, (IEqualityComparer<T>)(object)UnityObjectEqualityComparer<GameObject>.Instance); } if (typeof(T) == typeof(ItemDrop)) { return ((GetHandler<T>)(object)new GetHandler<ItemDrop>(GetItemDrop), (SetHandler<T>)(object)(SetHandler<ItemDrop>)delegate(ZDO zdo, int hash, ItemDrop value) { zdo.Set(hash, ((Object)value).name); }, null, (IEqualityComparer<T>)(object)UnityObjectEqualityComparer<ItemDrop>.Instance); } throw new NotSupportedException(); static GameObject GetGameObject(ZDO zdo, int hash, GameObject defaultValue) { string string2 = zdo.GetString(hash, ""); if (string.IsNullOrEmpty(string2)) { return defaultValue; } return ZNetScene.instance.GetPrefab(string2) ?? defaultValue; } static ItemDrop GetItemDrop(ZDO zdo, int hash, ItemDrop defaultValue) { string @string = zdo.GetString(hash, ""); if (!string.IsNullOrEmpty(@string)) { GameObject prefab = ZNetScene.instance.GetPrefab(@string); return ((prefab != null) ? prefab.GetComponent<ItemDrop>() : null) ?? defaultValue; } return defaultValue; } })(); private FieldReference(FieldInfo field) { _hash = StringExtensionMethods.GetStableHashCode(FormattableString.Invariant($"{typeof(TComponent).Name}.{field.Name}")); ParameterExpression parameterExpression = Expression.Parameter(typeof(TComponent)); _getFieldValue = Expression.Lambda<Func<TComponent, T>>(Expression.Field(parameterExpression, field), new ParameterExpression[1] { parameterExpression }).Compile(); } public static FieldReference<T> Get(Func<Expression<Func<TComponent, T>>> factory, string callerFilePath, int callerLineNo) { if (!__cacheByLocation.TryGetValue((callerFilePath, callerLineNo), out FieldReference<T> value)) { Expression<Func<TComponent, T>> expression = ExpressionCache<T>.Get(factory, callerFilePath, callerLineNo); MemberExpression memberExpression = (MemberExpression)expression.Body; FieldInfo fieldInfo = (FieldInfo)memberExpression.Member; if (!__cacheByFieldName.TryGetValue(fieldInfo.Name, out value)) { __cacheByFieldName.Add(fieldInfo.Name, value = new FieldReference<T>(fieldInfo)); } __cacheByLocation.Add((callerFilePath, callerLineNo), value); } return value; } public T GetValue(ComponentFieldAccessor<TComponent> componentFieldAccessor) { T val = _getFieldValue(componentFieldAccessor._component); if (!componentFieldAccessor.HasFields) { return val; } return Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val); } public ComponentFieldAccessor<TComponent> SetValue(ComponentFieldAccessor<TComponent> componentFieldAccessor, T value) { if (Accessors.Remover != null && Accessors.EqualityComparer.Equals(value, _getFieldValue(componentFieldAccessor._component))) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { if (!componentFieldAccessor.HasFields) { componentFieldAccessor.SetHasFields(value: true); } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, value); } return componentFieldAccessor; } public bool UpdateValue(ComponentFieldAccessor<TComponent> componentFieldAccessor, T value) { T val = _getFieldValue(componentFieldAccessor._component); if (Accessors.EqualityComparer.Equals(value, Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val))) { return false; } bool flag = Accessors.EqualityComparer.Equals(value, val); if (Accessors.Remover != null && flag) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { if (!componentFieldAccessor.HasFields && !flag) { componentFieldAccessor.SetHasFields(value: true); } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, value); } return true; } public ComponentFieldAccessor<TComponent> ResetValue(ComponentFieldAccessor<TComponent> componentFieldAccessor) { if (!componentFieldAccessor.HasFields) { return componentFieldAccessor; } if (Accessors.Remover != null) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, _getFieldValue(componentFieldAccessor._component)); } return componentFieldAccessor; } public bool UpdateResetValue(ComponentFieldAccessor<TComponent> componentFieldAccessor) { if (!componentFieldAccessor.HasFields) { return false; } if (Accessors.Remover != null) { return Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } T val = _getFieldValue(componentFieldAccessor._component); if (Accessors.EqualityComparer.Equals(Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val), val)) { return false; } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, val); return true; } } 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); } } [MustBeOnUniqueLine] public bool GetBool(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public float GetFloat(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public int GetInt(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public string GetString(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, bool value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, float value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, int value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, Vector3>>> fieldExpressionFactory, Vector3 value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) return FieldReference<Vector3>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, string value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, GameObject>>> fieldExpressionFactory, GameObject value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Set(Func<Expression<Func<TComponent, ItemDrop>>> fieldExpressionFactory, ItemDrop value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, bool value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, float value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, int value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, string value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, GameObject>>> fieldExpressionFactory, GameObject value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func<Expression<Func<TComponent, ItemDrop>>> fieldExpressionFactory, ItemDrop value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, GameObject>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor<TComponent> Reset(Func<Expression<Func<TComponent, ItemDrop>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, GameObject>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func<Expression<Func<TComponent, ItemDrop>>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, bool>>> fieldExpressionFactory, bool set, bool setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<bool>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, float>>> fieldExpressionFactory, bool set, float setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<float>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, int>>> fieldExpressionFactory, bool set, int setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<int>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, string>>> fieldExpressionFactory, bool set, string setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<string>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, GameObject>>> fieldExpressionFactory, bool set, GameObject setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<GameObject>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func<Expression<Func<TComponent, ItemDrop>>> fieldExpressionFactory, bool set, ItemDrop setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference<ItemDrop>.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } } public delegate void RecreateHandler(ExtendedZDO oldZdo, ExtendedZDO newZdo); 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; } } public float TotalWeight => Inventory.GetTotalWeight(); 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_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_014a: 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(() => (Container x) => x.m_width, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.ZDOInventory.cs", 47); int int2 = componentFieldAccessor.GetInt(() => (Container x) => x.m_height, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.ZDOInventory.cs", 48); 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); _items = null; } 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.ZDOInventory.cs", 80); if (dataRevision != ((ZDO)ZDO).DataRevision) { (Container, PrefabInfo.Optional<Piece>, PrefabInfo.Optional<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; } } public readonly struct ZDOVars_ { private readonly ExtendedZDO _zdo; private static int __processorId = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.ProcessorId"); 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.InitialLevel"); private static int __beaconFound = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.BeaconState"); 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($"{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 float GetEitr(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_eitr, defaultValue); } 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 int GetLeftItem(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_leftItem, defaultValue); } 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 string GetHealthString(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_health, defaultValue); } public void SetHealth(string 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 GetLocation(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_location, defaultValue); } public int GetSeed(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_seed, defaultValue); } public Guid GetProcessorId(Guid defaultValue = default(Guid)) { byte[] byteArray = ((ZDO)_zdo).GetByteArray(__processorId, Array.Empty<byte>()); if (byteArray == null || byteArray.Length <= 0) { return defaultValue; } return new Guid(byteArray); } public void SetProcessorId(Guid value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__processorId, (value == default(Guid)) ? Array.Empty<byte>() : value.ToByteArray()); } 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 GetBeaconFound(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(__beaconFound, defaultValue); } public void SetBeaconFound(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__beaconFound, value); } 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); } public float GetEstimatedSkillLevel(long playerID, SkillType skill, float defaultValue = 0f) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return ((ZDO)_zdo).GetFloat($"player{playerID}_EstimatedSkillLevel_{skill}", defaultValue); } public void SetEstimatedSkillLevel(long playerID, SkillType skill, float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_EstimatedSkillLevel_{skill}", value); } } private ZDOID _lastId = ZDOID.None; private AdditionalData? _addData; private static readonly int __hasFieldsHash = StringExtensionMethods.GetStableHashCode("HasFields"); private static bool _onZdoDestroyedRegistered; [CompilerGenerated] private PlayerProcessor.IPeerInfo? <OwnerPeerInfo>k__BackingField; 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 bool HasProcessors => AddData.HasProcessors; public IReadOnlyList<Processor> Processors => AddData.Processors; public DateTimeOffset OwnerTimestamp { get; private set; } public PlayerProcessor.IPeerInfo? OwnerPeerInfo { get { if (!((ZDO)this).HasOwner()) { return null; } long owner = ((ZDO)this).GetOwner(); PlayerProcessor.IPeerInfo? peerInfo = <OwnerPeerInfo>k__BackingField; if (peerInfo == null || peerInfo.Owner != owner) { PlayerProcessor.IPeerInfo? peerInfo2 = <OwnerPeerInfo>k__BackingField; if (peerInfo2 != null) { peerInfo2.PlayerZDO.Destroyed -= OnOwnerPlayerZdoDestroyed; } <OwnerPeerInfo>k__BackingField = Processor.Instance<PlayerProcessor>().GetPeerInfo(owner); PlayerProcessor.IPeerInfo? peerInfo3 = <OwnerPeerInfo>k__BackingField; if (peerInfo3 != null) { peerInfo3.PlayerZDO.Destroyed += OnOwnerPlayerZdoDestroyed; } } return <OwnerPeerInfo>k__BackingField; void OnOwnerPlayerZdoDestroyed(ZDO zdo) { <OwnerPeerInfo>k__BackingField = null; } } } 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", 45); } 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(IReadOnlyList<Processor> processors) { AddData.Ungregister(processors); } public void UnregisterAllExcept(Processor processor) { AddData.UnregisterAllExcept(processor); } 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: 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 extendedZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(position, prefab); ((ZDO)extendedZDO).Deserialize(new ZPackage(val.GetArray())); extendedZDO.SetOwnerInternal(owner); return extendedZDO; } 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 interface IZDOInventoryReadOnly { IReadOnlyList<ItemData> Items { get; } float TotalWeight { get; } } internal interface IZDOInventory { Inventory Inventory { get; } IList<ItemData> Items { get; } float TotalWeight { get; } int? PickupRange { get; set; } int? FeedRange { get; set; } void Save(); } internal static class ExtensionMethods { public readonly struct ListEnumerable<T> { public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable { private readonly IReadOnlyList<T> _list; private readonly int _count; private int _index; public T Current { get; private set; } readonly object? IEnumerator.Current => Current; public Enumerator(IReadOnlyList<T> list) { _list = list; _count = list.Count; _index = -1; Current = default(T); } public void Dispose() { Current = default(T); } public bool MoveNext() { if (++_index < _count) { Current = _list[_index]; return true; } Current = default(T); return false; } public void Reset() { _index = -1; } } private readonly IReadOnlyList<T> _list; public ListEnumerable(IReadOnlyList<T> list) { _list = list; } public Enumerator GetEnumerator() { return new Enumerator(_list); } } 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 float GetHeight(this Heightmap hmap, Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) int num = default(int); int num2 = default(int); hmap.WorldToVertex(pos, ref num, ref num2); return hmap.GetHeight(num, num2); } public static ConfigEntry<T> BindEx<T>(this ConfigFile config, string section, T defaultValue, string description, AcceptableValueBase? acceptableValues = null, ModConfigBase.Deprecated? deprecated = null, [CallerMemberName] string key = null) { return ModConfigBase.BindEx(config, section, defaultValue, description, acceptableValues, deprecated, key); } public static bool IsDeprecated(this ConfigEntryBase entry) { return ModConfigBase.IsDeprecated(entry); } [Conditional("DEBUG")] public static void AssertIs<T>(this ExtendedZDO zdo) where T : MonoBehaviour { } public static void InsertSorted<T>(this List<T> list, T item) where T : IComparable<T> { int num = list.BinarySearch(item); if (num < 0) { num = ~num; } list.Insert(num, item); } public static ListEnumerable<T> AsEnumerable<T>(this IReadOnlyList<T> list) { return new ListEnumerable<T>(list); } public static IEnumerable<T> AsBoxedEnumerable<T>(this IReadOnlyList<T> list) { return Enumerable.AsEnumerable(list); } } internal sealed class Logger : ILogSource, IDisposable { private readonly ManualLogSource _logger = Logger.CreateLogSource(sourceName); public string SourceName => _logger.SourceName; public event EventHandler<LogEventArgs> LogEvent { add { _logger.LogEvent += value; } remove { _logger.LogEvent -= value; } } public Logger(string sourceName) { } public void Dispose() { _logger.Dispose(); } public void Log(LogLevel level, object data) { //IL_003d: 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) double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; TimeSpan timeSpan = TimeSpan.FromSeconds(realtimeSinceStartupAsDouble); if (realtimeSinceStartupAsDouble < 86400.0) { _logger.Log(level, (object)$"[{timeSpan:hh\\:mm\\:ss\\.fff}] {data}"); } else { _logger.Log(level, (object)$"[{timeSpan:d\\.hh\\:mm\\:ss\\.fff}] {data}"); } } public void LogFatal(object data) { Log((LogLevel)1, data); } public void LogError(object data) { Log((LogLevel)2, data); } public void LogWarning(object data) { Log((LogLevel)4, data); } public void LogMessage(object data) { Log((LogLevel)8, data); } public void LogInfo(object data) { Log((LogLevel)16, data); } public void LogDebug(object data) { Log((LogLevel)32, data); } [Conditional("DEBUG")] public void DevLog(string text, LogLevel logLevel = 4) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Log(logLevel, text); } } [BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.8.0")] public sealed class Main : BaseUnityPlugin { private record SectorInfo(List<Peer> Peers, List<ZDO> ZDOs) { public int ZdoIndex { get; set; } public int InverseWeight { get; set; } } private sealed class PeersEnumerable : IEnumerable<Peer>, IEnumerable { public struct Enumerator : IEnumerator<Peer>, IEnumerator, IDisposable { private readonly PeersEnumerable _enumerable; private int _index; public Peer Current { get; private set; } readonly object IEnumerator.Current => Current; public Enumerator(PeersEnumerable enumerable) { _enumerable = enumerable; _index = -2; Current = null; } public void Dispose() { Current = null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { if (++_index < 0) { if (_enumerable._localPeer != null) { Current = Peer.Get(_enumerable._localPeer); return true; } _index++; } if (_index < _enumerable._peers.Count) { Current = Peer.Get(_enumerable._peers[_index]); return true; } Current = null; return false; } public void Reset() { _index = -2; } } private readonly ZNetPeer? _localPeer; private List<ZNetPeer> _peers; public int Count => _peers.Count + ((_localPeer != null) ? 1 : 0); public PeersEnumerable(ZNetPeer? localPeer) { _localPeer = localPeer; _peers = new List<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(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator<Peer> IEnumerable<Peer>.GetEnumerator() { return GetEnumerator(); } 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_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) { int num2 = (ZNet.instance.IsDedicated() ? 10 : 30); int num3 = ((Application.targetFrameRate < 0) ? (2 * num2) : Application.targetFrameRate); double num4 = 1.0 / (double)num2; double num5 = 1.0 / (double)Time.unscaledDeltaTime; if ((double)Time.unscaledDeltaTime > num4) { if (main.Config.General.DiagnosticLogs.Value) { main.Logger.LogInfo($"No time budget available, actual FPS: {num5}, min FPS: {num2}, target FPS: {num3}"); } break; } double num6 = Math.Min(1.0, (num5 - (double)num2) / (double)(num3 - num2)); double timeBudgetSeconds = (num4 - (double)Time.unscaledDeltaTime) * num6; try { main.Execute(<peers>5__2, timeBudgetSeconds); } catch (OperationCanceledException) { return false; } catch (Exception data) { main.Logger.LogError(data); return false; } break; } <peers>5__2 = null; goto IL_005b; } 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("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; 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_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; } <>2__current = null; <>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 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 List<(Processor, double)>? _processingTimes; private readonly List<Processor> _unregister = new List<Processor>(); private bool _configChanged = true; private readonly GameVersion ExpectedGameVersion = GameVersion.ParseGameVersion("0.221"); private const uint ExpectedNetworkVersion = 36u; private const uint ExpectedItemDataVersion = 106u; private const uint ExpectedWorldVersion = 37u; internal const string DummyConfigSection = "Z - Dummy"; private const string PluginVersion = "1.8.0"; internal const string PluginInformationalVersion = "1.8.0"; 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 Logger Logger { get; } = new Logger("ServersideQoL"); internal ModConfig Config => _worldConfig ?? _mainConfig ?? (_mainConfig = new ModConfig(((BaseUnityPlugin)this).Config)); public Main() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) Instance = this; } private void Awake() { 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_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected O, but got Unknown //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Expected O, but got Unknown //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: 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("Using world config file"); _worldConfig = new ModConfig(new ConfigFile(rootPath, false, new BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.8.0"))); } Logger.LogInfo(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("Many features are incompatible with " + value.Metadata.Name); } if (Config.General.DiagnosticLogs.Value) { Logger 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(string.Join(separator, list.ToArray())); } bool flag = false; bool flag2 = false; GameVersion gameVersion = RuntimeInformation.Instance.GameVersion; gameVersion.m_patch = 0; GameVersion val = gameVersion; if (RuntimeInformation.Instance.NetworkVersion != 36) { Logger.LogWarning(FormattableString.Invariant($"Unsupported network version: {RuntimeInformation.Instance.NetworkVersion}, expected: {36u}")); flag = true; flag2 |= !Config.General.IgnoreNetworkVersionCheck.Value; } if ((long)RuntimeInformation.Instance.ItemDataVersion != 106) { Logger.LogWarning(FormattableString.Invariant($"Unsupported item data version: {RuntimeInformation.Instance.ItemDataVersion}, expected: {106u}")); flag = true; flag2 |= !Config.General.IgnoreItemDataVersionCheck.Value; } if ((long)RuntimeInformation.Instance.WorldVersion != 37) { Logger.LogWarning(FormattableString.Invariant($"Unsupported world version: {RuntimeInformation.Instance.WorldVersion}, expected: {37u}")); flag = true; flag2 |= !Config.General.IgnoreWorldVersionCheck.Value; } if (flag) { if (flag2) { Logger.LogError("Version checks failed. Mod execution is stopped"); return false; } Logger.LogWarning("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($"Config changed: [{e.ChangedSetting.Definition.Section}].[{e.ChangedSetting.Definition.Key}] = {e.ChangedSetting.BoxedValue}"); } if (e.ChangedSetting == Config.General.DiagnosticLogs && Config.General.DiagnosticLogs.Value) { Logger 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(string.Join(separator, list.ToArray())); } } private void Execute(PeersEnumerable peers, double timeBudgetSeconds) { //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_04d1: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_0433: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_05f9: Unknown result type (might be due to invalid IL or missing references) //IL_05fb: 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_0922: Unknown result type (might be due to invalid IL or missing references) //IL_093d: Unknown result type (might be due to invalid IL or missing references) //IL_09bd: Unknown result type (might be due to invalid IL or missing references) //IL_09c1: Invalid comparison between Unknown and I4 //IL_09c3: Unknown result type (might be due to invalid IL or missing references) //IL_071f: Unknown result type (might be due to invalid IL or missing references) //IL_0aae: Unknown result type (might be due to invalid IL or missing references) double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; double num = realtimeSinceStartupAsDouble + timeBudgetSeconds; _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 data) { Logger.LogError(data); } } 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 data2) { Logger.LogError(data2); } } } if (Config.GlobalsKeys.SetGlobalKeysFromConfig.Value) { foreach (KeyValuePair<GlobalKeys, ConfigEntryBase> item in Config.GlobalsKeys.KeyConfigs.Where<KeyValuePair<GlobalKeys, ConfigEntryBase>>((KeyValuePair<GlobalKeys, ConfigEntryBase> x) => !object.Equals(x.Value.BoxedValue, x.Value.DefaultValue))) { item.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 num2; try { num2 = (float)Convert.ChangeType(val4.BoxedValue, typeof(float)); } catch (Exception data3) { Logger.LogError(data3); continue; } ZoneSystem.instance.SetGlobalKey(val3, num2); } } foreach (Processor item2 in Processor.DefaultProcessors.AsEnumerable()) { item2.Initialize(_executeCounter == 1); } if (_executeCounter == 1) { Config.ConfigFile.SettingChanged -= OnConfigChanged; Config.ConfigFile.SettingChanged += OnConfigChanged; return; } { foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { @object.ReregisterAllProcessors(); } return; } } peers.Update(); SharedProcessorState.CleanUp(peers); if (peers.Count == 0) { return; } Dictionary<Vector2i, SectorInfo> playerSectorsOld = _playerSectorsOld; Dictionary<Vector2i, SectorInfo> playerSectors = _playerSectors; _playerSectors = playerSectorsOld; _playerSectorsOld = playerSectors; int value2 = Config.General.ZonesAroundPlayers.Value; Vector2i key2 = default(Vector2i); foreach (Peer peer in peers) { Vector2i zone = ZoneSystem.GetZone(peer.m_refPos); for (int i = zone.x - value2; i <= zone.x + value2; i++) { for (int j = zone.y - value2; j <= zone.y + value2; j++) { ((Vector2i)(ref key2))..ctor(i, j); if (_playerSectorsOld.Remove(key2, out SectorInfo value3)) { _playerSectors.Add(key2, value3); value3.InverseWeight = 0; value3.Peers.Clear(); value3.Peers.Add(peer); continue; } if (_playerSectors.TryGetValue(key2, out value3)) { value3.Peers.Add(peer); continue; } if (_sectorInfoPool.TryPop(out value3)) { value3.Peers.Add(peer); } else { value3 = new SectorInfo(new List<Peer>(1) { peer }, new List<ZDO>()); } _playerSectors.Add(key2, value3); } } } foreach (SectorInfo value4 in _playerSectorsOld.Values) { value4.ZdoIndex = 0; value4.InverseWeight = 0; value4.Peers.Clear(); value4.ZDOs.Clear(); _sectorInfoPool.Push(value4); } _playerSectorsOld.Clear(); Dictionary<Vector2i, SectorInfo> playerSectors2 = _playerSectors; foreach (Processor item3 in Processor.DefaultProcessors.AsEnumerable()) { item3.PreProcess(peers); } int num3 = 0; int num4 = 0; int num5 = 0; foreach (var (val6, sectorInfo2) in playerSectors2) { if (Time.realtimeSinceStartupAsDouble > num) { break; } num3++; 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); } } num5 += sectorInfo2.ZDOs.Count; while (sectorInfo2.ZdoIndex < sectorInfo2.ZDOs.Count && (num4 % 10 != 0 || !(Time.realtimeSinceStartupAsDouble >= num))) { num4++; ExtendedZDO extendedZDO2 = (ExtendedZDO)(object)sectorInfo2.ZDOs[sectorInfo2.ZdoIndex]; if (((ZDO)extendedZDO2).IsValid() && extendedZDO2.HasProcessors) { if (extendedZDO2.Processors.Count > 1) { Processor processor = null; foreach (Processor item4 in extendedZDO2.Processors.AsEnumerable()) { if (item4.ClaimExclusive(extendedZDO2)) { if (processor == null) { processor = item4; } else if (Config.General.DiagnosticLogs.Value) { Logger.LogError(FormattableString.Invariant($"ZDO {((ZDO)extendedZDO2).m_uid} claimed exclusive by {item4.GetType().Name} while already claimed by {processor.GetType().Name}")); }
Valheim.ServersideQoL.YamlDotNet.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
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