using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Timers; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Jotunn.Configs; using Jotunn.Managers; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; 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("HarnessPrefabs")] [assembly: AssemblyDescription("Policy driven Valheim prefab builder tabs for public and admin clients.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("sighsorry")] [assembly: AssemblyProduct("HarnessPrefabs")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("1.0.3")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.3.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace HarnessPrefabs { internal static class MvbpCompatibilityDefaults { private sealed class PatchDefaults { public Vector3? PlacementOffset { get; set; } public bool PlayerBasePatch { get; set; } public string SpawnOnDestroyed { get; set; } = ""; public int? ContainerWidth { get; set; } public int? ContainerHeight { get; set; } } private static readonly Dictionary Defaults = new Dictionary(StringComparer.Ordinal) { ["AshlandsTree1"] = new PatchDefaults { PlacementOffset = new Vector3(0f, 1f, 0f) }, ["AshlandsTree3"] = new PatchDefaults { PlacementOffset = new Vector3(0f, 1f, 0f) }, ["AshlandsTree5"] = new PatchDefaults { PlacementOffset = new Vector3(0f, 0.5f, 0f) }, ["Ashlands_Fortress_Wall_PillarTopStone_frac"] = new PatchDefaults { PlacementOffset = new Vector3(0f, -0.1f, 0f) }, ["BogWitch_Fire_Pit"] = new PatchDefaults { PlacementOffset = new Vector3(0f, -1f, 0f) }, ["dvergrprops_pickaxe"] = new PatchDefaults { PlacementOffset = new Vector3(-1f, 0f, 0f) }, ["shipwreck_karve_dragonhead"] = new PatchDefaults { PlacementOffset = new Vector3(0f, -1.5f, 6f) }, ["CastleKit_groundtorch"] = new PatchDefaults { PlayerBasePatch = true }, ["CastleKit_groundtorch_blue"] = new PatchDefaults { PlayerBasePatch = true }, ["CastleKit_groundtorch_green"] = new PatchDefaults { PlayerBasePatch = true }, ["MountainKit_brazier"] = new PatchDefaults { PlayerBasePatch = true }, ["MountainKit_brazier_blue"] = new PatchDefaults { PlayerBasePatch = true }, ["dvergrprops_bed"] = new PatchDefaults { PlayerBasePatch = true }, ["goblin_bed"] = new PatchDefaults { PlayerBasePatch = true }, ["TreasureChest_ashland_stone"] = new PatchDefaults { ContainerWidth = 5, ContainerHeight = 2 }, ["TreasureChest_charredfortress"] = new PatchDefaults { ContainerWidth = 8, ContainerHeight = 4 }, ["TreasureChest_dvergr_loose_stone"] = new PatchDefaults { ContainerWidth = 8, ContainerHeight = 4 }, ["TreasureChest_dvergrtower"] = new PatchDefaults { ContainerWidth = 7, ContainerHeight = 4 }, ["TreasureChest_dvergrtown"] = new PatchDefaults { ContainerWidth = 8, ContainerHeight = 4 }, ["TreasureChest_fCrypt"] = new PatchDefaults { ContainerWidth = 5, ContainerHeight = 2 }, ["TreasureChest_mountaincave"] = new PatchDefaults { ContainerWidth = 6, ContainerHeight = 3 }, ["TreasureChest_sunkencrypt"] = new PatchDefaults { ContainerWidth = 5, ContainerHeight = 2 }, ["TreasureChest_trollcave"] = new PatchDefaults { ContainerWidth = 6, ContainerHeight = 3 }, ["loot_chest_stone"] = new PatchDefaults { ContainerWidth = 5, ContainerHeight = 2 }, ["Trailership"] = new PatchDefaults { ContainerWidth = 6, ContainerHeight = 4 }, ["ancient_skull"] = new PatchDefaults { SpawnOnDestroyed = "sfx_rock_destroyed" }, ["flying_core"] = new PatchDefaults { SpawnOnDestroyed = "fx_crystal_destruction" }, ["rock_mistlands2"] = new PatchDefaults { SpawnOnDestroyed = "sfx_rock_destroyed" } }; public static Vector3? GetPlacementOffset(string prefabName) { if (!TryGetDefaults(prefabName, out var defaults)) { return null; } return defaults.PlacementOffset; } public static bool HasPlayerBasePatch(string prefabName) { if (TryGetDefaults(prefabName, out var defaults)) { return defaults.PlayerBasePatch; } return false; } public static bool TryGetSpawnOnDestroyed(string prefabName, out string spawnOnDestroyed) { spawnOnDestroyed = ""; if (!TryGetDefaults(prefabName, out var defaults) || string.IsNullOrWhiteSpace(defaults.SpawnOnDestroyed)) { return false; } spawnOnDestroyed = defaults.SpawnOnDestroyed; return true; } public static bool TryGetContainerSize(string prefabName, out int width, out int height) { width = 0; height = 0; if (!TryGetDefaults(prefabName, out var defaults) || !defaults.ContainerWidth.HasValue || !defaults.ContainerHeight.HasValue) { return false; } width = defaults.ContainerWidth.Value; height = defaults.ContainerHeight.Value; return true; } private static bool TryGetDefaults(string prefabName, out PatchDefaults defaults) { string text = HarnessPrefabsRuntime.NormalizePrefabName(prefabName); if (text.Length == 0) { defaults = null; return false; } return Defaults.TryGetValue(text, out defaults); } } internal readonly struct MvbpPrefabDefault { public readonly bool Enabled; public readonly bool AllowedInDungeons; public readonly string Category; public readonly string CraftingStation; public readonly string Requirements; public readonly bool ClipEverything; public readonly bool ClipGround; public readonly bool PlacementPatch; public readonly string? DisplayName; public readonly string? Description; public readonly string PieceGroup; public MvbpPrefabDefault(bool enabled, bool allowedInDungeons, string category, string craftingStation, string requirements, bool clipEverything, bool clipGround, bool placementPatch, string? displayName, string? description, string pieceGroup) { Enabled = enabled; AllowedInDungeons = allowedInDungeons; Category = (string.IsNullOrWhiteSpace(category) ? "CreatorShop" : category); CraftingStation = (string.IsNullOrWhiteSpace(craftingStation) ? "None" : craftingStation); Requirements = requirements ?? ""; ClipEverything = clipEverything; ClipGround = clipGround; PlacementPatch = placementPatch; DisplayName = displayName; Description = description; PieceGroup = (string.IsNullOrWhiteSpace(pieceGroup) ? "None" : pieceGroup); } } internal static class MvbpPrefabDefaults { private static readonly TextInfo EnglishTextInfo = new CultureInfo("en-US", useUserOverride: false).TextInfo; private static readonly Regex DigitsToEndRegex = new Regex("(.+?)((? Defaults = new Dictionary(StringComparer.Ordinal) { ["ancient_skull"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:100", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["ArmorStand_Female"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "FineWood:8;BronzeNails:2;Tar:4", clipEverything: false, clipGround: false, placementPatch: false, null, "", "ArmorStand"), ["ArmorStand_Male"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "FineWood:8;BronzeNails:2;Tar:4", clipEverything: false, clipGround: false, placementPatch: false, null, "", "ArmorStand"), ["ashland_pot1_green"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashland_pot1_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashland_pot2_green"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashland_pot2_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashland_pot3_green"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashland_pot3_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashland_Stair"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:32", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashland_Steepstair"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_Altar"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Arch1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Arch2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Arch2_Broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Arch2_Broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_ArchRoof"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_ArchRoofDamaged"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_ArchRoofDamaged_half1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_ArchRoofDamaged_half2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_ArchRoofLong_Damaged"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Boss_Pillar"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_Boss_Pillar_Twist_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Boss_Pillar_Twist_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Boss_Pillar_Twist_broken3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Floor"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_floor_large_fractured"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Floor"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Gate"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:32", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Gate_Door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "BlackForge", "Copper:35", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Wall_Pillar"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Wall_Pillar_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Wall_PillarTop"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Wall_PillarTop_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Fortress_Wall_PillarTopStone_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_Fortress_Wall_Spikes"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "BlackForge", "Copper:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip2_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip2_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip3_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip3_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Pillar4_tip3_broken3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_PillarBase3_double"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:3", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ramp"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_rock1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "Stonecutter", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_rock2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "Stonecutter", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_1point5x1point5"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_1point5x1point5_broken"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_3x3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_3x3_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_3x3_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_3x3_broken3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_6x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_6x6_broken1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Floor_6x6_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_Ruins_Ramp"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Ramp_Upsidedown"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_TopStone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_twist_ArchBig"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_twist_PillarBase"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_twist_PillarBaseSmall"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:3", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_4x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Broken3_4x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Broken4_4x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Broken5_4x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Top_wHole"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:16", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Window_4x6_broken2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Window_4x6_broken3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Window_4x6_broken4"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Window_4x6_broken5"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Window_4x6_broken6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Ruins_Wall_Windows_Broken_4x6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Ashlands_StairsBroad"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:24", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_cornerL"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_cornerL_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_cornerR"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_cornerR_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_edge"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_edge_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_edge2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_edge2_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_Wall_2x2_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_WallBlock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_WallBlock_1x2x2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Ashlands_WallBlock_base"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:3", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsBranch1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["AshlandsBranch2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsBranch3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["AshlandsBush1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["AshlandsBush2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["AshlandsTree1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsTree3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsTree4"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsTree5"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsTree6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["AshlandsTree6_big"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeLog1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeLog2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeLogHalf1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeLogHalf2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeStump1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeStump2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["AshlandsTreeStump3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["ashwood_arch_bottom"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Blackwood:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashwood_arch_top"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Blackwood:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashwood_wall_beam_26_alt"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashwood_wall_beam_45_alt"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashwood_wall_cross_26_alt"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["ashwood_wall_cross_45_alt"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["asksvin_carrion"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["asksvin_carrion2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["barrell"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "Workbench", "FineWood:2", clipEverything: false, clipGround: false, placementPatch: false, "Barrel", "", "Misc"), ["beech_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BeechSeeds:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["beech_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BeechSeeds:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Beech_small1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Beech_small2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Beech_Stub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Beech1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["BigRock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Birch_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Birch_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Birch1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BirchSeeds:1;FineWood:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Birch1_aut"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BirchSeeds:1;FineWood:2", clipEverything: true, clipGround: false, placementPatch: false, "Birch1 (autumn)", null, "Flora"), ["Birch2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BirchSeeds:1;FineWood:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Birch2_aut"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "BirchSeeds:1;FineWood:2", clipEverything: true, clipGround: false, placementPatch: false, "Birch (autumn)", null, "Flora"), ["BirchStub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["blackmarble_2x2_enforced"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "BlackForge", "BlackMarble:8;Copper:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_2x2x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_altar_crystal"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["blackmarble_altar_crystal_broken"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["blackmarble_base_2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:6", clipEverything: false, clipGround: false, placementPatch: false, "Black marble plinth (wide)", null, "BlackMarble"), ["blackmarble_column_3"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:16", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_creep_4x1x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_creep_4x2x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_creep_slope_inverted_1x1x2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_creep_slope_inverted_2x2x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_creep_stair"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_floor_large"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:32", clipEverything: false, clipGround: true, placementPatch: false, "Black marble floor 8x8", null, "BlackMarble"), ["blackmarble_head_big01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_head_big02"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_head01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_head02"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_out_2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:6", clipEverything: false, clipGround: false, placementPatch: false, "Black marble cornice (wide)", null, "BlackMarble"), ["blackmarble_post01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: true, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_slope_1x2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_slope_inverted_1x2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_stair_corner"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: false, placementPatch: true, null, null, "BlackMarble"), ["blackmarble_stair_corner_left"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: false, placementPatch: true, null, null, "BlackMarble"), ["blackmarble_tile_floor_1x1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_tile_floor_2x2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_tile_wall_1x1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_tile_wall_2x2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["blackmarble_tile_wall_2x4"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "BlackMarble"), ["BlueberryBush"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Blueberries:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Plant"), ["BogWitch_Fire_Pit"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "None", "PowderedDragonEgg:2;Stone:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["BossStone_Bonemass"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["BossStone_DragonQueen"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["BossStone_Eikthyr"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["BossStone_Fader"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["BossStone_TheElder"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["BossStone_TheQueen"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["BossStone_Yagluth"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Misc"), ["bucket"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "Workbench", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Misc"), ["Bush01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Bush01_heath"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Bush02_en"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Candle_resin_bogwitch"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["CastleKit_braided_box01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "Workbench", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, "Wood box", null, "Misc"), ["CastleKit_groundtorch"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Iron:2;Resin:2;SurtlingCore:1", clipEverything: false, clipGround: false, placementPatch: false, "Standing Iron Torch (Eternal)", "Burns eternally without fuel.", "Torch"), ["CastleKit_groundtorch_blue"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Iron:2;GreydwarfEye:2;SurtlingCore:1", clipEverything: false, clipGround: false, placementPatch: false, "Standing Blue-Burning Iron Torch (Eternal)", "Burns eternally without fuel.", "Torch"), ["CastleKit_groundtorch_green"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Iron:2;Guck:2;SurtlingCore:1", clipEverything: false, clipGround: false, placementPatch: false, "Standing Green-Burning Iron Torch (Eternal)", "Burns eternally without fuel.", "Torch"), ["caverock_ice_pillar_wall"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ice"), ["caverock_ice_stalagmite"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ice"), ["caverock_ice_stalagmite_broken"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Ice"), ["caverock_ice_stalagtite"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Ice"), ["caverock_ice_stalagtite_falling"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Ice"), ["Charred_altar_bellfragment"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["charred_shieldgenerator"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CharredBanner1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CharredBanner2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CharredBanner3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Charredfortress_LOD"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["Chest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "None", "Wood:10;Iron:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chest"), ["Cinder"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["Cinder_campfire"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["CinderSky"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["CinderStorm"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands_Arch_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands1_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: true, placementPatch: true, null, null, "None"), ["cliff_ashlands2_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: true, placementPatch: true, null, null, "None"), ["cliff_ashlands3_Arch_1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["cliff_ashlands4"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands4_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands5"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands6"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands6_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands7_HalfArch"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands7_HalfArch_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlands8"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_ashlandsflowrock_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["cliff_mistlands1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cliff_mistlands1_creep"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cliff_mistlands1_creep_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cliff_mistlands1_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cliff_mistlands2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:175", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cliff_mistlands2_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:175", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["cloth_hanging_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["cloth_hanging_door_double"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "JuteRed:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["cloth_hanging_long"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["CloudberryBush"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Cloudberry:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Plant"), ["CreepProp_egg_hanging01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CreepProp_egg_hanging02"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CreepProp_entrance1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["CreepProp_entrance2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["CreepProp_hanging01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["CreepProp_wall01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["crypt_skeleton_chest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["dead_deer"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["dungeon_forestcrypt_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["dungeon_queen_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:40;DvergrKeyFragment:4;Iron:12", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["dungeon_sunkencrypt_irongate"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "None", "Iron:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Iron"), ["dungeon_sunkencrypt_irongate_rusty"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Forge", "Iron:4", clipEverything: false, clipGround: true, placementPatch: false, null, null, "Iron"), ["dverger_demister"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "Iron:1;Wisp:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Torch"), ["dverger_demister_broken"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Torch"), ["dverger_demister_large"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "Iron:1;Wisp:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Torch"), ["dverger_demister_ruins"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Misc"), ["dverger_guardstone"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "BlackForge", "YggdrasilWood:5;BlackMarble:5;BlackCore:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["dvergrprops_banner"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "JuteBlue:6;FineWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["dvergrprops_barrel"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "YggdrasilWood:20;Bronze:5;Resin:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_bed"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:8;ScaleHide:2;IronNails:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Bed"), ["dvergrprops_chair"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chair"), ["dvergrprops_crate"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Misc"), ["dvergrprops_crate_ashlands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["dvergrprops_crate_long"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr component crate", "", "Misc"), ["dvergrprops_curtain"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "JuteBlue:6;FineWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["dvergrprops_hooknchain"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "BlackForge", "Chain:2;Iron:2", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr hook & chain", null, "Misc"), ["dvergrprops_lantern_standing"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_pickaxe"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_shelf"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:4;IronNails:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_stool"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chair"), ["dvergrprops_table"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:6;IronNails:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Table"), ["dvergrprops_wood_beam"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_wood_floor"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_wood_pole"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr wood pole (large)", null, "Dvergr"), ["dvergrprops_wood_stair"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_wood_stakewall"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "None", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrprops_wood_wall"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:10", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr wood wall 4x4", null, "Dvergr"), ["dvergrtown_arch"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "BlackMarble:8", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_creep_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, "Door hanging (creep)", "", "Misc"), ["dvergrtown_secretdoor"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "BlackForge", "BlackMarble:12;Eitr:2", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr secret door", null, "Dvergr"), ["dvergrtown_slidingdoor"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "BlackForge", "BlackMarble:32;Copper:8", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr sliding door", null, "Dvergr"), ["dvergrtown_stair_corner_wood_left"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:5;CopperScrap:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_beam"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr wood beam (creep)", null, "Dvergr"), ["dvergrtown_wood_crane"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:8;Chain:2;Iron:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_pole"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr wood pole (creep)", null, "Dvergr"), ["dvergrtown_wood_stake"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_stakewall"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_support"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_wall01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:20", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_wall02"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:12", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["dvergrtown_wood_wall03"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:10;IronNails:6", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["fader_bellholder"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["fenrirhide_hanging"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "WolfHairBundle:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["fenrirhide_hanging_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "WolfHairBundle:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["FernAshlands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["FernFiddleHeadAshlands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["Fire"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["fire_pit_haldor"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "None", "Stone:5;Wood:2;BlackCore:1", clipEverything: false, clipGround: false, placementPatch: false, "Campfire (Eternal)", "Burns eternally without fuel.", "Fire"), ["fire_pit_hildir"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "Forge", "Ironpit:1;Wood:1;BlackCore:1", clipEverything: false, clipGround: false, placementPatch: false, "Firepit Iron (Eternal)", "Burns eternally without fuel.", "Fire"), ["FireFlies"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["FirTree"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:16", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_oldLog"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_small"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_small_dead"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["FirTree_Stub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["FlametalRockstand"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["FlametalRockstand_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Flies"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["flying_core"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Crystal:24", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["fuling_trap"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["fx_fallenvalkyrie_death"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["fx_Lightning"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["giant_arm"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_brain"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Softtissue:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_brain_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Softtissue:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_helmet1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_helmet1_destruction"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_helmet2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_helmet2_destruction"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_ribs"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_ribs_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_skull"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_skull_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BlackMarble:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_sword1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_sword1_destruction"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_sword2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["giant_sword2_destruction"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Iron:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["GlowingMushroom"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Ooze:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["goblin_banner"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "Wood:1;DeerHide:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Banner"), ["goblin_bed"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "Wood:8;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Bed"), ["goblin_fence"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_pole"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_pole_small"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_roof_45d"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1;DeerHide:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_roof_45d_corner"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1;DeerHide:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_roof_cap"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:4;DeerHide:4;Tar:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_stairs"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_stepladder"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_strawpile"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "None", "Wood:4", clipEverything: false, clipGround: false, placementPatch: false, "Rug straw (large)", "", "Rug"), ["goblin_totempole"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Workbench", "Wood:2;GoblinTotem:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_trashpile"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_woodwall_1m"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_woodwall_2m"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblin_woodwall_2m_ribs"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BoneFragments:6;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["goblinking_totemholder"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Stone:1;Tar:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Goblin"), ["GraveStone_Broken_CharredTwitcherNest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GraveStone_Broken_World"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GraveStone_CharredFaderLocation"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GraveStone_CharredTwitcherNest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GraveStone_Elite_Broken_CharredTwitcherNest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GraveStone_Elite_CharredTwitcherNest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Greydwarf_Root"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["GuckSack"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Guck:12", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["GuckSack_small"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Guck:6", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["hanging_hairstrands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["highstone"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["highstone_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["horizontal_web"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["HouseFire"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["HugeRoot1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Ice_floor"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Crystal:16", clipEverything: true, clipGround: true, placementPatch: false, null, null, "None"), ["Ice_floor_fractured"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Crystal:16", clipEverything: true, clipGround: true, placementPatch: false, null, null, "None"), ["ice_rock1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["ice_rock1_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["ice1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["IceBlocker"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["iron_floor_1x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["iron_wall_1x1_rusty"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Forge", "Iron:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Iron"), ["lavabomb_rock1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["LavaRock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["lavarock_ashlands1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: true, null, null, "None"), ["Leviathan"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Chitin:50", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["LeviathanLava"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["lightningAOE"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["loot_chest_stone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:10", clipEverything: false, clipGround: false, placementPatch: false, "Stone chest (light moss)", null, "Chest"), ["lox_ribs"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "BoneFragments:30", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["LuredWisp"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Wisp:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["marker01"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["marker02"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["metalbar_1x2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "BlackMarble:2;Copper:1", clipEverything: false, clipGround: false, placementPatch: false, "Black marble 1x2 enforced", "", "BlackMarble"), ["MineRock_Copper"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:10;CopperOre:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["MineRock_Iron"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:10;IronScrap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["MineRock_Meteorite"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["MineRock_Obsidian"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Obsidian:7", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["MineRock_Stone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["MineRock_Tin"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "TinOre:4", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["mistvolume"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Eitr:10;Wisp:4", clipEverything: true, clipGround: false, placementPatch: false, "Mist volume", "Warning: requires devcommands to remove.", "None"), ["morgenhole_pile"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["MountainGraveStone01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["MountainKit_brazier"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Bronze:5;Coal:2;BlackCore:1;WolfClaw:3", clipEverything: false, clipGround: false, placementPatch: false, "Standing Brazier (Eternal)", "Burns eternally without fuel.", "Brazier"), ["MountainKit_brazier_blue"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Bronze:5;GreydwarfEye:2;BlackCore:1;WolfClaw:3", clipEverything: false, clipGround: false, placementPatch: false, "Blue Standing Brazier (Eternal)", "Burns eternally without fuel.", "Brazier"), ["MountainKit_brazier_purple"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Forge", "Bronze:5;CharcoalResin:2;BlackCore:1;WolfClaw:3", clipEverything: false, clipGround: false, placementPatch: false, "Purple Standing Brazier (Eternal)", "Burns eternally without fuel.", "None"), ["mountainkit_chair"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "Workbench", "FineWood:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chair"), ["mountainkit_table"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "Workbench", "FineWood:10;IronNails:20", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Table"), ["MountainKit_wood_gate"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "Forge", "Wood:20;Iron:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "IronScrap:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile_beacon"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "IronScrap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile_old"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "IronScrap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "IronScrap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["mudpile2_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "IronScrap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Oak_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:10;FineWood:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Oak_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:5;FineWood:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["Oak1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:20;FineWood:20", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["OakStub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:5;FineWood:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_Ashstone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Barley"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Barley:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Barley_Wild"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Barley:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_BlackCoreStand"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "CreatorShop", "BlackForge", "Iron:2;BlackCore:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_BogIronOre"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "IronScrap:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_Branch"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_Carrot"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Carrot:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Charredskull"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Dandelion"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Dandelion:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Plant"), ["Pickable_DolmenTreasure"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Coins:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_DragonEgg"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "DragonEgg:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_DvergrLantern"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_DvergrMineTreasure"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_DvergrStein"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Fiddlehead"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Fishingrod"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Flax"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Flax:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Flax_Wild"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Flax:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Flint"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Flint:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_ForestCryptRemains01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_ForestCryptRemains02"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_ForestCryptRemains03"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_ForestCryptRemains04"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Hairstrands01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Hairstrands02"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_HardRockOffspring"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Item"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, "Coins (pickable)", null, "Treasure"), ["Pickable_MeatPile"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Meteorite"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_MoltenCoreStand"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_MountainCaveCrystal"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_MountainCaveObsidian"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_MountainRemains01_buried"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Mushroom"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Mushroom:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Plant"), ["Pickable_Mushroom_blue"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "MushroomBlue:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Plant"), ["Pickable_Mushroom_JotunPuffs"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "MushroomJotunPuffs:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Mushroom_Magecap"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "MushroomMagecap:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Mushroom_yellow"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "MushroomYellow:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Plant"), ["Pickable_Obsidian"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Obsidian:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_Onion"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Obsidian:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_Pot_Shard"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_RoyalJelly"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_SeedCarrot"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_SeedOnion"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_SeedTurnip"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_SmokePuff"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Stone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_StoneRock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_SulfurRock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_SurtlingCoreStand"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "CreatorShop", "Forge", "Iron:2;SurtlingCore:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Treasure"), ["Pickable_Swordpiece1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Swordpiece2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Swordpiece3"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Pickable_Tar"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Tar:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_TarBig"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pickable_Thistle"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Thistle:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Plant"), ["Pickable_Tin"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "TinOre:1", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["Pickable_Turnip"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Turnip:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "VanillaCrop"), ["Pickable_VoltureEgg"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["piece_blackwood_bench"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Workbench", "Blackwood:6", clipEverything: false, clipGround: false, placementPatch: true, null, null, "Chair"), ["piece_Charred_Balista"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_dvergr_pole"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:1", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr wood pole", null, "Dvergr"), ["piece_dvergr_wood_door"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:16;IronNails:24", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["piece_dvergr_wood_wall"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "BlackForge", "YggdrasilWood:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Dvergr"), ["piece_pot1_cracked"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_pot1_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_pot2_cracked"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_pot2_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_pot3_cracked"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["piece_pot3_red"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["PineTree"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pinetree_01"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:10;RoundLog:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["Pinetree_01_Stub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:5;RoundLog:5", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["PineTree_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:10;RoundLog:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["PineTree_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Wood:5;RoundLog:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["portal"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "GaldrTable", "GreydwarfEye:10;Stone:20;BlackCore:2", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr portal", "Connects another portal with equal or no tag.", "Portal"), ["RaspberryBush"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Raspberry:5", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Plant"), ["Rock_3"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_3_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_4"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_4_plains"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_7"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_destructible"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["Rock_destructible_test"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock_mistlands1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:48", clipEverything: true, clipGround: false, placementPatch: false, "Rock (black)", null, "Rock"), ["rock_mistlands1_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:48", clipEverything: true, clipGround: false, placementPatch: false, "Rock (black)", null, "Rock"), ["rock_mistlands2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:48", clipEverything: true, clipGround: false, placementPatch: false, "Rock (black, alt)", null, "Rock"), ["rock1_mistlands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, "Rock (large boulder)", null, "Rock"), ["rock1_mountain"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock1_mountain_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock2_heath"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock2_heath_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock2_mountain"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock2_mountain_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock3_ice"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock3_ice_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Crystal:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock3_mountain"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:100", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock3_mountain_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:100", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock3_silver"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64;SilverOre:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["rock3_silver_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64;SilverOre:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["rock4_ashlands_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["rock4_bigrock_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["rock4_coast"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock4_coast_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock4_copper"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64;CopperOre:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["rock4_copper_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: true, placementPatch: false, null, null, "Ore"), ["rock4_forest"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock4_forest_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:64", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock4_heath"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["rock4_heath_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["RockDolmen_1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:75", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["RockDolmen_2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:50", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["RockDolmen_3"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:75", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["RockFinger"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["RockFinger_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["RockFingerBroken"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:175", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["RockFingerBroken_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:175", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["rockformation1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:350", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["RockThumb"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:200", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["RockThumb_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:200", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["root07"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:2", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["root08"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:4", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["root11"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:4", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["root12"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:4", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["rug_bogwitch_deer"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["rug_bogwitch_fur"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["rug_bogwitch_wolf"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["rug_straw"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Rug"), ["SeekerEgg"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["SeekerEgg_alwayshatch"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["SeekerQueen_spithit"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["shieldgenerator_attack"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["shipwreck_karve_bottomboards"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "FineWood:8", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["shipwreck_karve_bow"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "FineWood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["shipwreck_karve_dragonhead"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "FineWood:8", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["shipwreck_karve_stern"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "FineWood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["shipwreck_karve_sternpost"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "FineWood:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["ShootStump"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["shrub_2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["shrub_2_heath"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["siege_wall_1x1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "Stonecutter", "Grausten:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["sign_notext"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1", clipEverything: false, clipGround: false, placementPatch: false, "Wood plank", "", "Wood"), ["silvervein"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:50;SilverOre:50", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["silvervein_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Stone:50;SilverOre:50", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Ore"), ["Skull1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "CreatorShop", "None", "TrophySkeleton:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["Skull2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["smokebomb_explosion"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["StatueCorgi"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Statue"), ["StatueDeer"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Statue"), ["StatueEvil"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Statue"), ["StatueHare"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:24", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Statue"), ["StatueSeed"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Statue"), ["stone_floor"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "Stone:16", clipEverything: false, clipGround: true, placementPatch: false, "Stone floor 4x4", null, "Stone"), ["stoneblock_fracture"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingStonecutter", "Stonecutter", "Stone:16", clipEverything: false, clipGround: true, placementPatch: false, "Stone floor 4x4 (2)", null, "Stone"), ["stubbe"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["stubbe_spawner"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["sunken_crypt_gate"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "BuildingStonecutter", "Forge", "Iron:4", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Iron"), ["SwampTree1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["SwampTree1_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["SwampTree1_Stub"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["SwampTree2"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["SwampTree2_darkland"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["SwampTree2_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "ElderBark:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["tarlump1"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Tar:50", clipEverything: true, clipGround: false, placementPatch: false, "Crystallized tar", "Warning: requires devcommands to remove", "None"), ["tarlump1_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "Tar:50", clipEverything: true, clipGround: false, placementPatch: false, "Crystallized tar", null, "None"), ["TESTTOWER"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["trader_wagon_destructable"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "FineWood:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["Trailership"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Misc", "Workbench", "BlackMetal:5;LoxPelt:10;FineWood:20;IronNails:40", clipEverything: false, clipGround: false, placementPatch: false, "Trader ship", null, "Ship"), ["TreasureChest_ashland_stone"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chest"), ["TreasureChest_charredfortress"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Chest"), ["TreasureChest_dvergr_loose_stone"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "BlackMarble:10", clipEverything: false, clipGround: false, placementPatch: false, "Black marble chest", null, "Chest"), ["TreasureChest_dvergrtower"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:10;Copper:2", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr chest", null, "Chest"), ["TreasureChest_dvergrtown"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "BlackForge", "YggdrasilWood:10;Copper:6", clipEverything: false, clipGround: false, placementPatch: false, "Dvergr chest (large)", null, "Chest"), ["TreasureChest_fCrypt"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:10;RoundLog:1", clipEverything: false, clipGround: false, placementPatch: false, "Stone chest (mossy)", null, "Chest"), ["TreasureChest_mountaincave"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:10;Crystal:1", clipEverything: false, clipGround: false, placementPatch: false, "Stone chest (snow)", null, "Chest"), ["TreasureChest_sunkencrypt"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:10;ElderBark:1", clipEverything: false, clipGround: false, placementPatch: false, "Stone chest (dark moss)", null, "Chest"), ["TreasureChest_trollcave"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Furniture", "Stonecutter", "Stone:10;RoundLog:2", clipEverything: false, clipGround: false, placementPatch: false, "Stone chest (mossy, big)", null, "Chest"), ["tunnel_web"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["turf_roof"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Wood"), ["turf_roof_top"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Wood"), ["UnstableLavaRock"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["veg_skull_Ashlands"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: true, null, null, "None"), ["vertical_web"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "None"), ["vfx_Burning"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Cold"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_darkland_groundfog"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_edge_clouds"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Freezing"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Frost"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_GoblinShield"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_mistlands_mist"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_ocean_clouds"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Smoked"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_StaffShield"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_swamp_mist"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Tared"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_TrollPheromones"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_UndeadBurn"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["vfx_Wet"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Effect", "None", "", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Effect"), ["VineAsh"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["VineGreen"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["vines"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Wood:2", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["volture_strawpile"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "CreatorShop", "None", "", clipEverything: false, clipGround: false, placementPatch: false, null, null, "None"), ["widestone"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["widestone_frac"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "Stone:32", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Rock"), ["wood_ledge"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "BuildingWorkbench", "Workbench", "Wood:1", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Wood"), ["yggashoot_log"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["yggashoot_log_half"] = new MvbpPrefabDefault(enabled: false, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["YggaShoot_small1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:10", clipEverything: false, clipGround: false, placementPatch: false, null, null, "Flora"), ["YggaShoot1"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["YggaShoot2"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["YggaShoot3"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:16", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora"), ["YggdrasilRoot"] = new MvbpPrefabDefault(enabled: true, allowedInDungeons: false, "Nature", "None", "YggdrasilWood:64;Sap:10", clipEverything: true, clipGround: false, placementPatch: false, null, null, "Flora") }; public static IEnumerable Names => Defaults.Keys; public static bool HasDefault(string prefabName) { return Defaults.ContainsKey(prefabName); } public static bool IsRuntimeEffect(string prefabName) { string text = HarnessPrefabsRuntime.NormalizePrefabName(prefabName); if (text.Length > 0 && Defaults.TryGetValue(text, out var value)) { if (!(value.Category == "Effect")) { return value.PieceGroup == "Effect"; } return true; } return false; } public static bool NeedsPlacementPatch(string prefabName) { string text = HarnessPrefabsRuntime.NormalizePrefabName(prefabName); if (text.Length > 0 && Defaults.TryGetValue(text, out var value)) { return value.PlacementPatch; } return false; } public static string GetPieceGroup(string prefabName) { string text = HarnessPrefabsRuntime.NormalizePrefabName(prefabName); if (text.Length <= 0 || !Defaults.TryGetValue(text, out var value)) { return ""; } return value.PieceGroup; } public static bool TryCreateRule(PrefabDiscovery discovery, out PrefabRule rule) { rule = null; if (!Defaults.TryGetValue(discovery.Name, out var value)) { return false; } PrefabAccess prefabAccess = ResolveAccess(discovery, value); rule = new PrefabRule { Access = prefabAccess, Category = ResolveCategory(discovery.Name, value, prefabAccess), DisplayName = ((prefabAccess == PrefabAccess.Public) ? ResolvePublicDisplayName(discovery, value) : ""), Description = ((prefabAccess == PrefabAccess.Public) ? ResolvePublicDescription(discovery, value) : ""), CraftingStation = value.CraftingStation, Requirements = PrefabRequirementParser.ParseMany(value.Requirements), ClipEverything = value.ClipEverything, ClipGround = value.ClipGround, AllowedInDungeons = value.AllowedInDungeons, CanBeRemoved = ResolveCanBeRemoved(value), Components = NormalizeComponents(discovery.Components) }; return true; } private static bool ResolveCanBeRemoved(MvbpPrefabDefault seed) { return !seed.PieceGroup.Equals("Ship", StringComparison.OrdinalIgnoreCase); } private static string ResolvePublicDisplayName(PrefabDiscovery discovery, MvbpPrefabDefault seed) { return seed.DisplayName ?? FormatMvbpPieceName(discovery.Name); } private static string FormatMvbpPieceName(string prefabName) { string value = RemoveSuffix(prefabName, "_frac"); value = RemoveSuffix(value, "_destruction"); value = CreepToEndRegex.Replace(value, "$1$3 ($2)"); value = DigitsToEndRegex.Replace(value, "$1$3 $2"); value = UnitSpaceRegex.Replace(value, "$1 $2"); value = SplitCapitalsRegex.Replace(value, "$1 $2"); value = value.Replace('_', ' ').ToLowerInvariant().Replace("dverger", "dvergr") .Replace("dvergrtown", "dvergr") .Replace("dvergrprops", "dvergr") .Replace("destructable", "destructible") .Replace("rockdolmen", "rock dolmen") .Replace("blackmarble", "black marble") .Replace("sunkencrypt", "sunken crypt") .Replace("irongate", "iron gate") .Replace("goblin", "fuling") .Replace("hugeroot", "ancient root") .Replace("stubbe", "stump") .Replace("stub", "stump") .Replace("swamptree", "Ancient tree") .Replace("swamp tree", "Ancient tree") .Replace("ygga", "yggdrasil ") .Replace("guardstone", "ward") .Replace("woodwall", "wood wall") .Trim(); value = RemovePrefix(value, "piece").TrimStart(Array.Empty()); value = RemovePrefix(value, "dungeon").TrimStart(Array.Empty()); if (value.EndsWith("destructible", StringComparison.Ordinal)) { value = RemoveSuffix(value, "destructible") + " (destructible)"; } if (value.StartsWith("pickable", StringComparison.Ordinal)) { value = RemovePrefix(value, "pickable").TrimStart(Array.Empty()) + " (pickable)"; } if (StartsWithAny(value, "mountainkit", "mountain kit")) { value = RemovePrefix(value, "mountainkit"); value = RemovePrefix(value, "mountain kit").TrimStart(Array.Empty()) + " (cave)"; } if (StartsWithAny(value, "sunkencrypt", "sunken crypt")) { value = RemovePrefix(value, "sunkencrypt"); value = RemovePrefix(value, "sunken crypt").TrimStart(Array.Empty()) + " (crypt)"; } if (StartsWithAny(value, "forestcrypt", "forest crypt")) { value = RemovePrefix(value, "forestcrypt"); value = RemovePrefix(value, "forest crypt").TrimStart(Array.Empty()) + " (tomb)"; } if (value.EndsWith("26", StringComparison.Ordinal) || value.EndsWith("45", StringComparison.Ordinal)) { value += "°"; } value = IsLastCharDigitRegex.Replace(value, " ($1)"); value = WhiteSpaceRegex.Replace(value, " "); return EnglishTextInfo.ToTitleCase(value); } private static string RemovePrefix(string value, string prefix) { if (!value.StartsWith(prefix, StringComparison.Ordinal)) { return value; } return value.Substring(prefix.Length); } private static string RemoveSuffix(string value, string suffix) { if (!value.EndsWith(suffix, StringComparison.Ordinal)) { return value; } return value.Substring(0, value.Length - suffix.Length); } private static bool StartsWithAny(string value, string first, string second) { if (!value.StartsWith(first, StringComparison.Ordinal)) { return value.StartsWith(second, StringComparison.Ordinal); } return true; } private static string ResolvePublicDescription(PrefabDiscovery discovery, MvbpPrefabDefault seed) { if (seed.Description != null) { return seed.Description; } return FindMvbpPieceDescription(discovery.Prefab); } private static string FindMvbpPieceDescription(GameObject? prefab, HashSet? visited = null) { if (!Object.op_Implicit((Object)(object)prefab)) { return ""; } if (visited == null) { visited = new HashSet(StringComparer.Ordinal); } if (!visited.Add(((Object)prefab).name)) { return ""; } HoverText component = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component) && !string.IsNullOrEmpty(component.m_text)) { return component.m_text; } ItemDrop component2 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component2)) { string text = component2.m_itemData?.m_shared?.m_name; if (text != null && text.Length > 0) { return text; } } Character component3 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component3) && !string.IsNullOrEmpty(component3.m_name)) { return component3.m_name; } RuneStone component4 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component4) && !string.IsNullOrEmpty(component4.m_name)) { return component4.m_name; } ItemStand component5 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component5) && !string.IsNullOrEmpty(component5.m_name)) { return component5.m_name; } MineRock component6 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component6) && !string.IsNullOrEmpty(component6.m_name)) { return component6.m_name; } Pickable component7 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component7) && Object.op_Implicit((Object)(object)component7.m_itemPrefab)) { return FindMvbpPieceDescription(component7.m_itemPrefab, visited); } CreatureSpawner component8 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component8) && Object.op_Implicit((Object)(object)component8.m_creaturePrefab)) { return FindMvbpPieceDescription(component8.m_creaturePrefab, visited); } SpawnArea component9 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component9) && component9.m_prefabs.Count > 0 && Object.op_Implicit((Object)(object)component9.m_prefabs[0].m_prefab)) { return FindMvbpPieceDescription(component9.m_prefabs[0].m_prefab, visited); } return ""; } private static PrefabAccess ResolveAccess(PrefabDiscovery discovery, MvbpPrefabDefault seed) { if (discovery.Access == PrefabAccess.Hidden) { return PrefabAccess.Hidden; } if (IsAdminOnlyCategory(seed.Category)) { return PrefabAccess.Admin; } if (!seed.Enabled) { return PrefabAccess.Admin; } return PrefabAccess.Public; } private static string ResolveCategory(string prefabName, MvbpPrefabDefault seed, PrefabAccess access) { if (access == PrefabAccess.Public) { return MapPublicCategory(seed.Category); } return MapAdminCategory(prefabName, seed); } private static string MapPublicCategory(string category) { return category switch { "BuildingWorkbench" => "Building", "BuildingStonecutter" => "BuildingStonecutter", "Furniture" => "Furniture", "Misc" => "Misc", "Crafting" => "Crafting", _ => "Misc", }; } private static string MapAdminCategory(string prefabName, MvbpPrefabDefault seed) { if (seed.Category == "Effect" || seed.PieceGroup == "Effect") { return "Harness Props"; } if (seed.Category == "Nature" || IsNatureGroup(seed.PieceGroup)) { return "Harness Nature"; } if (IsInteractiveGroup(seed.PieceGroup)) { return "Harness Structures"; } bool flag = IsStructureGroup(seed.PieceGroup); if (!flag) { string category = seed.Category; bool flag2 = ((category == "BuildingWorkbench" || category == "BuildingStonecutter") ? true : false); flag = flag2; } if (flag || IsStructureName(prefabName) || IsStructureStation(seed.CraftingStation)) { return "Harness Structures"; } if (!IsPropGroup(seed.PieceGroup) && !(seed.Category == "CreatorShop")) { _ = seed.Category == "Furniture"; } return "Harness Props"; } private static bool IsAdminOnlyCategory(string category) { if (!(category == "CreatorShop") && !(category == "Effect")) { return category == "Nature"; } return true; } private static bool IsNatureGroup(string group) { switch (group) { case "Flora": case "Plant": case "Rock": case "Ore": case "Ice": case "VanillaCrop": return true; default: return false; } } private static bool IsInteractiveGroup(string group) { switch (group) { case "Chest": case "Torch": case "Fire": case "Ship": case "ArmorStand": case "Bed": case "Brazier": case "Portal": return true; default: return false; } } private static bool IsStructureGroup(string group) { switch (group) { case "Dvergr": case "Goblin": case "Iron": case "Wood": case "BlackMarble": case "Ice": case "Stone": return true; default: return false; } } private static bool IsPropGroup(string group) { switch (group) { case "Banner": case "Statue": case "Chair": case "Table": case "Misc": case "Rug": case "Treasure": return true; default: return false; } } private static bool IsStructureStation(string station) { if (station == "BlackForge" || station == "Stonecutter") { return true; } return false; } private static bool IsStructureName(string prefabName) { string text = prefabName.ToLowerInvariant(); return new string[19] { "arch", "beam", "bridge", "column", "corner", "door", "floor", "fortress", "foundation", "gate", "pillar", "pole", "railing", "ramp", "roof", "ruin", "stair", "steepstair", "wall" }.Any(text.Contains); } private static ComponentList NormalizeComponents(IEnumerable components) { return new ComponentList((from component in components where !string.IsNullOrWhiteSpace(component) select component.Trim() into component where !component.StartsWith("MVBP", StringComparison.Ordinal) select component).Distinct(StringComparer.Ordinal).OrderBy((string component) => component, StringComparer.OrdinalIgnoreCase)); } } public enum PrefabAccess { Hidden, Public, Admin } internal static class BuildCategories { public const string Misc = "Misc"; public const string Crafting = "Crafting"; public const string Building = "Building"; public const string Stonecutter = "BuildingStonecutter"; public const string Furniture = "Furniture"; public const string HarnessProps = "Harness Props"; public const string HarnessNature = "Harness Nature"; public const string HarnessStructures = "Harness Structures"; private static readonly Dictionary CanonicalNames = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["Misc"] = "Misc", ["Crafting"] = "Crafting", ["Building"] = "Building", ["BuildingWorkbench"] = "Building", ["BuildingStonecutter"] = "BuildingStonecutter", ["Stonecutter"] = "BuildingStonecutter", ["Furniture"] = "Furniture", ["Harness Props"] = "Harness Props", ["Harness Nature"] = "Harness Nature", ["Harness Structures"] = "Harness Structures" }; public static bool IsAdminCategory(string categoryName) { if (string.IsNullOrWhiteSpace(categoryName)) { return false; } switch (NormalizeCategory(categoryName)) { case "Harness Props": case "Harness Nature": case "Harness Structures": return true; default: return false; } } public static string NormalizeCategory(string categoryName) { if (string.IsNullOrWhiteSpace(categoryName)) { return "Harness Props"; } string text = categoryName.Trim(); if (!CanonicalNames.TryGetValue(text, out string value)) { return text; } return value; } } internal static class PrefabSortPolicy { public static IEnumerable SortForHammer(IEnumerable discoveries) { return from entry in (from discovery in discoveries select (Discovery: discovery, Key: CreateSortKey(discovery)) into entry orderby entry.Key.CategoryOrder select entry).ThenBy<(PrefabDiscovery, (int, string, int, string, string)), string>(((PrefabDiscovery Discovery, (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) Key) entry) => entry.Key.CategoryName, StringComparer.OrdinalIgnoreCase).ThenBy<(PrefabDiscovery, (int, string, int, string, string)), int>(((PrefabDiscovery Discovery, (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) Key) entry) => entry.Key.BucketOrder).ThenBy<(PrefabDiscovery, (int, string, int, string, string)), string>(((PrefabDiscovery Discovery, (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) Key) entry) => entry.Key.BucketName, StringComparer.OrdinalIgnoreCase) .ThenBy<(PrefabDiscovery, (int, string, int, string, string)), string>(((PrefabDiscovery Discovery, (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) Key) entry) => entry.Key.DisplayName, StringComparer.OrdinalIgnoreCase) .ThenBy<(PrefabDiscovery, (int, string, int, string, string)), string>(((PrefabDiscovery Discovery, (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) Key) entry) => entry.Discovery.Name, StringComparer.Ordinal) select entry.Discovery; } private static (int CategoryOrder, string CategoryName, int BucketOrder, string BucketName, string DisplayName) CreateSortKey(PrefabDiscovery discovery) { PrefabRule rule; bool flag = PrefabRuleStore.TryGetRule(discovery.Name, out rule); string text = BuildCategories.NormalizeCategory(flag ? rule.Category : discovery.Category); ComponentList components2; if (flag) { ComponentList components = rule.Components; if (components != null && components.Count > 0) { components2 = rule.Components; goto IL_004c; } } components2 = discovery.Components; goto IL_004c; IL_004c: ComponentList components3 = components2; string pieceGroup = MvbpPrefabDefaults.GetPieceGroup(discovery.Name); string lower = discovery.Name.ToLowerInvariant(); (int, string) tuple; switch (text) { case "Crafting": tuple = GetCraftingBucket(components3, lower); break; case "Building": case "BuildingStonecutter": case "Harness Structures": tuple = GetStructureBucket(components3, pieceGroup, lower); break; case "Furniture": case "Harness Props": tuple = GetPropBucket(components3, pieceGroup, lower); break; case "Harness Nature": tuple = GetNatureBucket(components3, pieceGroup, lower); break; default: tuple = GetGeneralBucket(components3); break; } (int, string) tuple2 = tuple; string item = ((flag && !string.IsNullOrWhiteSpace(rule.DisplayName)) ? rule.DisplayName.Trim() : discovery.Name); return (CategoryOrder: GetCategoryOrder(text), CategoryName: text, BucketOrder: tuple2.Item1, BucketName: tuple2.Item2, DisplayName: item); } private static int GetCategoryOrder(string category) { return category switch { "Misc" => 10, "Crafting" => 20, "Building" => 30, "BuildingStonecutter" => 40, "Furniture" => 50, "Harness Nature" => 110, "Harness Structures" => 120, "Harness Props" => 130, _ => 1000, }; } private static (int Order, string Name) GetCraftingBucket(IReadOnlyCollection components, string lower) { if (components.Contains("CraftingStation")) { return (Order: 10, Name: "CraftingStation"); } if (components.Contains("StationExtension")) { return (Order: 20, Name: "StationExtension"); } if (components.Contains("CookingStation")) { return (Order: 30, Name: "CookingStation"); } if (components.Contains("Smelter")) { return (Order: 40, Name: "Smelter"); } if (components.Contains("Fireplace") || lower.Contains("fire")) { return (Order: 50, Name: "Fire"); } return GetGeneralBucket(components); } private static (int Order, string Name) GetInteractiveBucket(IReadOnlyCollection components, string group, string lower) { if (components.Contains("Container") || group == "Chest" || lower.Contains("chest")) { return (Order: 10, Name: "Container"); } if (components.Contains("CraftingStation") || components.Contains("StationExtension")) { return (Order: 20, Name: "Crafting"); } if (components.Contains("CookingStation") || components.Contains("Smelter")) { return (Order: 30, Name: "Processing"); } bool flag = components.Contains("Fireplace"); if (!flag) { bool flag2; switch (group) { case "Fire": case "Brazier": case "Torch": flag2 = true; break; default: flag2 = false; break; } flag = flag2; } if (flag) { return (Order: 40, Name: "Fire"); } if (components.Contains("TeleportWorld") || group == "Portal") { return (Order: 50, Name: "Portal"); } if (components.Contains("Door") || lower.Contains("door") || lower.Contains("gate")) { return (Order: 60, Name: "Door"); } if (components.Contains("Bed") || group == "Bed") { return (Order: 70, Name: "Bed"); } if (components.Contains("Ship") || components.Contains("Vagon") || group == "Ship") { return (Order: 80, Name: "Vehicle"); } if (components.Contains("ArmorStand") || group == "ArmorStand") { return (Order: 90, Name: "ArmorStand"); } if (components.Contains("PrivateArea")) { return (Order: 100, Name: "PrivateArea"); } return (Order: 1000, Name: ""); } private static (int Order, string Name) GetNatureBucket(IReadOnlyCollection components, string group, string lower) { bool flag = components.Contains("Plant"); if (!flag) { bool flag2 = ((group == "Plant" || group == "VanillaCrop") ? true : false); flag = flag2; } if (flag) { return (Order: 10, Name: "Plant"); } if (components.Contains("Pickable")) { return (Order: 20, Name: "Pickable"); } if (components.Contains("TreeBase") || lower.Contains("tree")) { return (Order: 30, Name: "Tree"); } if (components.Contains("TreeLog") || lower.Contains("log")) { return (Order: 40, Name: "TreeLog"); } flag = components.Contains("MineRock") || components.Contains("MineRock5"); if (!flag) { bool flag2; switch (group) { case "Rock": case "Ore": case "Ice": flag2 = true; break; default: flag2 = false; break; } flag = flag2; } if (flag) { return (Order: 50, Name: "RockOre"); } if (group == "Flora" || ContainsAny(lower, "bush", "fern", "grass", "reed", "moss", "vine", "root")) { return (Order: 60, Name: "Flora"); } if (ContainsAny(lower, "rock", "cliff", "stoneformation")) { return (Order: 70, Name: "RockStatic"); } return GetGeneralBucket(components); } private static (int Order, string Name) GetStructureBucket(IReadOnlyCollection components, string group, string lower) { if (ContainsAny(lower, "floor", "foundation")) { return (Order: 10, Name: "Floor"); } if (ContainsAny(lower, "wall", "window")) { return (Order: 20, Name: "Wall"); } if (ContainsAny(lower, "roof")) { return (Order: 30, Name: "Roof"); } if (ContainsAny(lower, "stair", "ramp")) { return (Order: 40, Name: "StairRamp"); } if (ContainsAny(lower, "beam", "pole", "pillar", "column")) { return (Order: 50, Name: "Support"); } if (ContainsAny(lower, "arch", "bridge", "ruin", "fortress")) { return (Order: 60, Name: "Shell"); } if (ContainsAny(lower, "gate", "door")) { return (Order: 70, Name: "GateDoor"); } (int, string) interactiveBucket = GetInteractiveBucket(components, group, lower); if (interactiveBucket.Item1 < 1000) { return (Order: 100 + interactiveBucket.Item1, Name: "Interactive" + interactiveBucket.Item2); } if (components.Contains("Destructible")) { return (Order: 220, Name: "Destructible"); } if (components.Contains("WearNTear")) { return (Order: 230, Name: "WearNTear"); } if (components.Contains("Piece")) { return (Order: 240, Name: "Piece"); } if (!string.IsNullOrWhiteSpace(group) && group != "None") { return (Order: 250, Name: group); } return GetGeneralBucket(components); } private static (int Order, string Name) GetPropBucket(IReadOnlyCollection components, string group, string lower) { if (components.Contains("InstanceRenderer")) { return (Order: 5, Name: "InstanceRenderer"); } if (components.Contains("Chair") || group == "Chair") { return (Order: 10, Name: "Chair"); } if (components.Contains("ArmorStand") || group == "ArmorStand") { return (Order: 20, Name: "ArmorStand"); } if (group == "Table" || lower.Contains("table")) { return (Order: 30, Name: "Table"); } if (group == "Banner" || lower.Contains("banner")) { return (Order: 40, Name: "Banner"); } if (group == "Rug" || lower.Contains("rug")) { return (Order: 50, Name: "Rug"); } if (group == "Statue" || lower.Contains("statue")) { return (Order: 60, Name: "Statue"); } if (group == "Treasure" || ContainsAny(lower, "treasure", "coin", "chest")) { return (Order: 70, Name: "Treasure"); } if (ContainsAny(lower, "barrel", "barrell", "crate", "pot", "jar")) { return (Order: 80, Name: "ContainerProp"); } if (!string.IsNullOrWhiteSpace(group) && group != "None") { string item = (lower.Contains("clutter") ? "Clutter" : (ContainsAny(lower, "frac", "fragment", "broken") ? "Fragment" : ((lower.Contains("_lod") || lower.EndsWith("lod", StringComparison.Ordinal)) ? "LOD" : group))); return (Order: 90, Name: item); } if (lower.Contains("clutter")) { return (Order: 100, Name: "Clutter"); } if (ContainsAny(lower, "frac", "fragment", "broken")) { return (Order: 110, Name: "Fragment"); } if (lower.Contains("_lod") || lower.EndsWith("lod", StringComparison.Ordinal)) { return (Order: 120, Name: "LOD"); } return GetGeneralBucket(components); } private static (int Order, string Name) GetGeneralBucket(IReadOnlyCollection components) { int item = (components.Contains("Piece") ? 10 : (components.Contains("WearNTear") ? 20 : (components.Contains("Destructible") ? 30 : (components.Contains("ParticleSystem") ? 40 : 1000)))); string item2 = ((components.Count > 0) ? components.OrderBy((string component) => component, StringComparer.OrdinalIgnoreCase).First() : "Static"); return (Order: item, Name: item2); } private static bool ContainsAny(string value, params string[] tokens) { return tokens.Any(value.Contains); } } internal static class PrefabBuildManager { private static readonly HashSet AddedPrefabs = new HashSet(); private static readonly HashSet AddedAdminPieceNames = new HashSet(StringComparer.Ordinal); private static bool _jotunnPiecesRegistered; private static bool _refreshing; private static bool? _lastHarnessHammerTabsEnabled; private static bool _hasCompletedFullRefresh; private static string _lastFullRefreshSignature = ""; public static void MarkJotunnPiecesRegistered() { _jotunnPiecesRegistered = true; } public static void RefreshIfHarnessHammerVisibilityChanged() { bool harnessHammerTabsEnabled = HarnessPrefabsPlugin.HarnessHammerTabsEnabled; if (!_lastHarnessHammerTabsEnabled.HasValue || _lastHarnessHammerTabsEnabled.Value != harnessHammerTabsEnabled) { RefreshFromCachedRules("harness hammer visibility changed"); } } public static void Refresh(string reason) { if (_refreshing || !Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ObjectDB.instance) || !_jotunnPiecesRegistered) { return; } PieceTable hammerPieceTable = GetHammerPieceTable(); if (!Object.op_Implicit((Object)(object)hammerPieceTable)) { return; } string text = BuildFullRefreshSignature(hammerPieceTable); if (_hasCompletedFullRefresh && PrefabRuleStore.HasCachedDiscoveries && string.Equals(_lastFullRefreshSignature, text, StringComparison.Ordinal)) { RefreshFromCachedRules(reason + "; full discovery skipped"); return; } _refreshing = true; Stopwatch stopwatch = Stopwatch.StartNew(); long num = 0L; long num2 = 0L; long num3 = 0L; long num4 = 0L; int existingBuildableCount = 0; int discoveryCount = 0; try { HarnessPrefabsPlugin.EnsureSourceOfTruthFileMode(); num = stopwatch.ElapsedMilliseconds; HashSet hashSet = CollectExistingBuildables(); existingBuildableCount = hashSet.Count; num2 = stopwatch.ElapsedMilliseconds; List list = PrefabClassifier.Discover(CollectScenePrefabs(), hashSet); discoveryCount = list.Count; num3 = stopwatch.ElapsedMilliseconds; PrefabRuleStore.LoadRulesForCurrentAuthority(list); num4 = stopwatch.ElapsedMilliseconds; ApplyActiveRulesToHammer(hammerPieceTable, list, reason); _lastFullRefreshSignature = text; _hasCompletedFullRefresh = true; } catch (Exception arg) { HarnessPrefabsPlugin.Log.LogError((object)$"Prefab refresh failed ({reason}): {arg}"); } finally { stopwatch.Stop(); LogRefreshProfile(reason, stopwatch.ElapsedMilliseconds, num, num2 - num, num3 - num2, num4 - num3, stopwatch.ElapsedMilliseconds - num4, existingBuildableCount, discoveryCount); _refreshing = false; } } public static void RefreshFromCachedRules(string reason) { if (_refreshing) { return; } if (!PrefabRuleStore.HasCachedDiscoveries) { Refresh(reason + "; full discovery fallback"); } else { if (!Object.op_Implicit((Object)(object)ZNetScene.instance) || !Object.op_Implicit((Object)(object)ObjectDB.instance) || !_jotunnPiecesRegistered) { return; } PieceTable hammerPieceTable = GetHammerPieceTable(); if (!Object.op_Implicit((Object)(object)hammerPieceTable)) { return; } _refreshing = true; Stopwatch stopwatch = Stopwatch.StartNew(); try { ApplyActiveRulesToHammer(hammerPieceTable, PrefabRuleStore.LastDiscoveries, reason); } catch (Exception arg) { HarnessPrefabsPlugin.Log.LogError((object)$"Prefab cached-rule refresh failed ({reason}): {arg}"); } finally { stopwatch.Stop(); LogCachedRefreshProfile(reason, stopwatch.ElapsedMilliseconds, PrefabRuleStore.LastDiscoveries.Count); _refreshing = false; } } } public static void PreparePieceTableForUpdate(PieceTable table, HashSet knownRecipes) { if (!Object.op_Implicit((Object)(object)table)) { return; } if (!IsHammerPieceTable(table)) { RemoveAddedPiecesFromTable(table); RemoveAdminCategoryTabs(table); PrefabCategoryRegistry.EnsureGrown(table); return; } PrefabCategoryRegistry.EnsureGrown(table); if (!HarnessPrefabsPlugin.HarnessHammerTabsEnabled) { RemoveAdminCategoryTabs(table); } if (knownRecipes == null) { return; } foreach (string addedAdminPieceName in AddedAdminPieceNames) { knownRecipes.Add(addedAdminPieceName); } } private static void ApplyActiveRulesToHammer(PieceTable hammer, IReadOnlyCollection discoveries, string reason) { _lastHarnessHammerTabsEnabled = HarnessPrefabsPlugin.HarnessHammerTabsEnabled; RemoveAddedPieces(hammer); RemoveAdminCategoryTabs(hammer); PrefabPlacementPatchRegistry.Clear(); int num = 0; int num2 = 0; int num3 = 0; foreach (PrefabDiscovery item in PrefabSortPolicy.SortForHammer(discoveries)) { if (!PrefabRuleStore.TryGetRule(item.Name, out PrefabRule rule)) { continue; } switch (rule.Access) { case PrefabAccess.Hidden: num3++; continue; case PrefabAccess.Admin: if (!HarnessPrefabsPlugin.HarnessHammerTabsEnabled) { num2++; continue; } num2++; break; case PrefabAccess.Public: num++; break; } PrefabPlacementPatchRegistry.Set(item.Name, MvbpPrefabDefaults.NeedsPlacementPatch(item.Name), MvbpCompatibilityDefaults.GetPlacementOffset(item.Name)); if (!Object.op_Implicit((Object)(object)item.Prefab)) { continue; } try { if (TryAddPrefabToHammer(item.Prefab, rule, hammer)) { AddedPrefabs.Add(item.Prefab); } } catch (Exception arg) { HarnessPrefabsPlugin.Log.LogError((object)$"Prefab '{item.Name}' materialization failed and will be skipped: {arg}"); } } if (!HarnessPrefabsPlugin.HarnessHammerTabsEnabled) { RemoveAdminCategoryTabs(hammer); } PrefabCategoryRegistry.EnsureGrown(hammer); if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { Player.m_localPlayer.UpdateAvailablePiecesList(); } if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogInfo((object)$"Refresh complete ({reason}). public={num}, admin={num2}, hidden={num3}, visibleAdded={AddedPrefabs.Count}, isAdmin={HarnessPrefabsPlugin.IsAdmin}, debugMode={HarnessPrefabsPlugin.IsDebugMode}"); } } private static bool TryAddPrefabToHammer(GameObject prefab, PrefabRule rule, PieceTable hammer) { if (!Object.op_Implicit((Object)(object)prefab) || !Object.op_Implicit((Object)(object)hammer) || hammer.m_pieces.Contains(prefab)) { return false; } if (!TryResolveRequirements(((Object)prefab).name, rule.Requirements, out var resolvedRequirements) || !TryResolveCraftingStation(((Object)prefab).name, rule.CraftingStation, out var craftingStation)) { return false; } Piece val = EnsurePiece(prefab, rule, hammer, resolvedRequirements, craftingStation); if (!Object.op_Implicit((Object)(object)val)) { return false; } try { PieceManager.Instance.RegisterPieceInPieceTable(prefab, PieceTables.Hammer, (string)null); } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogWarning((object)("Jotunn failed to register prefab '" + ((Object)prefab).name + "' in Hammer table: " + ex.Message)); return false; } if (!hammer.m_pieces.Contains(prefab)) { return false; } if (rule.Access == PrefabAccess.Admin) { AddedAdminPieceNames.Add(val.m_name); } return true; } private static Piece EnsurePiece(GameObject prefab, PrefabRule rule, PieceTable hammer, Requirement[] resources, CraftingStation craftingStation) { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) Piece val = prefab.GetComponent(); if (!Object.op_Implicit((Object)(object)val)) { val = prefab.AddComponent(); } val.m_enabled = true; val.m_name = (string.IsNullOrWhiteSpace(rule.DisplayName) ? ((Object)prefab).name : rule.DisplayName); val.m_description = (string.IsNullOrWhiteSpace(rule.Description) ? "" : rule.Description); val.m_category = PrefabCategoryRegistry.GetOrAdd(hammer, rule.Category); val.m_groundOnly = false; val.m_groundPiece = false; val.m_cultivatedGroundOnly = false; val.m_waterPiece = false; val.m_noInWater = false; val.m_notOnWood = false; val.m_notOnTiltingSurface = false; val.m_inCeilingOnly = false; val.m_notOnFloor = false; val.m_onlyInTeleportArea = false; ApplyPrefabPlacementProfile(prefab, val); val.m_allowedInDungeons = rule.AllowedInDungeons; val.m_clipEverything = rule.ClipEverything; val.m_clipGround = rule.ClipGround; val.m_repairPiece = false; val.m_canBeRemoved = rule.CanBeRemoved; val.m_craftingStation = craftingStation; HarnessPrefabsPlacedPiecePatches.RegisterDefaultResources(prefab, val.m_resources); val.m_resources = resources; ApplyPrefabContainerDefaults(prefab); PrefabMvbpFixups.Apply(prefab); HarnessPrefabsSfxManager.FixPlacementSfx(val); if (!Object.op_Implicit((Object)(object)val.m_icon)) { val.m_icon = ResolveDefaultIcon(); } PrefabIconRenderer.QueueIcon(val); return val; } private static void ApplyPrefabContainerDefaults(GameObject prefab) { if (!MvbpCompatibilityDefaults.TryGetContainerSize(HarnessPrefabsRuntime.NormalizePrefabName(Object.op_Implicit((Object)(object)prefab) ? ((Object)prefab).name : ""), out var width, out var height)) { return; } Container[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Container val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val)) { val.m_width = width; val.m_height = height; } } } private static void ApplyPrefabPlacementProfile(GameObject prefab, Piece piece) { piece.m_allowRotatedOverlap = true; if (HarnessPrefabsRuntime.NormalizePrefabName(Object.op_Implicit((Object)(object)prefab) ? ((Object)prefab).name : "").Equals("Trailership", StringComparison.Ordinal)) { object obj; if (!Object.op_Implicit((Object)(object)ZNetScene.instance)) { obj = null; } else { GameObject prefab2 = ZNetScene.instance.GetPrefab("VikingShip"); obj = ((prefab2 != null) ? prefab2.GetComponent() : null); } Piece val = (Piece)obj; piece.m_waterPiece = !Object.op_Implicit((Object)(object)val) || val.m_waterPiece; piece.m_noClipping = !Object.op_Implicit((Object)(object)val) || val.m_noClipping; piece.m_allowRotatedOverlap = Object.op_Implicit((Object)(object)val) && val.m_allowRotatedOverlap; } } private static bool TryResolveRequirements(string prefabName, IEnumerable requirements, out Requirement[] resolvedRequirements) { //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Expected O, but got Unknown if (requirements == null) { resolvedRequirements = Array.Empty(); return true; } List list = new List(); foreach (PrefabRequirement requirement in requirements) { if (requirement == null || string.IsNullOrWhiteSpace(requirement.Item)) { resolvedRequirements = Array.Empty(); HarnessPrefabsPlugin.Log.LogError((object)("Prefab '" + prefabName + "' has an empty build requirement and will not be registered.")); return false; } string text = requirement.Item.Trim(); int amount = requirement.Amount; if (amount < 1) { resolvedRequirements = Array.Empty(); HarnessPrefabsPlugin.Log.LogError((object)("Prefab '" + prefabName + "' has an invalid amount for requirement '" + text + "' and will not be registered.")); return false; } ItemDrop val = ResolveItemDrop(text); if (!Object.op_Implicit((Object)(object)val)) { resolvedRequirements = Array.Empty(); HarnessPrefabsPlugin.Log.LogError((object)("Prefab '" + prefabName + "' requirement item '" + text + "' could not be resolved. The prefab will not be registered.")); return false; } list.Add(new Requirement { m_resItem = val, m_amount = amount, m_amountPerLevel = amount, m_recover = true }); } resolvedRequirements = list.ToArray(); return true; } private static ItemDrop ResolveItemDrop(string itemName) { GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab(itemName) : null); if (!Object.op_Implicit((Object)(object)val)) { return null; } return val.GetComponent(); } private static bool TryResolveCraftingStation(string prefabName, string stationName, out CraftingStation craftingStation) { craftingStation = null; if (string.IsNullOrWhiteSpace(stationName) || stationName.Equals("None", StringComparison.OrdinalIgnoreCase)) { return true; } string text = stationName.Trim(); string internalName; try { internalName = CraftingStations.GetInternalName(text); } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogError((object)("Prefab '" + prefabName + "' crafting station '" + text + "' is invalid and the prefab will not be registered: " + ex.Message)); return false; } GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? (ZNetScene.instance.GetPrefab(internalName) ?? ZNetScene.instance.GetPrefab(text)) : null); if (!Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)ObjectDB.instance)) { val = ObjectDB.instance.GetItemPrefab(internalName) ?? ObjectDB.instance.GetItemPrefab(text); } craftingStation = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); if (Object.op_Implicit((Object)(object)craftingStation)) { return true; } HarnessPrefabsPlugin.Log.LogError((object)("Prefab '" + prefabName + "' crafting station '" + text + "' could not be resolved. The prefab will not be registered.")); return false; } private static Sprite ResolveDefaultIcon() { try { Sprite prefab = Cache.GetPrefab("mapicon_hildir1"); if (Object.op_Implicit((Object)(object)prefab)) { return prefab; } } catch { } GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab("Hammer") : null); ItemDrop val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); if (val2?.m_itemData?.m_shared?.m_icons != null && val2.m_itemData.m_shared.m_icons.Length != 0) { return val2.m_itemData.m_shared.m_icons[0]; } return null; } private static void RemoveAddedPieces(PieceTable hammer) { RemoveAddedPiecesFromTable(hammer); AddedPrefabs.Clear(); AddedAdminPieceNames.Clear(); } private static void RemoveAddedPiecesFromTable(PieceTable table) { if (!Object.op_Implicit((Object)(object)table) || table.m_pieces == null || AddedPrefabs.Count == 0) { return; } for (int num = table.m_pieces.Count - 1; num >= 0; num--) { GameObject val = table.m_pieces[num]; if (Object.op_Implicit((Object)(object)val) && AddedPrefabs.Contains(val)) { table.m_pieces.RemoveAt(num); } } } private static void RemoveAdminCategoryTabs(PieceTable hammer) { if (!Object.op_Implicit((Object)(object)hammer) || hammer.m_categories == null || hammer.m_categoryLabels == null) { return; } for (int num = hammer.m_categoryLabels.Count - 1; num >= 0; num--) { if (num >= hammer.m_categories.Count) { hammer.m_categoryLabels.RemoveAt(num); } else if (BuildCategories.IsAdminCategory(hammer.m_categoryLabels[num])) { hammer.m_categoryLabels.RemoveAt(num); hammer.m_categories.RemoveAt(num); } } } private static HashSet CollectExistingBuildables() { HashSet hashSet = new HashSet(StringComparer.Ordinal); PieceTable[] array = Resources.FindObjectsOfTypeAll(); foreach (PieceTable val in array) { if (!Object.op_Implicit((Object)(object)val) || val.m_pieces == null) { continue; } foreach (GameObject piece in val.m_pieces) { if (Object.op_Implicit((Object)(object)piece) && !string.IsNullOrWhiteSpace(((Object)piece).name) && !AddedPrefabs.Contains(piece)) { hashSet.Add(((Object)piece).name); } } } return hashSet; } private static IEnumerable CollectScenePrefabs() { HashSet seen = new HashSet(StringComparer.Ordinal); foreach (GameObject item in ZNetScene.instance.m_prefabs.Concat(ZNetScene.instance.m_nonNetViewPrefabs)) { if (Object.op_Implicit((Object)(object)item) && !string.IsNullOrWhiteSpace(((Object)item).name) && seen.Add(((Object)item).name)) { yield return item; } } foreach (GameObject item2 in CollectSeededSoftReferencePrefabs(seen)) { yield return item2; } } private static IEnumerable CollectSeededSoftReferencePrefabs(HashSet seen) { int loadedCount = 0; int missingCount = 0; foreach (string name in MvbpPrefabDefaults.Names) { if (!seen.Contains(name)) { GameObject val = TryResolveSeededSoftReferencePrefab(name); if (!Object.op_Implicit((Object)(object)val) || string.IsNullOrWhiteSpace(((Object)val).name)) { missingCount++; } else if (MvbpPrefabDefaults.HasDefault(((Object)val).name) && seen.Add(((Object)val).name)) { loadedCount++; yield return val; } } } if (HarnessPrefabsPlugin.Verbose && (loadedCount > 0 || missingCount > 0)) { HarnessPrefabsPlugin.Log.LogInfo((object)$"Loaded {loadedCount} MVBP-seeded prefabs from SoftRef fallback. missing={missingCount}"); } } private static GameObject TryResolveSeededSoftReferencePrefab(string prefabName) { try { return Cache.GetPrefab(prefabName); } catch (Exception ex) { if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogWarning((object)("SoftRef fallback failed for '" + prefabName + "': " + ex.Message)); } return null; } } private static PieceTable GetHammerPieceTable() { PieceTable pieceTable = PieceManager.Instance.GetPieceTable(PieceTables.Hammer); if (Object.op_Implicit((Object)(object)pieceTable)) { return pieceTable; } GameObject val = (Object.op_Implicit((Object)(object)ObjectDB.instance) ? ObjectDB.instance.GetItemPrefab("Hammer") : null); return (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null)?.m_itemData?.m_shared?.m_buildPieces; } private static bool IsHammerPieceTable(PieceTable table) { PieceTable hammerPieceTable = GetHammerPieceTable(); if (Object.op_Implicit((Object)(object)table) && Object.op_Implicit((Object)(object)hammerPieceTable)) { return table == hammerPieceTable; } return false; } private static string BuildFullRefreshSignature(PieceTable hammer) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("source=").Append(HarnessPrefabsPlugin.IsSourceOfTruth).Append(';'); stringBuilder.AppendLine(); AppendPrefabNames(stringBuilder, "znet", ZNetScene.instance.m_prefabs); AppendPrefabNames(stringBuilder, "nonnv", ZNetScene.instance.m_nonNetViewPrefabs); AppendPieceTableMembership(stringBuilder, hammer); return stringBuilder.ToString(); } private static void AppendPrefabNames(StringBuilder builder, string label, IEnumerable prefabs) { builder.Append('[').Append(label).AppendLine("]"); foreach (string item in (from prefab in prefabs where Object.op_Implicit((Object)(object)prefab) && !string.IsNullOrWhiteSpace(((Object)prefab).name) select ((Object)prefab).name).Distinct(StringComparer.Ordinal).OrderBy((string name) => name, StringComparer.Ordinal)) { builder.AppendLine(item); } } private static void AppendPieceTableMembership(StringBuilder builder, PieceTable hammer) { builder.AppendLine("[pieceTables]"); foreach (PieceTable item in (from table in Resources.FindObjectsOfTypeAll() where Object.op_Implicit((Object)(object)table) && table.m_pieces != null select table).OrderBy((PieceTable table) => (table != hammer) ? ((Object)table).name : "Hammer", StringComparer.Ordinal)) { builder.Append((item == hammer) ? "Hammer" : ((Object)item).name).Append('='); foreach (string item2 in (from piece in item.m_pieces where Object.op_Implicit((Object)(object)piece) && !string.IsNullOrWhiteSpace(((Object)piece).name) && !AddedPrefabs.Contains(piece) select ((Object)piece).name).OrderBy((string name) => name, StringComparer.Ordinal)) { builder.Append(item2).Append(','); } builder.AppendLine(); } } private static void LogRefreshProfile(string reason, long totalMs, long setupMs, long existingMs, long discoverMs, long rulesMs, long applyMs, int existingBuildableCount, int discoveryCount) { if (HarnessPrefabsPlugin.Verbose || totalMs >= 1000) { HarnessPrefabsPlugin.Log.LogInfo((object)$"Refresh profile ({reason}): total={totalMs} ms, setup={setupMs} ms, existingBuildables={existingMs} ms/{existingBuildableCount}, discover={discoverMs} ms/{discoveryCount}, rules={rulesMs} ms/{PrefabRuleStore.ActiveRuleCount}, apply={applyMs} ms, visible={AddedPrefabs.Count}."); } } private static void LogCachedRefreshProfile(string reason, long totalMs, int discoveryCount) { if (HarnessPrefabsPlugin.Verbose || totalMs >= 1000) { HarnessPrefabsPlugin.Log.LogInfo((object)$"Cached refresh profile ({reason}): total={totalMs} ms, cachedDiscoveries={discoveryCount}, activeRules={PrefabRuleStore.ActiveRuleCount}, visible={AddedPrefabs.Count}."); } } } internal static class PrefabCategoryRegistry { private const int FirstCustomCategory = 9; private static readonly Dictionary CategoriesByName = new Dictionary(StringComparer.Ordinal); public static PieceCategory GetOrAdd(PieceTable table, string categoryName) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) categoryName = NormalizeCategoryName(categoryName); if (TryGetBuiltIn(categoryName, out var category)) { EnsureTableHasCategory(table, category, categoryName); return category; } if (TryGetExistingCustomCategory(table, categoryName, out var category2) && !IsCategoryUsedByDifferentLabel(table, category2, categoryName)) { CategoriesByName[categoryName] = category2; EnsureTableHasCategory(table, category2, categoryName); return category2; } if (CategoriesByName.TryGetValue(categoryName, out var value)) { if (!IsCategoryUsedByDifferentLabel(table, value, categoryName)) { EnsureTableHasCategory(table, value, categoryName); return value; } CategoriesByName.Remove(categoryName); } if (TryGetJotunnCategory(categoryName, out value) && !IsCategoryUsedByDifferentLabel(table, value, categoryName)) { CategoriesByName[categoryName] = value; EnsureTableHasCategory(table, value, categoryName); return value; } if (TryAddJotunnCategory(categoryName, out value) && !IsCategoryUsedByDifferentLabel(table, value, categoryName)) { CategoriesByName[categoryName] = value; EnsureTableHasCategory(table, value, categoryName); return value; } value = AllocateCategory(table); CategoriesByName[categoryName] = value; EnsureTableHasCategory(table, value, categoryName); return value; } public static void EnsureGrown(PieceTable table) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected I4, but got Unknown //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected I4, but got Unknown if (!Object.op_Implicit((Object)(object)table) || table.m_availablePieces == null) { return; } int num = 8; if (table.m_categories != null) { foreach (PieceCategory category in table.m_categories) { int num2 = (int)category; if (num2 >= 0 && num2 < 100) { num = Math.Max(num, num2 + 1); } } } if (table.m_pieces != null) { foreach (GameObject piece in table.m_pieces) { if (!Object.op_Implicit((Object)(object)piece)) { continue; } Piece component = piece.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { int num3 = (int)component.m_category; if (num3 >= 0 && num3 < 100) { num = Math.Max(num, num3 + 1); } } } } while (table.m_availablePieces.Count < num) { table.m_availablePieces.Add(new List()); } GrowVectorArray(ref table.m_selectedPiece, num); GrowVectorArray(ref table.m_lastSelectedPiece, num); } private static string NormalizeCategoryName(string categoryName) { return BuildCategories.NormalizeCategory(categoryName); } private static bool TryGetBuiltIn(string name, out PieceCategory category) { switch (name) { case "Misc": category = (PieceCategory)0; return true; case "Crafting": category = (PieceCategory)1; return true; case "Building": category = (PieceCategory)2; return true; case "BuildingStonecutter": category = (PieceCategory)3; return true; case "Furniture": category = (PieceCategory)4; return true; default: category = (PieceCategory)0; return false; } } private static PieceCategory AllocateCategory(PieceTable table) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected I4, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected I4, but got Unknown int num = 9; if (table.m_categories != null) { foreach (PieceCategory category in table.m_categories) { int num2 = (int)category; if (num2 >= 9 && num2 < 100) { num = Math.Max(num, num2 + 1); } } } foreach (PieceCategory value in CategoriesByName.Values) { int num3 = (int)value; if (num3 >= 9 && num3 < 100) { num = Math.Max(num, num3 + 1); } } if (num >= 100) { num = 99; } return (PieceCategory)num; } private static bool TryGetJotunnCategory(string categoryName, out PieceCategory category) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Expected I4, but got Unknown category = (PieceCategory)0; try { PieceCategory? pieceCategory = PieceManager.Instance.GetPieceCategory(categoryName); if (!pieceCategory.HasValue || (int)pieceCategory.Value == 8 || (int)pieceCategory.Value == 100) { return false; } category = (PieceCategory)(int)pieceCategory.Value; return true; } catch { return false; } } private static bool TryAddJotunnCategory(string categoryName, out PieceCategory category) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected I4, but got Unknown category = (PieceCategory)0; try { category = (PieceCategory)(int)PieceManager.Instance.AddPieceCategory(categoryName); return (int)category != 8 && (int)category != 100; } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogWarning((object)("Jotunn failed to add Hammer category '" + categoryName + "': " + ex.Message)); return false; } } private static bool IsCategoryUsedByDifferentLabel(PieceTable table, PieceCategory category, string label) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)table) || table.m_categories == null || table.m_categoryLabels == null) { return false; } for (int i = 0; i < table.m_categories.Count && i < table.m_categoryLabels.Count; i++) { if (table.m_categories[i] == category && !string.Equals(table.m_categoryLabels[i], label, StringComparison.Ordinal)) { return true; } } return false; } private static bool TryGetExistingCustomCategory(PieceTable table, string label, out PieceCategory category) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Invalid comparison between Unknown and I4 //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Invalid comparison between Unknown and I4 //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Expected I4, but got Unknown category = (PieceCategory)0; if (!Object.op_Implicit((Object)(object)table) || table.m_categories == null || table.m_categoryLabels == null) { return false; } for (int num = table.m_categoryLabels.Count - 1; num >= 0; num--) { if (string.Equals(table.m_categoryLabels[num], label, StringComparison.Ordinal) && num < table.m_categories.Count) { PieceCategory val = table.m_categories[num]; if ((int)val != 8 && (int)val != 100) { category = (PieceCategory)(int)val; return true; } table.m_categoryLabels.RemoveAt(num); table.m_categories.RemoveAt(num); } } return false; } private static void EnsureTableHasCategory(PieceTable table, PieceCategory category, string label) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)table)) { return; } PieceTable val = table; if (val.m_categories == null) { val.m_categories = new List(); } val = table; if (val.m_categoryLabels == null) { val.m_categoryLabels = new List(); } for (int num = table.m_categoryLabels.Count - 1; num >= 0; num--) { if (num >= table.m_categories.Count) { table.m_categoryLabels.RemoveAt(num); } else if (string.Equals(table.m_categoryLabels[num], label, StringComparison.Ordinal) && table.m_categories[num] != category) { table.m_categoryLabels.RemoveAt(num); table.m_categories.RemoveAt(num); } } if (!table.m_categories.Contains(category)) { table.m_categories.Add(category); table.m_categoryLabels.Add(label); } } private static void GrowVectorArray(ref Vector2Int[] array, int needed) { if (array == null) { array = (Vector2Int[])(object)new Vector2Int[needed]; } else if (array.Length < needed) { Vector2Int[] array2 = (Vector2Int[])(object)new Vector2Int[needed]; Array.Copy(array, array2, array.Length); array = array2; } } } internal static class PrefabClassifier { private readonly struct ComponentProbe { public Type Type { get; } public bool IncludeChildren { get; } public string Name { get; } public ComponentProbe(Type type, bool includeChildren) { Type = type; IncludeChildren = includeChildren; Name = type.Name; } } private sealed class ComponentSnapshot { private readonly Type[] _rootTypes; private readonly Type[] _allTypes; public ComponentSnapshot(GameObject prefab) { _rootTypes = CollectTypes(prefab.GetComponents()); _allTypes = CollectTypes(prefab.GetComponentsInChildren(true)); } public bool Has(Type componentType, bool includeChildren) { return (includeChildren ? _allTypes : _rootTypes).Any(componentType.IsAssignableFrom); } public bool HasAny(IEnumerable componentTypes, bool includeChildren) { return componentTypes.Any((Type type) => Has(type, includeChildren)); } private static Type[] CollectTypes(IEnumerable components) { return (from component in components where Object.op_Implicit((Object)(object)component) select ((object)component).GetType()).Distinct().ToArray(); } } private static readonly ComponentProbe[] ComponentProbes = new ComponentProbe[30] { Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Root(), Child(), Child(), Child(), Child(), Child(), Child(), Child(), Child(), Child() }; private static readonly Type[] AlwaysExcludedChildTypes = new Type[22] { typeof(ItemDrop), typeof(Humanoid), typeof(Character), typeof(AnimalAI), typeof(CreatureSpawner), typeof(SpawnArea), typeof(TriggerSpawner), typeof(DungeonGenerator), typeof(TerrainModifier), typeof(EventZone), typeof(LocationProxy), typeof(LootSpawner), typeof(Mister), typeof(TombStone), typeof(LiquidVolume), typeof(Gibber), typeof(ShipConstructor), typeof(TeleportAbility), typeof(Trader), typeof(Fish), typeof(RandomFlyingBird), typeof(MusicLocation) }; private static readonly Type[] RuntimeTypes = new Type[4] { typeof(Projectile), typeof(Aoe), typeof(CamShaker), typeof(Ragdoll) }; private static readonly string[] NatureNameTokens = new string[19] { "ashlands_rock", "rock", "cliff", "stoneformation", "tree", "treelog", "stump", "bush", "branch", "root", "vine", "fern", "flora", "grass", "reed", "moss", "sapling", "shrub", "leviathan" }; private static readonly string[] InteractiveComponentNames = new string[13] { "Door", "PrivateArea", "Ship", "Vagon", "TeleportWorld", "Bed", "Container", "CraftingStation", "StationExtension", "CookingStation", "Smelter", "Fireplace", "ArmorStand" }; private static readonly HashSet MvbpIgnoredPrefabs = new HashSet(StringComparer.Ordinal) { "CapeOdin", "CargoCrate", "CastleKit_brazier", "CastleKit_groundtorch_unlit", "CastleKit_metal_groundtorch_unlit", "CastleKit_pot03", "Charredfortress_LOD", "Circle_section", "FishingRodFloat", "Flies", "HelmetOdin", "Pickable_Barley_Wild", "Pickable_DolmenTreasure", "Pickable_DvergerThing", "Pickable_Flax_Wild", "Pickable_Item", "Pickable_RandomFood", "PlaceMarker", "Player", "Ravens", "SunkenKit_int_towerwall_LOD", "TERRAIN_TEST", "TreasureChest_blackforest", "TreasureChest_forestcrypt", "TreasureChest_forestcrypt_hildir", "TreasureChest_heath", "TreasureChest_heath_hildir", "TreasureChest_meadows", "TreasureChest_meadows_buried", "TreasureChest_mountaincave_hildir", "TreasureChest_mountains", "TreasureChest_plains_stone", "TreasureChest_plainsfortress_hildir", "TreasureChest_swamp", "Valkyrie", "demister_ball", "dragoneggcup", "dvergrprops_crate_ashlands", "dvergrprops_lantern", "dvergrprops_wood_stake", "fenrirhide_hanging_door", "fuling_turret", "guard_stone_test", "horizontal_web", "loot_chest_wood", "odin", "shipwreck_karve_chest", "stonechest", "tolroko_flyer", "turf_roof_wall" }; public static List Discover(IEnumerable prefabs, HashSet existingBuildables) { List list = new List(); foreach (GameObject prefab in prefabs) { PrefabDiscovery prefabDiscovery = TryClassify(prefab, existingBuildables); if (prefabDiscovery != null) { list.Add(prefabDiscovery); } } return list; } private static PrefabDiscovery? TryClassify(GameObject prefab, HashSet existingBuildables) { if (!Object.op_Implicit((Object)(object)prefab)) { return null; } string name = ((Object)prefab).name; bool flag = MvbpPrefabDefaults.HasDefault(name); bool flag2 = existingBuildables.Contains(name); if (string.IsNullOrWhiteSpace(name) || HasExcludedName(name) || (Object.op_Implicit((Object)(object)prefab.transform.parent) && !flag) || flag2) { return null; } ComponentSnapshot componentSnapshot = new ComponentSnapshot(prefab); if (HasExcludedComponent(componentSnapshot, flag)) { return null; } List list = CollectComponents(componentSnapshot); if (IsRuntimePrefab(name, list, flag)) { return null; } bool flag3 = HasRenderable(componentSnapshot); if (list.Count == 0 && !flag3) { return null; } bool flag4 = componentSnapshot.Has(typeof(ZNetView), includeChildren: true); if (!flag && !flag4) { return null; } bool num = IsNature(name, list); bool clipEverything = ShouldClipEverything(name, list); bool clipGround = num || name.IndexOf("rock", StringComparison.OrdinalIgnoreCase) >= 0 || name.IndexOf("cliff", StringComparison.OrdinalIgnoreCase) >= 0; PrefabAccess access; string category; if (num) { access = PrefabAccess.Admin; category = "Harness Nature"; } else if (IsInteractive(list)) { access = PrefabAccess.Admin; category = "Harness Structures"; } else if (list.Contains("Piece") || list.Contains("WearNTear") || list.Contains("Door")) { access = PrefabAccess.Public; category = GuessPublicCategory(name, list); } else if (IsDestructibleOnly(list)) { access = PrefabAccess.Admin; category = "Harness Structures"; } else { access = PrefabAccess.Admin; category = "Harness Props"; } return new PrefabDiscovery { Name = name, Access = access, Category = category, ClipEverything = clipEverything, ClipGround = clipGround, AllowedInDungeons = false, Components = new ComponentList(list), Prefab = prefab }; } private static List CollectComponents(ComponentSnapshot snapshot) { SortedSet sortedSet = new SortedSet(StringComparer.Ordinal); ComponentProbe[] componentProbes = ComponentProbes; for (int i = 0; i < componentProbes.Length; i++) { ComponentProbe componentProbe = componentProbes[i]; if (snapshot.Has(componentProbe.Type, componentProbe.IncludeChildren)) { sortedSet.Add(componentProbe.Name); } } return sortedSet.ToList(); } private static bool HasExcludedComponent(ComponentSnapshot snapshot, bool hasMvbpDefault) { if (!snapshot.HasAny(AlwaysExcludedChildTypes, includeChildren: true)) { return snapshot.HasAny(RuntimeTypes, !hasMvbpDefault); } return true; } private static bool HasExcludedName(string name) { if (!MvbpIgnoredPrefabs.Contains(name) && !name.StartsWith("_", StringComparison.Ordinal) && !name.StartsWith("BBH_", StringComparison.Ordinal) && !name.StartsWith("rrr_", StringComparison.Ordinal) && !name.StartsWith("CLLC_", StringComparison.Ordinal) && !name.StartsWith("OLD_", StringComparison.Ordinal) && !name.EndsWith("OLD", StringComparison.Ordinal) && !name.EndsWith("_old", StringComparison.Ordinal) && !name.EndsWith("_test", StringComparison.Ordinal) && name.IndexOf("Random", StringComparison.Ordinal) < 0) { return name.IndexOf("random", StringComparison.Ordinal) >= 0; } return true; } private static ComponentProbe Root() where T : Component { return new ComponentProbe(typeof(T), includeChildren: false); } private static ComponentProbe Child() where T : Component { return new ComponentProbe(typeof(T), includeChildren: true); } private static bool HasRenderable(ComponentSnapshot snapshot) { if (!snapshot.Has(typeof(Renderer), includeChildren: true)) { return snapshot.Has(typeof(Collider), includeChildren: true); } return true; } private static bool IsRuntimePrefab(string name, IReadOnlyCollection components, bool hasMvbpDefault) { if (IsRuntimeName(name) || MvbpPrefabDefaults.IsRuntimeEffect(name)) { return true; } if (hasMvbpDefault) { return false; } return components.Contains("TimedDestruction"); } private static bool IsRuntimeName(string name) { if (!name.StartsWith("fx_", StringComparison.Ordinal) && !name.StartsWith("vfx_", StringComparison.Ordinal)) { return name.StartsWith("sfx_", StringComparison.Ordinal); } return true; } private static bool IsNature(string name, IReadOnlyCollection components) { if (!IsNatureComponent(components)) { return IsNatureName(name); } return true; } private static bool IsNatureComponent(IReadOnlyCollection components) { if (!components.Contains("Pickable") && !components.Contains("Plant") && !components.Contains("MineRock") && !components.Contains("MineRock5") && !components.Contains("TreeBase")) { return components.Contains("TreeLog"); } return true; } private static bool IsNatureName(string name) { string text = name.ToLowerInvariant(); return NatureNameTokens.Any(text.Contains); } private static bool IsInteractive(IReadOnlyCollection components) { return InteractiveComponentNames.Any(((IEnumerable)components).Contains); } private static bool IsDestructibleOnly(IReadOnlyCollection components) { if (components.Count == 1) { return components.Contains("Destructible"); } return false; } private static bool ShouldClipEverything(string name, IReadOnlyCollection components) { if (!IsNature(name, components) && !components.Contains("InstanceRenderer") && name.IndexOf("rock", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("cliff", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("web", StringComparison.OrdinalIgnoreCase) < 0) { return name.IndexOf("vine", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } private static string GuessPublicCategory(string name, IReadOnlyCollection components) { string text = name.ToLowerInvariant(); if (components.Contains("CraftingStation") || components.Contains("StationExtension")) { return "Crafting"; } if (components.Contains("Chair") || components.Contains("ArmorStand") || text.Contains("chair") || text.Contains("bench") || text.Contains("table") || text.Contains("rug") || text.Contains("banner") || text.Contains("curtain")) { return "Furniture"; } if (text.Contains("stone") || text.Contains("marble") || text.Contains("grausten")) { return "BuildingStonecutter"; } if (components.Contains("WearNTear") || components.Contains("Door") || text.Contains("wood") || text.Contains("wall") || text.Contains("floor") || text.Contains("roof") || text.Contains("beam") || text.Contains("stair")) { return "Building"; } return "Misc"; } } internal static class HarnessPrefabsRuntime { public static bool TryGetManagedRule(GameObject gameObject, out PrefabRule rule) { rule = null; if (!Object.op_Implicit((Object)(object)gameObject)) { return false; } return TryGetManagedRule(((Object)gameObject).name, out rule); } public static bool TryGetManagedRule(Component component, out PrefabRule rule) { return TryGetManagedRule(Object.op_Implicit((Object)(object)component) ? component.gameObject : null, out rule); } public static bool TryGetKnownManagedPlacedPiece(Component component, out Piece piece) { piece = (Object.op_Implicit((Object)(object)component) ? component.GetComponentInParent() : null); if (!Object.op_Implicit((Object)(object)piece) || !piece.IsPlacedByPlayer()) { return false; } string text = NormalizePrefabName(((Object)((Component)piece).gameObject).name); PrefabRule rule; if (text.Length > 0) { return PrefabRuleStore.TryGetRule(text, out rule); } return false; } public static bool TryGetManagedRule(string prefabName, out PrefabRule rule) { rule = null; string text = NormalizePrefabName(prefabName); if (text.Length == 0) { return false; } if (PrefabRuleStore.TryGetRule(text, out rule)) { return rule.Access != PrefabAccess.Hidden; } return false; } public static string NormalizePrefabName(string name) { if (string.IsNullOrWhiteSpace(name)) { return ""; } name = name.Trim(); if (name.EndsWith("(Clone)", StringComparison.Ordinal)) { name = name.Substring(0, name.Length - "(Clone)".Length).Trim(); } return name; } } internal static class PrefabLocalizationOverrideManager { private sealed class LocalizationPayload { public Dictionary All { get; set; } = new Dictionary(StringComparer.OrdinalIgnoreCase); public Dictionary> Languages { get; set; } = new Dictionary>(StringComparer.OrdinalIgnoreCase); } private const string DomainName = "localization"; private const string DefaultLanguageFileName = "English.yml"; private const string SyncedPayloadKey = "localization-yaml"; private const double ReloadDebounceMilliseconds = 500.0; private static readonly object StateLock = new object(); private static readonly IDeserializer Deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build(); private static readonly ISerializer Serializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).DisableAliases().Build(); private static LocalizationPayload _activePayload = new LocalizationPayload(); private static CustomSyncedValue? _syncedPayload; private static FileSystemWatcher? _watcher; private static System.Timers.Timer? _reloadTimer; private static string? _lastParsedPayload; private static readonly Dictionary> OriginalTranslationsByLanguage = new Dictionary>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary> AppliedKeysByLanguage = new Dictionary>(StringComparer.OrdinalIgnoreCase); private static string LocalizationDirectory => Path.Combine(PrefabRuleStore.RulesDirectory, "localization"); public static void Initialize(ConfigSync configSync) { _syncedPayload = new CustomSyncedValue(configSync, "localization-yaml", "", 90); _syncedPayload.ValueChanged += OnSyncedPayloadChanged; } public static void SetupFileWatcher() { if (!HarnessPrefabsPlugin.IsSourceOfTruth) { _reloadTimer?.Stop(); _watcher?.Dispose(); _watcher = null; return; } _watcher?.Dispose(); if (_reloadTimer == null) { _reloadTimer = CreateReloadTimer(); } EnsureDirectoryAndDefaultFile(); _watcher = new FileSystemWatcher(LocalizationDirectory, "*.*") { IncludeSubdirectories = false, SynchronizingObject = ThreadingHelper.SynchronizingObject, EnableRaisingEvents = true }; _watcher.Changed += ScheduleLocalizationReload; _watcher.Created += ScheduleLocalizationReload; _watcher.Deleted += ScheduleLocalizationReload; _watcher.Renamed += ScheduleLocalizationReload; } public static void Dispose() { if (_syncedPayload != null) { _syncedPayload.ValueChanged -= OnSyncedPayloadChanged; } _watcher?.Dispose(); _watcher = null; _reloadTimer?.Dispose(); _reloadTimer = null; } public static bool ReloadFromDiskAndSync() { if (!HarnessPrefabsPlugin.IsSourceOfTruth) { return ApplySyncedPayload(_syncedPayload?.Value ?? ""); } LocalizationPayload localizationPayload; string text; try { EnsureDirectoryAndDefaultFile(); localizationPayload = LoadPayloadFromDisk(); text = SerializePayload(localizationPayload); PublishPayload(text); } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogError((object)("Failed to reload localization YAML. Keeping the last known good localization. Error: " + ex.Message)); return false; } lock (StateLock) { _activePayload = localizationPayload; _lastParsedPayload = text; } ApplyCurrentLocalization(); return true; } public static void ApplyCurrentLocalization() { Localization instance = Localization.instance; if (instance != null) { ApplyCurrentLocalization(instance, instance.GetSelectedLanguage()); } } public static void ApplyCurrentLocalization(Localization localization, string? language) { if (localization == null) { return; } string text = NormalizeLanguage(language); Dictionary dictionary; lock (StateLock) { dictionary = BuildTranslationsForLanguage(_activePayload, text); } RestoreRemovedTranslations(localization, text, dictionary.Keys); foreach (KeyValuePair item in dictionary) { ApplyTranslation(localization, text, item.Key, item.Value); } AppliedKeysByLanguage[text] = new HashSet(dictionary.Keys, StringComparer.OrdinalIgnoreCase); } private static void ScheduleLocalizationReload(object sender, FileSystemEventArgs e) { if (HarnessPrefabsPlugin.IsSourceOfTruth && IsLocalizationFile(e.FullPath)) { _reloadTimer?.Stop(); _reloadTimer?.Start(); } } private static void ReadLocalizationValues(object sender, ElapsedEventArgs e) { if (HarnessPrefabsPlugin.IsSourceOfTruth && ReloadFromDiskAndSync()) { HarnessPrefabsPlugin.Log.LogInfo((object)"Localization YAML reload complete."); } } private static System.Timers.Timer CreateReloadTimer() { System.Timers.Timer timer = new System.Timers.Timer(500.0); timer.AutoReset = false; timer.SynchronizingObject = ThreadingHelper.SynchronizingObject; timer.Elapsed += ReadLocalizationValues; return timer; } private static void OnSyncedPayloadChanged() { if (!HarnessPrefabsPlugin.IsSourceOfTruth) { ApplySyncedPayload(_syncedPayload?.Value ?? ""); } } private static bool ApplySyncedPayload(string payload) { if (string.Equals(_lastParsedPayload, payload, StringComparison.Ordinal)) { return false; } if (!TryDeserializePayload(payload, "synced localization payload", out LocalizationPayload localizationPayload)) { return false; } lock (StateLock) { _activePayload = localizationPayload; _lastParsedPayload = payload; } ApplyCurrentLocalization(); return true; } private static void PublishPayload(string payload) { if (_syncedPayload != null && !string.Equals(_syncedPayload.Value ?? "", payload, StringComparison.Ordinal)) { _syncedPayload.Value = payload; } } private static LocalizationPayload LoadPayloadFromDisk() { LocalizationPayload localizationPayload = new LocalizationPayload(); if (!Directory.Exists(LocalizationDirectory)) { return localizationPayload; } foreach (string item in Directory.GetFiles(LocalizationDirectory, "*.yml").Concat(Directory.GetFiles(LocalizationDirectory, "*.yaml")).OrderBy((string path) => path, StringComparer.OrdinalIgnoreCase)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(item); Dictionary dictionary = LoadTranslationMap(item, fileNameWithoutExtension + " localization"); if (dictionary.Count != 0) { if (!localizationPayload.Languages.TryGetValue(fileNameWithoutExtension, out Dictionary value)) { value = new Dictionary(StringComparer.OrdinalIgnoreCase); localizationPayload.Languages[fileNameWithoutExtension] = value; } MergeTranslations(value, dictionary); } } return localizationPayload; } private static Dictionary LoadTranslationMap(string path, string source) { if (!File.Exists(path)) { return new Dictionary(StringComparer.OrdinalIgnoreCase); } string text = File.ReadAllText(path); if (string.IsNullOrWhiteSpace(text)) { return new Dictionary(StringComparer.OrdinalIgnoreCase); } try { return NormalizeTranslationMap(Deserializer.Deserialize>(text), source); } catch (Exception ex) { throw new InvalidDataException("Failed to parse " + source + " from '" + path + "': " + ex.Message, ex); } } private static Dictionary NormalizeTranslationMap(Dictionary? map, string source) { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); if (map == null) { return dictionary; } foreach (KeyValuePair item in map) { string text = NormalizeToken(item.Key); if (text.Length == 0) { HarnessPrefabsPlugin.Log.LogWarning((object)("Skipping localization entry with an empty token in " + source + ".")); } else { dictionary[text] = item.Value ?? ""; } } return dictionary; } private static string SerializePayload(LocalizationPayload payload) { return Serializer.Serialize(payload); } private static bool TryDeserializePayload(string payload, string source, out LocalizationPayload localizationPayload) { if (string.IsNullOrWhiteSpace(payload)) { localizationPayload = new LocalizationPayload(); return true; } try { LocalizationPayload payload2 = Deserializer.Deserialize(payload); localizationPayload = NormalizePayload(payload2, source); return true; } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogError((object)("Failed to parse " + source + ": " + ex.Message)); localizationPayload = null; return false; } } private static LocalizationPayload NormalizePayload(LocalizationPayload? payload, string source) { LocalizationPayload localizationPayload = new LocalizationPayload(); if (payload == null) { return localizationPayload; } MergeTranslations(localizationPayload.All, NormalizeStringTranslationMap(payload.All, source + " common")); foreach (KeyValuePair> language in payload.Languages) { string text = NormalizeLanguage(language.Key); if (text.Length != 0) { localizationPayload.Languages[text] = NormalizeStringTranslationMap(language.Value, source + " " + text); } } return localizationPayload; } private static Dictionary NormalizeStringTranslationMap(Dictionary? map, string source) { return NormalizeTranslationMap(map?.ToDictionary, string, string>((KeyValuePair pair) => pair.Key, (KeyValuePair pair) => pair.Value, StringComparer.OrdinalIgnoreCase), source); } private static Dictionary BuildTranslationsForLanguage(LocalizationPayload payload, string language) { Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); MergeTranslations(dictionary, payload.All); if (!language.Equals("English", StringComparison.OrdinalIgnoreCase) && payload.Languages.TryGetValue("English", out Dictionary value)) { MergeTranslations(dictionary, value); } if (payload.Languages.TryGetValue(language, out Dictionary value2)) { MergeTranslations(dictionary, value2); } return dictionary; } private static void MergeTranslations(Dictionary target, Dictionary source) { foreach (KeyValuePair item in source) { target[NormalizeToken(item.Key)] = item.Value; } } private static void ApplyTranslation(Localization localization, string language, string token, string text) { token = NormalizeToken(token); if (token.Length != 0) { Dictionary originalTranslations = GetOriginalTranslations(language); if (!originalTranslations.ContainsKey(token)) { originalTranslations[token] = (localization.m_translations.TryGetValue(token, out var value) ? value : null); } localization.m_translations[token] = text; } } private static void RestoreRemovedTranslations(Localization localization, string language, IEnumerable currentTokens) { HashSet current = new HashSet(currentTokens.Select(NormalizeToken), StringComparer.OrdinalIgnoreCase); if (!AppliedKeysByLanguage.TryGetValue(language, out HashSet value)) { return; } Dictionary originalTranslations = GetOriginalTranslations(language); string[] array = value.Where((string token) => !current.Contains(token)).ToArray(); foreach (string key in array) { if (originalTranslations.TryGetValue(key, out var value2)) { if (value2 == null) { localization.m_translations.Remove(key); } else { localization.m_translations[key] = value2; } originalTranslations.Remove(key); } } } private static Dictionary GetOriginalTranslations(string language) { if (!OriginalTranslationsByLanguage.TryGetValue(language, out Dictionary value)) { value = new Dictionary(StringComparer.OrdinalIgnoreCase); OriginalTranslationsByLanguage[language] = value; } return value; } private static void EnsureDirectoryAndDefaultFile() { Directory.CreateDirectory(LocalizationDirectory); string path = Path.Combine(LocalizationDirectory, "English.yml"); if (!File.Exists(path)) { File.WriteAllText(path, DefaultEnglishLocalizationTemplate()); } } private static string DefaultEnglishLocalizationTemplate() { return string.Join(Environment.NewLine, "# HarnessPrefabs server-synced localization.", "#", "# Put language files in this folder using Valheim language names:", "# English.yml, Korean.yml, Turkish.yml, German.yml, etc.", "#", "# English.yml is the fallback file. Other languages apply English first,", "# then the selected language file.", "#", "# Use tokens in prefabs.yml displayName or description fields:", "# - prefab: barrell", "# enabled: true", "# displayName: $ph_piece_barrell", "# description: $ph_piece_barrell_desc", "#", "# Example localization entries:", "# $ph_piece_barrell: \"Barrel\"", "# $ph_piece_barrell_desc: \"A decorative barrel.\"", ""); } private static bool IsLocalizationFile(string path) { string extension = Path.GetExtension(path); if (!extension.Equals(".yml", StringComparison.OrdinalIgnoreCase) && !extension.Equals(".yaml", StringComparison.OrdinalIgnoreCase)) { return false; } string fullPath = Path.GetFullPath(path); string fullPath2 = Path.GetFullPath(LocalizationDirectory); char directorySeparatorChar = Path.DirectorySeparatorChar; return fullPath.StartsWith(fullPath2 + directorySeparatorChar, StringComparison.OrdinalIgnoreCase); } private static string NormalizeToken(string token) { return (token ?? "").Trim().TrimStart(new char[1] { '$' }).Trim(); } private static string NormalizeLanguage(string? language) { string text = language?.Trim() ?? ""; if (text.Length != 0) { return text; } return "English"; } } [HarmonyPatch(typeof(Localization), "SetupLanguage")] internal static class HarnessPrefabsLocalizationSetupLanguagePatch { [HarmonyPriority(0)] private static void Postfix(Localization __instance, string language) { PrefabLocalizationOverrideManager.ApplyCurrentLocalization(__instance, language); } } [HarmonyPatch] internal static class HarnessPrefabsPlacedPiecePatches { private static readonly Dictionary DefaultResources = new Dictionary(StringComparer.Ordinal); private static readonly int PieceLayer = LayerMask.NameToLayer("piece"); private static readonly int CharacterTriggerLayer = LayerMask.NameToLayer("character_trigger"); private const float FermenterLodSize = 6.7675858f; private const string ZdoHasFields = "HasFields"; private const string ZdoHasFieldsContainer = "HasFieldsContainer"; private const string ZdoHasFieldsInventory = "HasFieldsInventory"; private const string ZdoHasFieldsTimedDestruction = "HasFieldsTimedDestruction"; private const string ZdoHasFieldsDestructible = "HasFieldsDestructible"; private const string ZdoHasFieldsDoor = "HasFieldsDoor"; private const string ZdoContainerCheckGuardStone = "Container.m_checkGuardStone"; private const string ZdoContainerWidth = "Container.m_width"; private const string ZdoContainerHeight = "Container.m_height"; private const string ZdoInventoryWidth = "Inventory.m_width"; private const string ZdoInventoryHeight = "Inventory.m_height"; private const string ZdoTimedDestructionTimeout = "TimedDestruction.m_timeout"; private const string ZdoDestructibleSpawnWhenDestroyed = "Destructible.m_spawnWhenDestroyed"; private const string ZdoDoorCanNotBeClosed = "Door.m_canNotBeClosed"; private const string ZdoDoorCheckGuardStone = "Door.m_checkGuardStone"; public static void RegisterDefaultResources(GameObject prefab, Requirement[] resources) { string text = HarnessPrefabsRuntime.NormalizePrefabName(Object.op_Implicit((Object)(object)prefab) ? ((Object)prefab).name : ""); if (text.Length != 0 && !DefaultResources.ContainsKey(text)) { DefaultResources[text] = CloneRequirements(resources); } } [HarmonyPrefix] [HarmonyPatch(typeof(Piece), "SetCreator")] private static void PieceSetCreatorPrefix(Piece __instance) { if (!HarnessPrefabsRuntime.TryGetManagedRule((Component)(object)__instance, out var _)) { return; } ZNetView component = ((Component)__instance).GetComponent(); if (Object.op_Implicit((Object)(object)component) && !component.m_persistent) { component.m_persistent = true; ZSyncTransform val = ((Component)__instance).gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)val)) { val = ((Component)__instance).gameObject.AddComponent(); } val.m_syncPosition = true; val.m_syncRotation = true; } } [HarmonyPostfix] [HarmonyPatch(typeof(Piece), "SetCreator")] private static void PieceSetCreatorPostfix(Piece __instance) { if (HarnessPrefabsRuntime.TryGetManagedRule((Component)(object)__instance, out var _)) { ClearPlacedContainerInventory(__instance); ApplyRuntimePatches(__instance); } } [HarmonyPostfix] [HarmonyPriority(700)] [HarmonyPatch(typeof(Piece), "Awake")] private static void PieceAwakePostfix(Piece __instance) { if (Object.op_Implicit((Object)(object)__instance) && __instance.IsPlacedByPlayer() && HarnessPrefabsRuntime.TryGetManagedRule((Component)(object)__instance, out var _)) { ApplyRuntimePatches(__instance); } } [HarmonyPrefix] [HarmonyPatch(typeof(WearNTear), "Destroy")] private static void WearNTearDestroyPrefix(WearNTear __instance, out (bool Changed, EffectList Original) __state) { __state = (Changed: false, Original: null); if (HarnessPrefabsRuntime.TryGetManagedRule((Component)(object)__instance, out var _) && !HarnessPrefabsSfxManager.HasSfx(__instance.m_destroyedEffect)) { __state = (Changed: true, Original: __instance.m_destroyedEffect); __instance.m_destroyedEffect = HarnessPrefabsSfxManager.FixRemovalSfx(__instance); } } [HarmonyFinalizer] [HarmonyPatch(typeof(WearNTear), "Destroy")] private static Exception WearNTearDestroyFinalizer(WearNTear __instance, (bool Changed, EffectList Original) __state, Exception __exception) { if (__state.Changed && Object.op_Implicit((Object)(object)__instance)) { __instance.m_destroyedEffect = __state.Original; } return __exception; } [HarmonyPrefix] [HarmonyPatch(typeof(Piece), "DropResources")] private static void PieceDropResourcesPrefix(Piece __instance, out (bool Changed, Requirement[] Original) __state) { __state = (Changed: false, Original: null); if (Object.op_Implicit((Object)(object)__instance) && HarnessPrefabsRuntime.TryGetManagedRule((Component)(object)__instance, out var _)) { Requirement[] dropResources = GetDropResources(__instance); if (dropResources != null && dropResources != __instance.m_resources) { __state = (Changed: true, Original: __instance.m_resources); __instance.m_resources = dropResources; } } } [HarmonyFinalizer] [HarmonyPatch(typeof(Piece), "DropResources")] private static Exception PieceDropResourcesFinalizer(Piece __instance, (bool Changed, Requirement[] Original) __state, Exception __exception) { if (__state.Changed && Object.op_Implicit((Object)(object)__instance)) { __instance.m_resources = __state.Original; } return __exception; } [HarmonyPrefix] [HarmonyPatch(typeof(DropOnDestroyed), "OnDestroyed")] private static bool DropOnDestroyedPrefix(DropOnDestroyed __instance) { Piece piece; return !HarnessPrefabsRuntime.TryGetKnownManagedPlacedPiece((Component)(object)__instance, out piece); } [HarmonyPrefix] [HarmonyPatch(typeof(Door), "RPC_UseDoor")] private static void DoorUsePrefix(Door __instance, out int? __state) { __state = null; if (HarnessPrefabsRuntime.TryGetKnownManagedPlacedPiece((Component)(object)__instance, out var piece) && !(HarnessPrefabsRuntime.NormalizePrefabName(((Object)((Component)piece).gameObject).name) != "dvergrtown_secretdoor")) { __state = GetDoorState(__instance); } } [HarmonyPostfix] [HarmonyPatch(typeof(Door), "RPC_UseDoor")] private static void DoorUsePostfix(Door __instance, int? __state) { if (!Object.op_Implicit((Object)(object)__instance) || !__state.HasValue) { return; } int? doorState = GetDoorState(__instance); ZNetView component = ((Component)__instance).GetComponent(); if (doorState.HasValue && (__state == -1 || __state == 1) && doorState == 0 && Object.op_Implicit((Object)(object)component) && component.IsValid()) { if (!component.IsOwner()) { component.ClaimOwnership(); } __instance.m_animator.Rebind(); __instance.m_animator.Update(0f); } } private static void ApplyRuntimePatches(Piece piece) { string prefabName = HarnessPrefabsRuntime.NormalizePrefabName(((Object)piece).name); ApplyContainerPatches(piece, prefabName); ApplyTimedDestructionPatch(piece); ApplySpawnOnDestroyedPatch(piece, prefabName); ApplyDoorPatches(piece); if (MvbpCompatibilityDefaults.HasPlayerBasePatch(prefabName)) { ApplyPlayerBasePatch(((Component)piece).gameObject); } if (HarnessPrefabsPlugin.UnsafeBedPatchesEnabled) { ApplyBedPatch(((Component)piece).gameObject, prefabName); } int fermenterPatchDurationPercent = HarnessPrefabsPlugin.FermenterPatchDurationPercent; if (fermenterPatchDurationPercent > 0) { ApplyFermenterPatch(((Component)piece).gameObject, prefabName, fermenterPatchDurationPercent); } } private static void ClearPlacedContainerInventory(Piece piece) { Container componentInChildren = ((Component)piece).GetComponentInChildren(); Inventory val = (Object.op_Implicit((Object)(object)componentInChildren) ? componentInChildren.GetInventory() : null); if (val != null && val.NrOfItems() != 0) { val.RemoveAll(); componentInChildren.Save(); if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogInfo((object)("Cleared default container inventory for placed prefab '" + HarnessPrefabsRuntime.NormalizePrefabName(((Object)piece).name) + "'.")); } } } private static void ApplyContainerPatches(Piece piece, string prefabName) { Container componentInChildren = ((Component)piece).GetComponentInChildren(); if (!Object.op_Implicit((Object)(object)componentInChildren) || !TryGetZdo(piece, out var zdo)) { return; } MarkZdoFields(zdo, "HasFieldsContainer"); zdo.Set("Container.m_checkGuardStone", true); componentInChildren.m_checkGuardStone = true; if (MvbpCompatibilityDefaults.TryGetContainerSize(prefabName, out var width, out var height)) { Inventory inventory = componentInChildren.GetInventory(); zdo.Set("Container.m_width", width); zdo.Set("Container.m_height", height); MarkZdoFields(zdo, "HasFieldsInventory"); zdo.Set("Inventory.m_width", width); zdo.Set("Inventory.m_height", height); componentInChildren.m_width = width; componentInChildren.m_height = height; if (inventory != null) { inventory.m_width = width; inventory.m_height = height; } } } private static void ApplyTimedDestructionPatch(Piece piece) { TimedDestruction component = ((Component)piece).GetComponent(); if (Object.op_Implicit((Object)(object)component) && TryGetZdo(piece, out var zdo)) { MarkZdoFields(zdo, "HasFieldsTimedDestruction"); zdo.Set("TimedDestruction.m_timeout", 1E+30f); component.m_timeout = 1E+30f; } } private static void ApplySpawnOnDestroyedPatch(Piece piece, string prefabName) { if (!MvbpCompatibilityDefaults.TryGetSpawnOnDestroyed(prefabName, out var spawnOnDestroyed) || !TryGetZdo(piece, out var zdo)) { return; } Destructible component = ((Component)piece).GetComponent(); if (Object.op_Implicit((Object)(object)component)) { GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab(spawnOnDestroyed) : null); if (Object.op_Implicit((Object)(object)val)) { MarkZdoFields(zdo, "HasFieldsDestructible"); zdo.Set("Destructible.m_spawnWhenDestroyed", spawnOnDestroyed); component.m_spawnWhenDestroyed = val; } } } private static void ApplyDoorPatches(Piece piece) { string text = HarnessPrefabsRuntime.NormalizePrefabName(((Object)piece).name); if (!(text != "dvergrtown_slidingdoor") || !(text != "dvergrtown_secretdoor")) { Door component = ((Component)piece).GetComponent(); if (Object.op_Implicit((Object)(object)component) && TryGetZdo(piece, out var zdo)) { component.m_canNotBeClosed = false; component.m_checkGuardStone = true; MarkZdoFields(zdo, "HasFieldsDoor"); zdo.Set("Door.m_canNotBeClosed", false); zdo.Set("Door.m_checkGuardStone", true); } } } private static void ApplyPlayerBasePatch(GameObject gameObject) { //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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)gameObject.transform.Find("PlayerBase"))) { GameObject val = new GameObject("PlayerBase"); val.transform.SetParent(gameObject.transform, false); val.transform.localScale = Vector3.one; val.transform.localPosition = Vector3.zero; val.layer = CharacterTriggerLayer; SphereCollider obj = val.AddComponent(); obj.center = Vector3.zero; obj.radius = 20f; ((Collider)obj).enabled = true; ((Collider)obj).isTrigger = true; EffectArea obj2 = val.AddComponent(); ((Behaviour)obj2).enabled = true; obj2.m_type = (Type)4; } } private static void ApplyBedPatch(GameObject gameObject, string prefabName) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) if (prefabName != "goblin_bed" && prefabName != "dvergrprops_bed") { return; } Bed component = gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)component) || !Object.op_Implicit((Object)(object)component.m_spawnPoint)) { Transform val = gameObject.transform.Find("spawnpoint"); if (!Object.op_Implicit((Object)(object)val)) { GameObject val2 = new GameObject("spawnpoint"); val2.transform.SetParent(gameObject.transform, false); val = val2.transform; } val.localPosition = new Vector3(0f, 0.45f, 0f); ((Component)val).gameObject.layer = PieceLayer; component = (Object.op_Implicit((Object)(object)component) ? component : gameObject.AddComponent()); component.m_spawnPoint = val; } } private static void ApplyFermenterPatch(GameObject gameObject, string prefabName, int durationPercent) { //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0231: 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_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Expected O, but got Unknown if (prefabName != "dvergrprops_barrel") { return; } Fermenter component = gameObject.GetComponent(); GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab("fermenter") : null); Fermenter val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); if (Object.op_Implicit((Object)(object)component)) { if (Object.op_Implicit((Object)(object)val2)) { component.m_fermentationDuration = val2.m_fermentationDuration * (float)Mathf.Clamp(durationPercent, 1, 100) / 100f; } EnsureFermenterHoverProxies(gameObject); ApplyFermenterLodPatch(gameObject, val); ApplyPlayerBasePatch(gameObject); } else { if (!Object.op_Implicit((Object)(object)val) || !Object.op_Implicit((Object)(object)val2)) { return; } Transform val3 = val.transform.Find("add_button"); Transform val4 = val.transform.Find("tap_button"); Transform val5 = val.transform.Find("roofcheckpoint"); Transform val6 = val.transform.Find("output"); Transform val7 = val.transform.Find("_ready"); Transform val8 = val.transform.Find("_fermenting"); if (!Object.op_Implicit((Object)(object)val3) || !Object.op_Implicit((Object)(object)val4) || !Object.op_Implicit((Object)(object)val5) || !Object.op_Implicit((Object)(object)val6) || !Object.op_Implicit((Object)(object)val7) || !Object.op_Implicit((Object)(object)val8) || !Object.op_Implicit((Object)(object)((Component)val3).GetComponent()) || !Object.op_Implicit((Object)(object)((Component)val4).GetComponent())) { return; } List list = new List(); Fermenter val9 = null; bool activeSelf = gameObject.activeSelf; try { GameObject val10 = CloneFermenterChild(val3, gameObject.transform); GameObject val11 = CloneFermenterChild(val4, gameObject.transform); GameObject val12 = CloneFermenterChild(val5, gameObject.transform); GameObject val13 = CloneFermenterChild(val6, gameObject.transform); GameObject val14 = CloneFermenterChild(val7, gameObject.transform); GameObject val15 = CloneFermenterChild(val8, gameObject.transform); list.AddRange((IEnumerable)(object)new GameObject[6] { val10, val11, val12, val13, val14, val15 }); val10.transform.localScale = Vector3.one; val10.transform.localPosition = new Vector3(0f, 0.75f, 0f); val11.transform.localPosition = new Vector3(0f, 0.5f, 0.9f); val13.transform.localPosition = new Vector3(0f, 0.5f, 1.2f); val12.transform.localPosition = new Vector3(0f, 1.5f, 0f); val14.transform.localPosition = new Vector3(0f, 0.75f, 0f); val15.transform.localPosition = new Vector3(0f, 0.75f, 0f); Transform val16 = gameObject.transform.Find("_top"); if (!Object.op_Implicit((Object)(object)val16)) { GameObject val17 = new GameObject("_top"); val17.transform.SetParent(gameObject.transform, false); list.Add(val17); val16 = val17.transform; } gameObject.SetActive(false); val9 = gameObject.AddComponent(); val9.m_addSwitch = val10.GetComponent(); val9.m_tapSwitch = val11.GetComponent(); val9.m_roofCheckPoint = val12.transform; val9.m_topObject = ((Component)val16).gameObject; val9.m_readyObject = val14; val9.m_fermentingObject = val15; val9.m_outputPoint = val13.transform; val9.m_tapDelay = val2.m_tapDelay; val9.m_updateCoverTimer = val2.m_updateCoverTimer; val9.m_fermentationDuration = val2.m_fermentationDuration * (float)Mathf.Clamp(durationPercent, 1, 100) / 100f; val9.m_name = val2.m_name; val9.m_addedEffects = val2.m_addedEffects; val9.m_tapEffects = val2.m_tapEffects; val9.m_spawnEffects = val2.m_spawnEffects; val9.m_conversion = val2.m_conversion; } catch (Exception ex) { if (Object.op_Implicit((Object)(object)val9)) { Object.DestroyImmediate((Object)(object)val9); } for (int num = list.Count - 1; num >= 0; num--) { if (Object.op_Implicit((Object)(object)list[num])) { Object.DestroyImmediate((Object)(object)list[num]); } } HarnessPrefabsPlugin.Log.LogWarning((object)("Failed to patch fermenter prefab '" + prefabName + "': " + ex.Message)); return; } finally { gameObject.SetActive(activeSelf); } EnsureFermenterHoverProxies(gameObject); ApplyFermenterLodPatch(gameObject, val); ApplyPlayerBasePatch(gameObject); } } private static void ApplyFermenterLodPatch(GameObject gameObject, GameObject fermenterPrefab = null) { float num = 6.7675858f; LODGroup val = (Object.op_Implicit((Object)(object)fermenterPrefab) ? fermenterPrefab.GetComponent() : null); if (Object.op_Implicit((Object)(object)val) && val.size > num) { num = val.size; } LODGroup[] componentsInChildren = gameObject.GetComponentsInChildren(true); foreach (LODGroup val2 in componentsInChildren) { if (Object.op_Implicit((Object)(object)val2)) { val2.size = Mathf.Max(val2.size, num); } } } private static void EnsureFermenterHoverProxies(GameObject gameObject) { if (!Object.op_Implicit((Object)(object)gameObject.GetComponent())) { return; } Collider[] componentsInChildren = gameObject.GetComponentsInChildren(true); foreach (Collider val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val) && ((Component)val).GetComponent() == null && !Object.op_Implicit((Object)(object)((Component)val).GetComponent())) { ((Component)val).gameObject.AddComponent(); } } } private static GameObject CloneFermenterChild(Transform source, Transform targetParent) { bool activeSelf = ((Component)source).gameObject.activeSelf; GameObject val; try { ((Component)source).gameObject.SetActive(false); val = Object.Instantiate(((Component)source).gameObject); } finally { ((Component)source).gameObject.SetActive(activeSelf); } ((Object)val).name = ((Object)source).name; val.transform.SetParent(targetParent, false); val.SetActive(activeSelf); return val; } private static Requirement[] GetDropResources(Piece piece) { string key = HarnessPrefabsRuntime.NormalizePrefabName(((Object)((Component)piece).gameObject).name); if (!piece.IsPlacedByPlayer() && DefaultResources.TryGetValue(key, out var value)) { return CloneRequirements(value); } DropItemStandItems(piece); Requirement[] array = CloneRequirements(piece.m_resources); Pickable component = ((Component)piece).GetComponent(); if (Object.op_Implicit((Object)(object)component)) { bool picked = component.m_picked; bool flag = false; ZNetView val = (Object.op_Implicit((Object)(object)component.m_nview) ? component.m_nview : ((Component)component).GetComponent()); if (!picked && Object.op_Implicit((Object)(object)val) && val.IsValid()) { val.InvokeRPC("RPC_Pick", new object[1] { 0 }); flag = true; } array = RemovePickableFromRequirements(array, component, picked || flag); } return array; } private static void DropItemStandItems(Piece piece) { ItemStand[] componentsInChildren = ((Component)piece).GetComponentsInChildren(); foreach (ItemStand val in componentsInChildren) { if (!Object.op_Implicit((Object)(object)val)) { continue; } ZNetView val2 = (Object.op_Implicit((Object)(object)val.m_nview) ? val.m_nview : (Object.op_Implicit((Object)(object)val.m_netViewOverride) ? val.m_netViewOverride : ((Component)val).GetComponent())); if (Object.op_Implicit((Object)(object)val2) && val2.IsValid()) { bool canBeRemoved = val.m_canBeRemoved; try { val.m_canBeRemoved = true; val2.InvokeRPC("RPC_DropItem", Array.Empty()); } finally { val.m_canBeRemoved = canBeRemoved; } } } } private static Requirement[] RemovePickableFromRequirements(Requirement[] requirements, Pickable pickable, bool pickedOrRequested) { if (requirements == null || !Object.op_Implicit((Object)(object)pickable) || !pickedOrRequested || !Object.op_Implicit((Object)(object)pickable.m_itemPrefab)) { return requirements; } ItemDrop component = pickable.m_itemPrefab.GetComponent(); if (component?.m_itemData?.m_shared == null) { return requirements; } Requirement[] array = CloneRequirements(requirements); int scaledPickableDropAmount = GetScaledPickableDropAmount(pickable); string name = component.m_itemData.m_shared.m_name; Requirement[] array2 = array; foreach (Requirement val in array2) { if (val?.m_resItem?.m_itemData?.m_shared?.m_name == name) { val.m_amount = Mathf.Clamp(val.m_amount - scaledPickableDropAmount, 0, val.m_amount); break; } } return array; } private static int GetScaledPickableDropAmount(Pickable pickable) { if (!Object.op_Implicit((Object)(object)Game.instance)) { return pickable.m_amount; } if (!pickable.m_dontScale) { return Mathf.Max(pickable.m_minAmountScaled, Game.instance.ScaleDrops(pickable.m_itemPrefab, pickable.m_amount)); } return pickable.m_amount; } private static Requirement[] CloneRequirements(Requirement[] requirements) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (requirements == null || requirements.Length == 0) { return Array.Empty(); } Requirement[] array = (Requirement[])(object)new Requirement[requirements.Length]; for (int i = 0; i < requirements.Length; i++) { Requirement val = requirements[i]; array[i] = ((val == null) ? ((Requirement)null) : new Requirement { m_resItem = val.m_resItem, m_amount = val.m_amount, m_amountPerLevel = val.m_amountPerLevel, m_recover = val.m_recover }); } return array; } private static int? GetDoorState(Door door) { if (!Object.op_Implicit((Object)(object)door) || !Object.op_Implicit((Object)(object)door.m_nview) || !door.m_nview.IsValid()) { return null; } return door.m_nview.GetZDO().GetInt(ZDOVars.s_state, 0); } private static bool TryGetZdo(Piece piece, out ZDO zdo) { zdo = null; if (!Object.op_Implicit((Object)(object)piece) || !Object.op_Implicit((Object)(object)piece.m_nview) || !piece.m_nview.IsValid()) { return false; } zdo = piece.m_nview.GetZDO(); return zdo != null; } private static void MarkZdoFields(ZDO zdo, params string[] fieldFlags) { zdo.Set("HasFields", true); foreach (string text in fieldFlags) { zdo.Set(text, true); } } } internal sealed class HarnessPrefabsFermenterHoverProxy : MonoBehaviour, Hoverable, Interactable { public string GetHoverName() { Fermenter componentInParent = ((Component)this).GetComponentInParent(); if (!Object.op_Implicit((Object)(object)componentInParent)) { return ""; } return componentInParent.GetHoverName(); } public string GetHoverText() { Fermenter componentInParent = ((Component)this).GetComponentInParent(); if (!Object.op_Implicit((Object)(object)componentInParent)) { return ""; } return componentInParent.GetHoverText(); } public bool Interact(Humanoid user, bool hold, bool alt) { Fermenter componentInParent = ((Component)this).GetComponentInParent(); if (Object.op_Implicit((Object)(object)componentInParent)) { return componentInParent.Interact(user, hold, alt); } return false; } public bool UseItem(Humanoid user, ItemData item) { Fermenter componentInParent = ((Component)this).GetComponentInParent(); if (Object.op_Implicit((Object)(object)componentInParent)) { return componentInParent.UseItem(user, item); } return false; } } internal static class HarnessPrefabsConsoleCommands { [CompilerGenerated] private static class <>O { public static ConsoleEvent <0>__WriteFullScaffoldFile; } private const string WriteFullCommandName = "harnessprefabs:full"; private static bool _registered; public static void Register() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown if (!_registered) { _registered = true; object obj = <>O.<0>__WriteFullScaffoldFile; if (obj == null) { ConsoleEvent val = WriteFullScaffoldFile; <>O.<0>__WriteFullScaffoldFile = val; obj = (object)val; } new ConsoleCommand("harnessprefabs:full", "Write HarnessPrefabs full scaffold YAML with explicit active defaults. Usage: harnessprefabs:full", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } private static void WriteFullScaffoldFile(ConsoleEventArgs args) { if (PrefabRuleStore.TryWriteFullScaffoldConfigurationFile(out string path, out string error)) { Terminal context = args.Context; if (context != null) { context.AddString("Wrote prefab full scaffold to " + path); } } else { Terminal context2 = args.Context; if (context2 != null) { context2.AddString(error); } } } } internal sealed class PrefabIconRenderer : MonoBehaviour { private static readonly HashSet DoNotUseJotunnCache = new HashSet(StringComparer.Ordinal) { "portal", "dvergrprops_wood_floor", "dvergrprops_wood_stair" }; private static PrefabIconRenderer _instance; private static readonly HashSet RenderedPrefabNames = new HashSet(StringComparer.Ordinal); private readonly Queue _queue = new Queue(); private readonly HashSet _queued = new HashSet(); private readonly HashSet _queuedPrefabNames = new HashSet(StringComparer.Ordinal); private bool _processing; public static void QueueIcon(Piece piece) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Invalid comparison between Unknown and I4 if (Object.op_Implicit((Object)(object)piece) && !Application.isBatchMode && (int)SystemInfo.graphicsDeviceType != 4) { EnsureInstance().Enqueue(piece); } } private static PrefabIconRenderer EnsureInstance() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (Object.op_Implicit((Object)(object)_instance)) { return _instance; } GameObject val = new GameObject("HarnessPrefabs_IconRenderer"); Object.DontDestroyOnLoad((Object)val); _instance = val.AddComponent(); return _instance; } private void Enqueue(Piece piece) { string text = (Object.op_Implicit((Object)(object)((Component)piece).gameObject) ? ((Object)((Component)piece).gameObject).name : ""); if ((text.Length > 0 && RenderedPrefabNames.Contains(text) && Object.op_Implicit((Object)(object)piece.m_icon)) || (text.Length > 0 && !_queuedPrefabNames.Add(text))) { return; } int instanceID = ((Object)piece).GetInstanceID(); if (_queued.Add(instanceID)) { _queue.Enqueue(piece); if (!_processing) { ((MonoBehaviour)this).StartCoroutine(ProcessQueue()); } } } private IEnumerator ProcessQueue() { _processing = true; yield return (object)new WaitForEndOfFrame(); int rendered = 0; int failed = 0; while (_queue.Count > 0) { Piece val = _queue.Dequeue(); if (!Object.op_Implicit((Object)(object)val)) { continue; } GameObject gameObject = ((Component)val).gameObject; Sprite val2 = TryRenderWithJotunn(gameObject); if (Object.op_Implicit((Object)(object)val2)) { val.m_icon = val2; if (((Object)gameObject).name.Length > 0) { RenderedPrefabNames.Add(((Object)gameObject).name); } rendered++; } else { failed++; } if ((rendered + failed) % 4 == 0) { yield return null; } } _queued.Clear(); _queuedPrefabNames.Clear(); _processing = false; if (HarnessPrefabsPlugin.Verbose && (rendered > 0 || failed > 0)) { HarnessPrefabsPlugin.Log.LogInfo((object)$"Icon render queue complete: rendered={rendered}, failed={failed}."); } } private static Sprite TryRenderWithJotunn(GameObject prefab) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)prefab) || IsEffectLike(prefab)) { return null; } try { RenderRequest val = new RenderRequest(prefab) { Rotation = RenderManager.IsometricRotation, UseCache = !DoNotUseJotunnCache.Contains(((Object)prefab).name) }; Sprite val2 = RenderManager.Instance.Render(val); if (!Object.op_Implicit((Object)(object)val2)) { val2 = TryRenderPickableItemFallback(prefab); } return val2; } catch (Exception ex) { if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogWarning((object)("Jotunn icon render failed for " + ((Object)prefab).name + ": " + ex.Message)); } return null; } } private static Sprite TryRenderPickableItemFallback(GameObject prefab) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Expected O, but got Unknown RandomItem[] array = prefab.GetComponent()?.m_randomItemPrefabs; if (array == null || array.Length == 0) { return null; } ItemDrop itemPrefab = array[0].m_itemPrefab; GameObject val = (Object.op_Implicit((Object)(object)itemPrefab) ? ((Component)itemPrefab).gameObject : null); if (!Object.op_Implicit((Object)(object)val)) { return null; } RenderRequest val2 = new RenderRequest(val) { Rotation = RenderManager.IsometricRotation, UseCache = true }; return RenderManager.Instance.Render(val2); } private static bool IsEffectLike(GameObject prefab) { if (Object.op_Implicit((Object)(object)prefab)) { if (!((Object)prefab).name.StartsWith("fx_", StringComparison.Ordinal) && !((Object)prefab).name.StartsWith("vfx_", StringComparison.Ordinal) && !((Object)prefab).name.StartsWith("sfx_", StringComparison.Ordinal)) { return Object.op_Implicit((Object)(object)prefab.GetComponent()); } return true; } return false; } } internal static class PrefabMvbpFixups { private const float SnapPointTolerance = 0.001f; public static void Apply(GameObject prefab) { if (!Object.op_Implicit((Object)(object)prefab)) { return; } bool flag = Object.op_Implicit((Object)(object)prefab.GetComponent()); if (((Object)prefab).name.Equals("Trailership", StringComparison.Ordinal)) { if (ApplyTrailershipFixup(prefab, !flag) && !flag) { prefab.AddComponent(); } } else if (!flag && ApplyByName(prefab) && !flag) { prefab.AddComponent(); } } private static bool ApplyByName(GameObject prefab) { //IL_23ef: Unknown result type (might be due to invalid IL or missing references) //IL_23f4: Unknown result type (might be due to invalid IL or missing references) //IL_1e1d: Unknown result type (might be due to invalid IL or missing references) //IL_1e22: Unknown result type (might be due to invalid IL or missing references) //IL_1e38: Unknown result type (might be due to invalid IL or missing references) //IL_1e3d: Unknown result type (might be due to invalid IL or missing references) //IL_1e53: Unknown result type (might be due to invalid IL or missing references) //IL_1e58: Unknown result type (might be due to invalid IL or missing references) //IL_1e6e: Unknown result type (might be due to invalid IL or missing references) //IL_1e73: Unknown result type (might be due to invalid IL or missing references) //IL_1e89: Unknown result type (might be due to invalid IL or missing references) //IL_1e8e: Unknown result type (might be due to invalid IL or missing references) //IL_1ea4: Unknown result type (might be due to invalid IL or missing references) //IL_1ea9: Unknown result type (might be due to invalid IL or missing references) //IL_1ebf: Unknown result type (might be due to invalid IL or missing references) //IL_1ec4: Unknown result type (might be due to invalid IL or missing references) //IL_1eda: Unknown result type (might be due to invalid IL or missing references) //IL_1edf: Unknown result type (might be due to invalid IL or missing references) //IL_21fe: Unknown result type (might be due to invalid IL or missing references) //IL_2203: Unknown result type (might be due to invalid IL or missing references) //IL_2219: Unknown result type (might be due to invalid IL or missing references) //IL_221e: Unknown result type (might be due to invalid IL or missing references) //IL_2234: Unknown result type (might be due to invalid IL or missing references) //IL_2239: Unknown result type (might be due to invalid IL or missing references) //IL_224f: Unknown result type (might be due to invalid IL or missing references) //IL_2254: Unknown result type (might be due to invalid IL or missing references) //IL_226a: Unknown result type (might be due to invalid IL or missing references) //IL_226f: Unknown result type (might be due to invalid IL or missing references) //IL_1f36: Unknown result type (might be due to invalid IL or missing references) //IL_1f3b: Unknown result type (might be due to invalid IL or missing references) //IL_1f51: Unknown result type (might be due to invalid IL or missing references) //IL_1f56: Unknown result type (might be due to invalid IL or missing references) //IL_1f6c: Unknown result type (might be due to invalid IL or missing references) //IL_1f71: Unknown result type (might be due to invalid IL or missing references) //IL_1f87: Unknown result type (might be due to invalid IL or missing references) //IL_1f8c: Unknown result type (might be due to invalid IL or missing references) //IL_1fa2: Unknown result type (might be due to invalid IL or missing references) //IL_1fa7: Unknown result type (might be due to invalid IL or missing references) //IL_0a1e: Unknown result type (might be due to invalid IL or missing references) //IL_0a23: Unknown result type (might be due to invalid IL or missing references) //IL_0a39: Unknown result type (might be due to invalid IL or missing references) //IL_0a3e: Unknown result type (might be due to invalid IL or missing references) //IL_0a54: Unknown result type (might be due to invalid IL or missing references) //IL_0a59: Unknown result type (might be due to invalid IL or missing references) //IL_0a6f: Unknown result type (might be due to invalid IL or missing references) //IL_0a74: Unknown result type (might be due to invalid IL or missing references) //IL_0a8a: Unknown result type (might be due to invalid IL or missing references) //IL_0a8f: Unknown result type (might be due to invalid IL or missing references) //IL_0aa5: Unknown result type (might be due to invalid IL or missing references) //IL_0aaa: Unknown result type (might be due to invalid IL or missing references) //IL_0ac0: Unknown result type (might be due to invalid IL or missing references) //IL_0ac5: Unknown result type (might be due to invalid IL or missing references) //IL_0adb: Unknown result type (might be due to invalid IL or missing references) //IL_0ae0: Unknown result type (might be due to invalid IL or missing references) //IL_0af6: Unknown result type (might be due to invalid IL or missing references) //IL_0afb: Unknown result type (might be due to invalid IL or missing references) //IL_261b: Unknown result type (might be due to invalid IL or missing references) //IL_2620: Unknown result type (might be due to invalid IL or missing references) //IL_2636: Unknown result type (might be due to invalid IL or missing references) //IL_263b: Unknown result type (might be due to invalid IL or missing references) //IL_2651: Unknown result type (might be due to invalid IL or missing references) //IL_2656: Unknown result type (might be due to invalid IL or missing references) //IL_266c: Unknown result type (might be due to invalid IL or missing references) //IL_2671: Unknown result type (might be due to invalid IL or missing references) //IL_2687: Unknown result type (might be due to invalid IL or missing references) //IL_268c: Unknown result type (might be due to invalid IL or missing references) //IL_26a2: Unknown result type (might be due to invalid IL or missing references) //IL_26a7: Unknown result type (might be due to invalid IL or missing references) //IL_26bd: Unknown result type (might be due to invalid IL or missing references) //IL_26c2: Unknown result type (might be due to invalid IL or missing references) //IL_26d8: Unknown result type (might be due to invalid IL or missing references) //IL_26dd: Unknown result type (might be due to invalid IL or missing references) //IL_16ec: Unknown result type (might be due to invalid IL or missing references) //IL_16f1: Unknown result type (might be due to invalid IL or missing references) //IL_1707: Unknown result type (might be due to invalid IL or missing references) //IL_170c: Unknown result type (might be due to invalid IL or missing references) //IL_1912: Unknown result type (might be due to invalid IL or missing references) //IL_1917: Unknown result type (might be due to invalid IL or missing references) //IL_192d: Unknown result type (might be due to invalid IL or missing references) //IL_1932: Unknown result type (might be due to invalid IL or missing references) //IL_1948: Unknown result type (might be due to invalid IL or missing references) //IL_194d: Unknown result type (might be due to invalid IL or missing references) //IL_1963: Unknown result type (might be due to invalid IL or missing references) //IL_1968: Unknown result type (might be due to invalid IL or missing references) //IL_197e: Unknown result type (might be due to invalid IL or missing references) //IL_1983: Unknown result type (might be due to invalid IL or missing references) //IL_1999: Unknown result type (might be due to invalid IL or missing references) //IL_199e: Unknown result type (might be due to invalid IL or missing references) //IL_19b4: Unknown result type (might be due to invalid IL or missing references) //IL_19b9: Unknown result type (might be due to invalid IL or missing references) //IL_247a: Unknown result type (might be due to invalid IL or missing references) //IL_247f: Unknown result type (might be due to invalid IL or missing references) //IL_2495: Unknown result type (might be due to invalid IL or missing references) //IL_249a: Unknown result type (might be due to invalid IL or missing references) //IL_24b0: Unknown result type (might be due to invalid IL or missing references) //IL_24b5: Unknown result type (might be due to invalid IL or missing references) //IL_24cb: Unknown result type (might be due to invalid IL or missing references) //IL_24d0: Unknown result type (might be due to invalid IL or missing references) //IL_24e6: Unknown result type (might be due to invalid IL or missing references) //IL_24eb: Unknown result type (might be due to invalid IL or missing references) //IL_2501: Unknown result type (might be due to invalid IL or missing references) //IL_2506: Unknown result type (might be due to invalid IL or missing references) //IL_09ec: Unknown result type (might be due to invalid IL or missing references) //IL_2290: Unknown result type (might be due to invalid IL or missing references) //IL_22a4: Unknown result type (might be due to invalid IL or missing references) //IL_22af: Unknown result type (might be due to invalid IL or missing references) //IL_22c3: Unknown result type (might be due to invalid IL or missing references) //IL_22d6: Unknown result type (might be due to invalid IL or missing references) //IL_22db: Unknown result type (might be due to invalid IL or missing references) //IL_22f1: Unknown result type (might be due to invalid IL or missing references) //IL_22f6: Unknown result type (might be due to invalid IL or missing references) //IL_20ad: Unknown result type (might be due to invalid IL or missing references) //IL_20b2: Unknown result type (might be due to invalid IL or missing references) //IL_20c8: Unknown result type (might be due to invalid IL or missing references) //IL_20cd: Unknown result type (might be due to invalid IL or missing references) //IL_20e3: Unknown result type (might be due to invalid IL or missing references) //IL_20e8: Unknown result type (might be due to invalid IL or missing references) //IL_20fe: Unknown result type (might be due to invalid IL or missing references) //IL_2103: Unknown result type (might be due to invalid IL or missing references) //IL_2119: Unknown result type (might be due to invalid IL or missing references) //IL_211e: Unknown result type (might be due to invalid IL or missing references) //IL_2134: Unknown result type (might be due to invalid IL or missing references) //IL_2139: Unknown result type (might be due to invalid IL or missing references) //IL_214f: Unknown result type (might be due to invalid IL or missing references) //IL_2154: Unknown result type (might be due to invalid IL or missing references) //IL_216a: Unknown result type (might be due to invalid IL or missing references) //IL_216f: Unknown result type (might be due to invalid IL or missing references) //IL_2185: Unknown result type (might be due to invalid IL or missing references) //IL_218a: Unknown result type (might be due to invalid IL or missing references) //IL_21a1: Unknown result type (might be due to invalid IL or missing references) //IL_21a6: Unknown result type (might be due to invalid IL or missing references) //IL_21c6: Unknown result type (might be due to invalid IL or missing references) //IL_21da: Unknown result type (might be due to invalid IL or missing references) //IL_1d2b: Unknown result type (might be due to invalid IL or missing references) //IL_1d30: Unknown result type (might be due to invalid IL or missing references) //IL_1d46: Unknown result type (might be due to invalid IL or missing references) //IL_1d4b: Unknown result type (might be due to invalid IL or missing references) //IL_1d61: Unknown result type (might be due to invalid IL or missing references) //IL_1d66: Unknown result type (might be due to invalid IL or missing references) //IL_1d7c: Unknown result type (might be due to invalid IL or missing references) //IL_1d81: Unknown result type (might be due to invalid IL or missing references) //IL_1da4: Unknown result type (might be due to invalid IL or missing references) //IL_1da9: Unknown result type (might be due to invalid IL or missing references) //IL_1dbf: Unknown result type (might be due to invalid IL or missing references) //IL_1dc4: Unknown result type (might be due to invalid IL or missing references) //IL_1dda: Unknown result type (might be due to invalid IL or missing references) //IL_1ddf: Unknown result type (might be due to invalid IL or missing references) //IL_1df5: Unknown result type (might be due to invalid IL or missing references) //IL_1dfa: Unknown result type (might be due to invalid IL or missing references) //IL_2700: Unknown result type (might be due to invalid IL or missing references) //IL_2705: Unknown result type (might be due to invalid IL or missing references) //IL_271b: Unknown result type (might be due to invalid IL or missing references) //IL_2720: Unknown result type (might be due to invalid IL or missing references) //IL_2736: Unknown result type (might be due to invalid IL or missing references) //IL_273b: Unknown result type (might be due to invalid IL or missing references) //IL_2751: Unknown result type (might be due to invalid IL or missing references) //IL_2756: Unknown result type (might be due to invalid IL or missing references) //IL_276c: Unknown result type (might be due to invalid IL or missing references) //IL_2771: Unknown result type (might be due to invalid IL or missing references) //IL_2787: Unknown result type (might be due to invalid IL or missing references) //IL_278c: Unknown result type (might be due to invalid IL or missing references) //IL_27a2: Unknown result type (might be due to invalid IL or missing references) //IL_27a7: Unknown result type (might be due to invalid IL or missing references) //IL_27bd: Unknown result type (might be due to invalid IL or missing references) //IL_27c2: Unknown result type (might be due to invalid IL or missing references) //IL_110b: Unknown result type (might be due to invalid IL or missing references) //IL_1110: Unknown result type (might be due to invalid IL or missing references) //IL_1126: Unknown result type (might be due to invalid IL or missing references) //IL_112b: Unknown result type (might be due to invalid IL or missing references) //IL_1141: Unknown result type (might be due to invalid IL or missing references) //IL_1146: Unknown result type (might be due to invalid IL or missing references) //IL_115c: Unknown result type (might be due to invalid IL or missing references) //IL_1161: Unknown result type (might be due to invalid IL or missing references) //IL_1177: Unknown result type (might be due to invalid IL or missing references) //IL_117c: Unknown result type (might be due to invalid IL or missing references) //IL_1192: Unknown result type (might be due to invalid IL or missing references) //IL_1197: Unknown result type (might be due to invalid IL or missing references) //IL_23a7: Unknown result type (might be due to invalid IL or missing references) //IL_23c6: Unknown result type (might be due to invalid IL or missing references) //IL_1899: Unknown result type (might be due to invalid IL or missing references) //IL_189e: Unknown result type (might be due to invalid IL or missing references) //IL_18b4: Unknown result type (might be due to invalid IL or missing references) //IL_18b9: Unknown result type (might be due to invalid IL or missing references) //IL_18cf: Unknown result type (might be due to invalid IL or missing references) //IL_18d4: Unknown result type (might be due to invalid IL or missing references) //IL_18ea: Unknown result type (might be due to invalid IL or missing references) //IL_18ef: Unknown result type (might be due to invalid IL or missing references) //IL_0eb0: Unknown result type (might be due to invalid IL or missing references) //IL_0eb5: Unknown result type (might be due to invalid IL or missing references) //IL_0ecb: Unknown result type (might be due to invalid IL or missing references) //IL_0ed0: Unknown result type (might be due to invalid IL or missing references) //IL_0ee6: Unknown result type (might be due to invalid IL or missing references) //IL_0eeb: Unknown result type (might be due to invalid IL or missing references) //IL_0f01: Unknown result type (might be due to invalid IL or missing references) //IL_0f06: Unknown result type (might be due to invalid IL or missing references) //IL_0f1c: Unknown result type (might be due to invalid IL or missing references) //IL_0f21: Unknown result type (might be due to invalid IL or missing references) //IL_0f37: Unknown result type (might be due to invalid IL or missing references) //IL_0f3c: Unknown result type (might be due to invalid IL or missing references) //IL_1f02: Unknown result type (might be due to invalid IL or missing references) //IL_1f07: Unknown result type (might be due to invalid IL or missing references) //IL_1f1d: Unknown result type (might be due to invalid IL or missing references) //IL_1f22: Unknown result type (might be due to invalid IL or missing references) //IL_1871: Unknown result type (might be due to invalid IL or missing references) //IL_1876: Unknown result type (might be due to invalid IL or missing references) //IL_2400: Unknown result type (might be due to invalid IL or missing references) //IL_2414: Unknown result type (might be due to invalid IL or missing references) //IL_16a9: Unknown result type (might be due to invalid IL or missing references) //IL_16ae: Unknown result type (might be due to invalid IL or missing references) //IL_16c4: Unknown result type (might be due to invalid IL or missing references) //IL_16c9: Unknown result type (might be due to invalid IL or missing references) //IL_207d: Unknown result type (might be due to invalid IL or missing references) //IL_2091: Unknown result type (might be due to invalid IL or missing references) //IL_19e3: Unknown result type (might be due to invalid IL or missing references) //IL_19e8: Unknown result type (might be due to invalid IL or missing references) //IL_19fe: Unknown result type (might be due to invalid IL or missing references) //IL_1a03: Unknown result type (might be due to invalid IL or missing references) //IL_1772: Unknown result type (might be due to invalid IL or missing references) //IL_1777: Unknown result type (might be due to invalid IL or missing references) //IL_178d: Unknown result type (might be due to invalid IL or missing references) //IL_1792: Unknown result type (might be due to invalid IL or missing references) //IL_1ace: Unknown result type (might be due to invalid IL or missing references) //IL_1ad3: Unknown result type (might be due to invalid IL or missing references) //IL_1ae9: Unknown result type (might be due to invalid IL or missing references) //IL_1aee: Unknown result type (might be due to invalid IL or missing references) //IL_1b04: Unknown result type (might be due to invalid IL or missing references) //IL_1b09: Unknown result type (might be due to invalid IL or missing references) //IL_1b1f: Unknown result type (might be due to invalid IL or missing references) //IL_1b24: Unknown result type (might be due to invalid IL or missing references) //IL_1aac: Unknown result type (might be due to invalid IL or missing references) //IL_1b47: Unknown result type (might be due to invalid IL or missing references) //IL_1b4c: Unknown result type (might be due to invalid IL or missing references) //IL_1b62: Unknown result type (might be due to invalid IL or missing references) //IL_1b67: Unknown result type (might be due to invalid IL or missing references) //IL_1b7d: Unknown result type (might be due to invalid IL or missing references) //IL_1b82: Unknown result type (might be due to invalid IL or missing references) //IL_1b98: Unknown result type (might be due to invalid IL or missing references) //IL_1b9d: Unknown result type (might be due to invalid IL or missing references) //IL_2317: Unknown result type (might be due to invalid IL or missing references) //IL_232b: Unknown result type (might be due to invalid IL or missing references) //IL_2345: Unknown result type (might be due to invalid IL or missing references) //IL_2359: Unknown result type (might be due to invalid IL or missing references) //IL_236c: Unknown result type (might be due to invalid IL or missing references) //IL_2371: Unknown result type (might be due to invalid IL or missing references) //IL_2387: Unknown result type (might be due to invalid IL or missing references) //IL_238c: Unknown result type (might be due to invalid IL or missing references) //IL_1a67: Unknown result type (might be due to invalid IL or missing references) //IL_1a6c: Unknown result type (might be due to invalid IL or missing references) //IL_1a82: Unknown result type (might be due to invalid IL or missing references) //IL_1a87: Unknown result type (might be due to invalid IL or missing references) //IL_130f: Unknown result type (might be due to invalid IL or missing references) //IL_1334: Unknown result type (might be due to invalid IL or missing references) //IL_1359: Unknown result type (might be due to invalid IL or missing references) //IL_137e: Unknown result type (might be due to invalid IL or missing references) //IL_13a3: Unknown result type (might be due to invalid IL or missing references) //IL_13c8: Unknown result type (might be due to invalid IL or missing references) //IL_13ed: Unknown result type (might be due to invalid IL or missing references) //IL_1412: Unknown result type (might be due to invalid IL or missing references) //IL_1444: Unknown result type (might be due to invalid IL or missing references) //IL_1469: Unknown result type (might be due to invalid IL or missing references) //IL_148e: Unknown result type (might be due to invalid IL or missing references) //IL_14b3: Unknown result type (might be due to invalid IL or missing references) //IL_14d8: Unknown result type (might be due to invalid IL or missing references) //IL_14fd: Unknown result type (might be due to invalid IL or missing references) //IL_1522: Unknown result type (might be due to invalid IL or missing references) //IL_1547: Unknown result type (might be due to invalid IL or missing references) //IL_1579: Unknown result type (might be due to invalid IL or missing references) //IL_159e: Unknown result type (might be due to invalid IL or missing references) //IL_15c3: Unknown result type (might be due to invalid IL or missing references) //IL_15e8: Unknown result type (might be due to invalid IL or missing references) //IL_160d: Unknown result type (might be due to invalid IL or missing references) //IL_1632: Unknown result type (might be due to invalid IL or missing references) //IL_1657: Unknown result type (might be due to invalid IL or missing references) //IL_167c: Unknown result type (might be due to invalid IL or missing references) //IL_11cd: Unknown result type (might be due to invalid IL or missing references) //IL_11f2: Unknown result type (might be due to invalid IL or missing references) //IL_1217: Unknown result type (might be due to invalid IL or missing references) //IL_123c: Unknown result type (might be due to invalid IL or missing references) //IL_0f5f: Unknown result type (might be due to invalid IL or missing references) //IL_0f64: Unknown result type (might be due to invalid IL or missing references) //IL_0f7a: Unknown result type (might be due to invalid IL or missing references) //IL_0f7f: Unknown result type (might be due to invalid IL or missing references) //IL_0f95: Unknown result type (might be due to invalid IL or missing references) //IL_0f9a: Unknown result type (might be due to invalid IL or missing references) //IL_0fb0: Unknown result type (might be due to invalid IL or missing references) //IL_0fb5: Unknown result type (might be due to invalid IL or missing references) //IL_0fcb: Unknown result type (might be due to invalid IL or missing references) //IL_0fd0: Unknown result type (might be due to invalid IL or missing references) //IL_0fe6: Unknown result type (might be due to invalid IL or missing references) //IL_0feb: Unknown result type (might be due to invalid IL or missing references) //IL_1c6f: Unknown result type (might be due to invalid IL or missing references) //IL_1c74: Unknown result type (might be due to invalid IL or missing references) //IL_1c8a: Unknown result type (might be due to invalid IL or missing references) //IL_1c8f: Unknown result type (might be due to invalid IL or missing references) //IL_1ca5: Unknown result type (might be due to invalid IL or missing references) //IL_1caa: Unknown result type (might be due to invalid IL or missing references) //IL_1cc0: Unknown result type (might be due to invalid IL or missing references) //IL_1cc5: Unknown result type (might be due to invalid IL or missing references) //IL_2457: Unknown result type (might be due to invalid IL or missing references) //IL_0b25: Unknown result type (might be due to invalid IL or missing references) //IL_0b2a: Unknown result type (might be due to invalid IL or missing references) //IL_0b40: Unknown result type (might be due to invalid IL or missing references) //IL_0b45: Unknown result type (might be due to invalid IL or missing references) //IL_0b5b: Unknown result type (might be due to invalid IL or missing references) //IL_0b60: Unknown result type (might be due to invalid IL or missing references) //IL_0b76: Unknown result type (might be due to invalid IL or missing references) //IL_0b7b: Unknown result type (might be due to invalid IL or missing references) //IL_0b91: Unknown result type (might be due to invalid IL or missing references) //IL_0b96: Unknown result type (might be due to invalid IL or missing references) //IL_0bac: Unknown result type (might be due to invalid IL or missing references) //IL_0bb1: Unknown result type (might be due to invalid IL or missing references) //IL_0bc7: Unknown result type (might be due to invalid IL or missing references) //IL_0bcc: Unknown result type (might be due to invalid IL or missing references) //IL_0be2: Unknown result type (might be due to invalid IL or missing references) //IL_0be7: Unknown result type (might be due to invalid IL or missing references) //IL_0bfd: Unknown result type (might be due to invalid IL or missing references) //IL_0c02: Unknown result type (might be due to invalid IL or missing references) //IL_17b5: Unknown result type (might be due to invalid IL or missing references) //IL_17ba: Unknown result type (might be due to invalid IL or missing references) //IL_17d0: Unknown result type (might be due to invalid IL or missing references) //IL_17d5: Unknown result type (might be due to invalid IL or missing references) //IL_1a3f: Unknown result type (might be due to invalid IL or missing references) //IL_1a44: Unknown result type (might be due to invalid IL or missing references) //IL_1a17: Unknown result type (might be due to invalid IL or missing references) //IL_1a1c: Unknown result type (might be due to invalid IL or missing references) //IL_1bc0: Unknown result type (might be due to invalid IL or missing references) //IL_1bc5: Unknown result type (might be due to invalid IL or missing references) //IL_1bdb: Unknown result type (might be due to invalid IL or missing references) //IL_1be0: Unknown result type (might be due to invalid IL or missing references) //IL_1bf6: Unknown result type (might be due to invalid IL or missing references) //IL_1bfb: Unknown result type (might be due to invalid IL or missing references) //IL_1c11: Unknown result type (might be due to invalid IL or missing references) //IL_1c16: Unknown result type (might be due to invalid IL or missing references) //IL_1c2c: Unknown result type (might be due to invalid IL or missing references) //IL_1c31: Unknown result type (might be due to invalid IL or missing references) //IL_1c47: Unknown result type (might be due to invalid IL or missing references) //IL_1c4c: Unknown result type (might be due to invalid IL or missing references) //IL_1ce8: Unknown result type (might be due to invalid IL or missing references) //IL_1ced: Unknown result type (might be due to invalid IL or missing references) //IL_1d03: Unknown result type (might be due to invalid IL or missing references) //IL_1d08: Unknown result type (might be due to invalid IL or missing references) //IL_100e: Unknown result type (might be due to invalid IL or missing references) //IL_1013: Unknown result type (might be due to invalid IL or missing references) //IL_1029: Unknown result type (might be due to invalid IL or missing references) //IL_102e: Unknown result type (might be due to invalid IL or missing references) //IL_1044: Unknown result type (might be due to invalid IL or missing references) //IL_1049: Unknown result type (might be due to invalid IL or missing references) //IL_105f: Unknown result type (might be due to invalid IL or missing references) //IL_1064: Unknown result type (might be due to invalid IL or missing references) //IL_107a: Unknown result type (might be due to invalid IL or missing references) //IL_107f: Unknown result type (might be due to invalid IL or missing references) //IL_1095: Unknown result type (might be due to invalid IL or missing references) //IL_109a: Unknown result type (might be due to invalid IL or missing references) //IL_252a: Unknown result type (might be due to invalid IL or missing references) //IL_252f: Unknown result type (might be due to invalid IL or missing references) //IL_2545: Unknown result type (might be due to invalid IL or missing references) //IL_254a: Unknown result type (might be due to invalid IL or missing references) //IL_2560: Unknown result type (might be due to invalid IL or missing references) //IL_2565: Unknown result type (might be due to invalid IL or missing references) //IL_257b: Unknown result type (might be due to invalid IL or missing references) //IL_2580: Unknown result type (might be due to invalid IL or missing references) //IL_2596: Unknown result type (might be due to invalid IL or missing references) //IL_259b: Unknown result type (might be due to invalid IL or missing references) //IL_25b1: Unknown result type (might be due to invalid IL or missing references) //IL_25b6: Unknown result type (might be due to invalid IL or missing references) //IL_25cc: Unknown result type (might be due to invalid IL or missing references) //IL_25d1: Unknown result type (might be due to invalid IL or missing references) //IL_25e7: Unknown result type (might be due to invalid IL or missing references) //IL_25ec: Unknown result type (might be due to invalid IL or missing references) //IL_25f3: Unknown result type (might be due to invalid IL or missing references) //IL_25f8: Unknown result type (might be due to invalid IL or missing references) //IL_126e: Unknown result type (might be due to invalid IL or missing references) //IL_1293: Unknown result type (might be due to invalid IL or missing references) //IL_12b8: Unknown result type (might be due to invalid IL or missing references) //IL_12dd: Unknown result type (might be due to invalid IL or missing references) //IL_27f5: Unknown result type (might be due to invalid IL or missing references) //IL_27fa: Unknown result type (might be due to invalid IL or missing references) //IL_2801: Unknown result type (might be due to invalid IL or missing references) //IL_2806: Unknown result type (might be due to invalid IL or missing references) //IL_281c: Unknown result type (might be due to invalid IL or missing references) //IL_2821: Unknown result type (might be due to invalid IL or missing references) //IL_2421: Unknown result type (might be due to invalid IL or missing references) //IL_172f: Unknown result type (might be due to invalid IL or missing references) //IL_1734: Unknown result type (might be due to invalid IL or missing references) //IL_174a: Unknown result type (might be due to invalid IL or missing references) //IL_174f: Unknown result type (might be due to invalid IL or missing references) //IL_17f8: Unknown result type (might be due to invalid IL or missing references) //IL_17fd: Unknown result type (might be due to invalid IL or missing references) //IL_1813: Unknown result type (might be due to invalid IL or missing references) //IL_1818: Unknown result type (might be due to invalid IL or missing references) //IL_182e: Unknown result type (might be due to invalid IL or missing references) //IL_1833: Unknown result type (might be due to invalid IL or missing references) //IL_1849: Unknown result type (might be due to invalid IL or missing references) //IL_184e: Unknown result type (might be due to invalid IL or missing references) //IL_0c6c: Unknown result type (might be due to invalid IL or missing references) //IL_0c71: Unknown result type (might be due to invalid IL or missing references) //IL_0c87: Unknown result type (might be due to invalid IL or missing references) //IL_0c8c: Unknown result type (might be due to invalid IL or missing references) //IL_0ca2: Unknown result type (might be due to invalid IL or missing references) //IL_0ca7: Unknown result type (might be due to invalid IL or missing references) //IL_0cbd: Unknown result type (might be due to invalid IL or missing references) //IL_0cc2: Unknown result type (might be due to invalid IL or missing references) //IL_0cd8: Unknown result type (might be due to invalid IL or missing references) //IL_0cdd: Unknown result type (might be due to invalid IL or missing references) //IL_0cf3: Unknown result type (might be due to invalid IL or missing references) //IL_0cf8: Unknown result type (might be due to invalid IL or missing references) //IL_0d0e: Unknown result type (might be due to invalid IL or missing references) //IL_0d13: Unknown result type (might be due to invalid IL or missing references) //IL_0d29: Unknown result type (might be due to invalid IL or missing references) //IL_0d2e: Unknown result type (might be due to invalid IL or missing references) //IL_0d44: Unknown result type (might be due to invalid IL or missing references) //IL_0d49: Unknown result type (might be due to invalid IL or missing references) //IL_0d60: Unknown result type (might be due to invalid IL or missing references) //IL_0d65: Unknown result type (might be due to invalid IL or missing references) //IL_243c: Unknown result type (might be due to invalid IL or missing references) //IL_0d94: Unknown result type (might be due to invalid IL or missing references) //IL_0d99: Unknown result type (might be due to invalid IL or missing references) //IL_0daf: Unknown result type (might be due to invalid IL or missing references) //IL_0db4: Unknown result type (might be due to invalid IL or missing references) //IL_0dca: Unknown result type (might be due to invalid IL or missing references) //IL_0dcf: Unknown result type (might be due to invalid IL or missing references) //IL_0de5: Unknown result type (might be due to invalid IL or missing references) //IL_0dea: Unknown result type (might be due to invalid IL or missing references) //IL_0e00: Unknown result type (might be due to invalid IL or missing references) //IL_0e05: Unknown result type (might be due to invalid IL or missing references) //IL_0e1b: Unknown result type (might be due to invalid IL or missing references) //IL_0e20: Unknown result type (might be due to invalid IL or missing references) //IL_0e36: Unknown result type (might be due to invalid IL or missing references) //IL_0e3b: Unknown result type (might be due to invalid IL or missing references) //IL_0e51: Unknown result type (might be due to invalid IL or missing references) //IL_0e56: Unknown result type (might be due to invalid IL or missing references) //IL_0e6c: Unknown result type (might be due to invalid IL or missing references) //IL_0e71: Unknown result type (might be due to invalid IL or missing references) //IL_0e88: Unknown result type (might be due to invalid IL or missing references) //IL_0e8d: Unknown result type (might be due to invalid IL or missing references) //IL_203b: Unknown result type (might be due to invalid IL or missing references) //IL_1fe4: Unknown result type (might be due to invalid IL or missing references) //IL_10c0: Unknown result type (might be due to invalid IL or missing references) List list = new List(); switch (((Object)prefab).name) { case "ArmorStand_Male": case "ArmorStand_Female": return AddSnapPoint(prefab, Vector3.zero, "Origin"); case "TreasureChest_mountaincave": case "TreasureChest_trollcave": FixPieceLayers(prefab); return AddSnapPointsToMeshCorners(prefab, "stonechest"); case "TreasureChest_dvergrtower": case "TreasureChest_dvergrtown": FixPieceLayers(prefab); return AddSnapPoints(prefab, Vector3.zero, new Vector3(0.66f, 0f, 0.33f), new Vector3(0.66f, 0f, -0.33f), new Vector3(-0.66f, 0f, 0.33f), new Vector3(-0.66f, 0f, -0.33f), new Vector3(0.6f, 0.7f, 0.33f), new Vector3(0.6f, 0.7f, -0.33f), new Vector3(-0.6f, 0.7f, 0.33f), new Vector3(-0.6f, 0.7f, -0.33f)); case "TreasureChest_plains_stone": case "TreasureChest_sunkencrypt": case "TreasureChest_fCrypt": FixPieceLayers(prefab); return AddSnapPoints(prefab, new Vector3(0f, -0.01f, 0f), new Vector3(1f, -0.01f, 0.37f), new Vector3(1f, -0.01f, -0.37f), new Vector3(-1f, -0.01f, 0.37f), new Vector3(-1f, -0.01f, -0.37f), new Vector3(0.65f, 0.8f, 0.35f), new Vector3(0.65f, 0.8f, -0.35f), new Vector3(-0.65f, 0.8f, 0.35f), new Vector3(-0.65f, 0.8f, -0.35f)); case "blackmarble_column_3": { for (float num3 = -4f; num3 <= 4f; num3 += 2f) { list.AddRange(BoxCornerPoints(1f, num3, 1f)); } return AddSnapPoints(prefab, (IEnumerable)list); } case "blackmarble_creep_4x1x1": RemoveRandomPieceRotation(prefab, "new"); return AddSnapPoints(prefab, new Vector3(-0.5f, 2f, -0.5f), new Vector3(0.5f, 2f, 0.5f), new Vector3(-0.5f, 2f, 0.5f), new Vector3(0.5f, 2f, -0.5f), new Vector3(-0.5f, -2f, -0.5f), new Vector3(0.5f, -2f, 0.5f), new Vector3(-0.5f, -2f, 0.5f), new Vector3(0.5f, -2f, -0.5f), new Vector3(0f, -2f, 0f), new Vector3(0f, 2f, 0f)); case "blackmarble_creep_4x2x1": RemoveRandomPieceRotation(prefab, "new"); return AddSnapPoints(prefab, new Vector3(1f, 2f, -0.5f), new Vector3(1f, 2f, 0.5f), new Vector3(-1f, 2f, -0.5f), new Vector3(-1f, 2f, 0.5f), new Vector3(1f, -2f, -0.5f), new Vector3(1f, -2f, 0.5f), new Vector3(-1f, -2f, -0.5f), new Vector3(-1f, -2f, 0.5f), new Vector3(0f, -2f, 0f), new Vector3(0f, 2f, 0f)); case "blackmarble_creep_slope_inverted_1x1x2": return AddSnapPoints(prefab, new Vector3(-0.5f, 1f, -0.5f), new Vector3(0.5f, 1f, 0.5f), new Vector3(-0.5f, 1f, 0.5f), new Vector3(0.5f, 1f, -0.5f), new Vector3(0.5f, -1f, -0.5f), new Vector3(-0.5f, -1f, -0.5f)); case "blackmarble_creep_slope_inverted_2x2x1": return AddSnapPoints(prefab, new Vector3(-1f, 0.5f, -1f), new Vector3(1f, 0.5f, 1f), new Vector3(-1f, 0.5f, 1f), new Vector3(1f, 0.5f, -1f), new Vector3(-1f, -0.5f, -1f), new Vector3(1f, -0.5f, -1f)); case "blackmarble_creep_stair": return AddSnapPoints(prefab, new Vector3(-1f, 1f, -1f), new Vector3(1f, 1f, -1f), new Vector3(-1f, 0f, -1f), new Vector3(1f, 0f, -1f), new Vector3(-1f, 0f, 1f), new Vector3(1f, 0f, 1f)); case "blackmarble_floor_large": { for (int m = -1; m <= 1; m += 2) { for (int n = -4; n <= 4; n += 2) { for (int num4 = -4; num4 <= 4; num4 += 2) { list.Add(new Vector3((float)n, (float)m, (float)num4)); } } } return AddSnapPoints(prefab, (IEnumerable)list); } case "blackmarble_head_big01": case "blackmarble_head_big02": return AddSnapPoints(prefab, new Vector3(-1f, 1f, -1f), new Vector3(1f, 1f, 1f), new Vector3(-1f, 1f, 1f), new Vector3(1f, 1f, -1f), new Vector3(1f, -1f, -1f), new Vector3(-1f, -1f, -1f)); case "blackmarble_out_2": RemoveComponent(prefab); FixPieceLayers(prefab); return true; case "blackmarble_tile_floor_1x1": return MoveSnapPoints(prefab, new(string, Vector3)[4] { ("_snappoint", new Vector3(0.5f, 0.1f, 0.5f)), ("_snappoint (1)", new Vector3(0.5f, 0.1f, -0.5f)), ("_snappoint (2)", new Vector3(-0.5f, 0.1f, 0.5f)), ("_snappoint (3)", new Vector3(-0.5f, 0.1f, -0.5f)) }); case "blackmarble_tile_floor_2x2": return MoveSnapPoints(prefab, new(string, Vector3)[4] { ("_snappoint", new Vector3(1f, 0.1f, 1f)), ("_snappoint (1)", new Vector3(1f, 0.1f, -1f)), ("_snappoint (2)", new Vector3(-1f, 0.1f, 1f)), ("_snappoint (3)", new Vector3(-1f, 0.1f, -1f)) }); case "blackmarble_tile_wall_1x1": return MoveSnapPoints(prefab, new(string, Vector3)[8] { ("_snappoint", new Vector3(0.5f, -0.05f, 0.1f)), ("_snappoint (1)", new Vector3(0.5f, 0.95f, 0.1f)), ("_snappoint (2)", new Vector3(-0.5f, -0.05f, 0.1f)), ("_snappoint (3)", new Vector3(-0.5f, 0.95f, 0.1f)), ("_snappoint (4)", new Vector3(0f, -0.05f, 0.1f)), ("_snappoint (5)", new Vector3(0.5f, 0.45f, 0.1f)), ("_snappoint (6)", new Vector3(0f, 0.95f, 0.1f)), ("_snappoint (7)", new Vector3(-0.5f, 0.45f, 0.1f)) }); case "blackmarble_tile_wall_2x2": return MoveSnapPoints(prefab, new(string, Vector3)[8] { ("_snappoint", new Vector3(1f, -0.05f, 0.1f)), ("_snappoint (1)", new Vector3(1f, 1.95f, 0.1f)), ("_snappoint (2)", new Vector3(-1f, -0.05f, 0.1f)), ("_snappoint (3)", new Vector3(-1f, -0.05f, 0.1f)), ("_snappoint (4)", new Vector3(0.5f, -0.05f, 0.1f)), ("_snappoint (5)", new Vector3(0.5f, 0.95f, 0.1f)), ("_snappoint (6)", new Vector3(-0.5f, -0.05f, 0.1f)), ("_snappoint (7)", new Vector3(-0.5f, 0.95f, 0.1f)) }); case "blackmarble_tile_wall_2x4": return MoveSnapPoints(prefab, new(string, Vector3)[8] { ("_snappoint", new Vector3(1f, -0.05f, 0.1f)), ("_snappoint (1)", new Vector3(1f, 3.95f, 0.1f)), ("_snappoint (2)", new Vector3(-1f, -0.05f, 0.1f)), ("_snappoint (3)", new Vector3(-1f, 3.95f, 0.1f)), ("_snappoint (4)", new Vector3(0.5f, -0.05f, 0.1f)), ("_snappoint (5)", new Vector3(0.5f, 1.95f, 0.1f)), ("_snappoint (6)", new Vector3(-0.5f, -0.05f, 0.1f)), ("_snappoint (7)", new Vector3(-0.5f, 1.95f, 0.1f)) }); case "dungeon_queen_door": return AddSnapPoints(prefab, new Vector3(2.5f, 0f, 0f), new Vector3(-2.5f, 0f, 0f)); case "dungeon_sunkencrypt_irongate": return AddSnapPoints(prefab, new Vector3(1f, -0.4f, 0f), new Vector3(-1f, -0.4f, 0f)); case "sunken_crypt_gate": return AddSnapPoints(prefab, new Vector3(1f, 0f, 0f), new Vector3(-1f, 0f, 0f)); case "dvergrtown_wood_beam": case "dvergrprops_wood_beam": return AddSnapPoints(prefab, new Vector3(3f, 0f, 0f), new Vector3(-3f, 0f, 0f)); case "dvergrprops_wood_pole": return AddSnapPoints(prefab, new Vector3(0f, 2f, 0f), new Vector3(0f, -2f, 0f)); case "dvergrprops_wood_wall": return AddSnapPoints(prefab, new Vector3(2.2f, 2f, 0f), new Vector3(-2.2f, 2f, 0f), new Vector3(2.2f, -2f, 0f), new Vector3(-2.2f, -2f, 0f)); case "dvergrtown_arch": return AddSnapPoints(prefab, new Vector3(1f, 0.5f, 0f)); case "dvergrtown_slidingdoor": case "dvergrtown_secretdoor": return AddSnapPoints(prefab, new Vector3(2f, 0f, 0f), new Vector3(-2f, 0f, 0f), new Vector3(2f, 4f, 0f), new Vector3(-2f, 4f, 0f)); case "dvergrtown_stair_corner_wood_left": return AddSnapPoints(prefab, new Vector3(0.25f, 0f, -0.25f), new Vector3(0.25f, 0f, 0.25f), new Vector3(0.25f, 1.1f, -0.25f), new Vector3(0.25f, 1.1f, 0.25f), new Vector3(0.25f, 0f, 2f), new Vector3(-0.25f, 1.1f, -0.25f), new Vector3(-2f, 1.1f, -0.25f)); case "dvergrprops_shelf": case "dvergrprops_table": return SetWearNTearSupports(prefab); case "dvergrtown_wood_pole": return AddSnapPoints(prefab, new Vector3(0f, -2f, 0f), new Vector3(0f, 2f, 0f)); case "dvergrtown_wood_stake": return AddSnapPoints(prefab, Vector3.zero); case "dvergrtown_wood_crane": return AddSnapPoints(prefab, new Vector3(0f, -3f, 0f)); case "dvergrtown_wood_support": return AddSnapPoints(prefab, new Vector3(-2f, 0f, 0f), new Vector3(2f, 0f, 0f)); case "dvergrtown_wood_wall01": { Transform val = prefab.transform.Find("wallcollider"); if (Object.op_Implicit((Object)(object)val)) { val.localPosition = Vector3.zero; } return AddSnapPoints(prefab, new Vector3(-3f, -2.7f, 0f), new Vector3(3f, -2.7f, 0f), new Vector3(-3f, 2.7f, 0f), new Vector3(3f, 2.7f, 0f)); } case "dvergrtown_wood_wall02": return AddSnapPoints(prefab, new Vector3(-3f, -0.5f, 0f), new Vector3(3f, -0.5f, 0f), new Vector3(-3f, 4.5f, 0f), new Vector3(3f, 4.5f, 0f)); case "dvergrtown_wood_wall03": return AddSnapPoints(prefab, new Vector3(1.1f, 0f, 0f), new Vector3(-1.1f, 0f, 0f), new Vector3(2f, 2f, 0f), new Vector3(-2f, 2f, 0f), new Vector3(1.1f, 4f, 0f), new Vector3(-1.1f, 4f, 0f)); case "goblin_roof_45d": return AddSnapPoints(prefab, new Vector3(1f, 0f, 1f), new Vector3(-1f, 0f, 1f), new Vector3(1f, 2f, -1f), new Vector3(-1f, 2f, -1f)); case "goblin_roof_45d_corner": return AddSnapPoints(prefab, new Vector3(-1f, 0f, -1f), new Vector3(1f, 0f, 1f)); case "goblin_woodwall_1m": return AddSnapPoints(prefab, new Vector3(-0.5f, 0f, 0f), new Vector3(0.5f, 0f, 0f), new Vector3(-0.5f, 2f, 0f), new Vector3(0.5f, 2f, 0f)); case "goblin_woodwall_2m": return AddSnapPoints(prefab, new Vector3(-1f, 0f, 0f), new Vector3(1f, 0f, 0f), new Vector3(-1f, 2f, 0f), new Vector3(1f, 2f, 0f)); case "Ice_floor": return AddSnapPoints(prefab, new Vector3(2f, 1f, 2f), new Vector3(-2f, 1f, -2f), new Vector3(2f, 1f, -2f), new Vector3(-2f, 1f, 2f), new Vector3(2f, -1f, 2f), new Vector3(-2f, -1f, -2f), new Vector3(2f, -1f, -2f), new Vector3(-2f, -1f, 2f)); case "turf_roof_top": return AddSnapPoints(prefab, new Vector3(1f, 0.5f, 0f), new Vector3(-1f, 0.5f, 0f)); case "metalbar_1x2": return AddSnapPoints(prefab, Vector3.zero, new Vector3(1f, -1f, 0f), new Vector3(1f, 0f, 0f), new Vector3(-1f, -1f, 0f), new Vector3(-1f, 0f, 0f)); case "stone_floor": { for (float num2 = -0.5f; num2 <= 0.5f; num2 += 1f) { for (int k = -2; k <= 2; k++) { for (int l = -2; l <= 2; l++) { if (Math.Abs(k) != 2 || Math.Abs(l) != 2) { list.Add(new Vector3((float)k, num2, (float)l)); } } } } return AddSnapPoints(prefab, (IEnumerable)list); } case "stoneblock_fracture": { for (float num = -0.5f; num <= 0.5f; num += 1f) { for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { list.Add(new Vector3((float)i, num, (float)j)); } } } FixPieceLayers(prefab); AddSnapPoints(prefab, (IEnumerable)list); AddBoxCollider(prefab, Vector3.zero, new Vector3(2f, 1f, 2f)); return true; } case "blackmarble_post01": FixPieceLayers(prefab); AddSnapPoints(prefab, Vector3.zero, new Vector3(1f, 0f, 1f), new Vector3(1f, 0f, -1f), new Vector3(-1f, 0f, -1f), new Vector3(-1f, 0f, 1f), new Vector3(1f, 1f, 1f), new Vector3(1f, 1f, -1f), new Vector3(-1f, 1f, -1f), new Vector3(-1f, 1f, 1f), new Vector3(0f, 3.5f, 0f)); AdjustNamedBoxCollider(prefab, "collider", new Vector3(0f, 0.5f, 0f), new Vector3(0f, -1f, 0f)); return true; case "wood_ledge": return AddSnapPoints(prefab, new Vector3(0.5f, 0f, 0.25f), new Vector3(0f, 0f, 0.25f), new Vector3(-0.5f, 0f, 0.25f), new Vector3(-0.5f, 0f, -0.25f), new Vector3(0.5f, 0f, -0.25f)); case "dverger_demister": RemoveColliders(prefab); AddBoxCollider(prefab, new Vector3(0f, -0.2f, 0f), new Vector3(0.2f, 1.1f, 0.2f)); AddBoxCollider(prefab, Vector3.zero, new Vector3(1f, 0.1f, 1f)); return AddSnapPoints(prefab, Vector3.zero, new Vector3(0f, -0.65f, 0f)); case "dverger_demister_large": RemoveColliders(prefab); AddBoxCollider(prefab, new Vector3(0f, -0.25f, 0f), new Vector3(0.2f, 1.3f, 0.2f)); AddBoxCollider(prefab, new Vector3(0f, -0.25f, 0f), new Vector3(1f, 0.1f, 1f)); return AddSnapPoints(prefab, Vector3.zero, new Vector3(0f, -0.9f, 0f)); case "dvergrprops_hooknchain": return AddSnapPoint(prefab, new Vector3(0f, 2.5f, 0f), "$hud_snappoint_top") | AddSnapPoint(prefab, new Vector3(0f, -2f, 0f), "Hook"); case "barrell": return AddSnapPoints(prefab, new Vector3(0f, -1f, 0f)); case "goblin_strawpile": AddBoxCollider(prefab, Vector3.zero, new Vector3(1.5f, 0.02f, 1.5f)); return true; case "mountainkit_chair": return AddChair(prefab, Vector3.zero); case "dvergrprops_chair": return AddChair(prefab, new Vector3(0f, -0.15f, 0f)); case "dvergrprops_stool": return AddChair(prefab, new Vector3(0f, -0.1f, 0f)); case "Ashland_Stair": return AddSnapPoints(prefab, new Vector3(2f, 0f, -2f), new Vector3(-2f, 0f, -2f), new Vector3(-2f, 0f, 2f), new Vector3(2f, 0f, 2f), new Vector3(2f, 2f, -2f), new Vector3(-2f, 2f, -2f)); case "Ashlands_Fortress_Floor": return AddSnapPoints(prefab, new Vector3(1f, -0.5f, -1f), new Vector3(-1f, -0.5f, -1f), new Vector3(-1f, -0.5f, 1f), new Vector3(1f, -0.5f, 1f), new Vector3(1f, 0.5f, -1f), new Vector3(-1f, 0.5f, -1f), new Vector3(-1f, 0.5f, 1f), new Vector3(1f, 0.5f, 1f), Vector3.zero); case "Ashlands_Wall_2x2": case "Ashlands_Wall_2x2_edge2": case "Ashlands_Wall_2x2_top": case "Ashlands_Wall_2x2_edge2_top": return AddSnapPoints(prefab, new Vector3(-1f, 0f, -0.5f), new Vector3(1f, 0f, -0.5f), new Vector3(-1f, 2f, -0.5f), new Vector3(1f, 2f, -0.5f), new Vector3(-1f, 0f, 0.5f), new Vector3(1f, 0f, 0.5f), new Vector3(-1f, 2f, 0.5f), new Vector3(1f, 2f, 0.5f)); case "Ashlands_Wall_2x2_edge_top": case "Ashlands_Wall_2x2_edge": return AddSnapPoints(prefab, new Vector3(1f, 0f, 0.5f), new Vector3(-1f, 0f, 0.5f), new Vector3(1f, 2f, 0.5f), new Vector3(-1f, 2f, 0.5f), new Vector3(1f, 0f, -0.5f), new Vector3(-1f, 0f, -0.5f), new Vector3(1f, 2f, -0.5f), new Vector3(-1f, 2f, -0.5f)); case "Ashlands_Wall_2x2_cornerR": case "Ashlands_Wall_2x2_cornerR_top": return AddCornerSnapPoints(prefab, right: true); case "Ashlands_Wall_2x2_cornerL": case "Ashlands_Wall_2x2_cornerL_top": return AddCornerSnapPoints(prefab, right: false); case "Ashlands_Fortress_Wall_Spikes": return AddSnapPoints(prefab, new Vector3(0f, 0f, -2f), Vector3.zero, new Vector3(0f, 0f, 2f)); default: return false; } } private static bool ApplyTrailershipFixup(GameObject prefab, bool applyStaticFixups) { //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) GameObject val = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab("VikingShip") : null); bool flag = !applyStaticFixups; if (applyStaticFixups) { Transform obj = FindDeepChild(prefab.transform, "hull"); MeshFilter val2 = ((obj != null) ? ((Component)obj).GetComponent() : null); object obj2; if (!Object.op_Implicit((Object)(object)val)) { obj2 = null; } else { Transform obj3 = FindDeepChild(val.transform, "hull"); obj2 = ((obj3 != null) ? ((Component)obj3).GetComponent() : null); } MeshFilter val3 = (MeshFilter)obj2; bool flag2 = Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val3.sharedMesh); if (flag2) { val2.sharedMesh = val3.sharedMesh; } GameObject val4 = (Object.op_Implicit((Object)(object)ZNetScene.instance) ? ZNetScene.instance.GetPrefab("ShieldBanded") : null); MeshRenderer val5 = (Object.op_Implicit((Object)(object)val4) ? val4.GetComponentInChildren(true) : null); Material val6 = (Object.op_Implicit((Object)(object)val5) ? ((Renderer)val5).sharedMaterial : null); Transform val7 = prefab.transform.Find("ship/visual/Customize/storage"); bool flag3 = Object.op_Implicit((Object)(object)val6) && Object.op_Implicit((Object)(object)val7); if (flag3) { for (int i = 0; i < val7.childCount; i++) { Transform child = val7.GetChild(i); MeshRenderer val8 = ((Object.op_Implicit((Object)(object)child) && ((Object)child).name.StartsWith("Shield", StringComparison.Ordinal)) ? ((Component)child).GetComponent() : null); if (Object.op_Implicit((Object)(object)val8)) { ((Renderer)val8).sharedMaterial = val6; } } } Transform obj4 = FindDeepChild(prefab.transform, "sail_full"); Cloth val9 = ((obj4 != null) ? ((Component)obj4).GetComponent() : null); object obj5; if (!Object.op_Implicit((Object)(object)val)) { obj5 = null; } else { Transform obj6 = FindDeepChild(val.transform, "sail_full"); obj5 = ((obj6 != null) ? ((Component)obj6).GetComponent() : null); } Cloth val10 = (Cloth)obj5; bool flag4 = Object.op_Implicit((Object)(object)val9) && Object.op_Implicit((Object)(object)val10); if (flag4) { val9.coefficients = val10.coefficients; } flag = flag2 && flag3 && flag4; } Ship component = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { Ship vikingShip = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); if (applyStaticFixups) { Transform val11 = prefab.transform.Find("ControlGui"); if (!Object.op_Implicit((Object)(object)val11)) { GameObject val12 = new GameObject("ControlGui"); val12.transform.SetParent(prefab.transform, false); val11 = val12.transform; } val11.localPosition = new Vector3(1f, 1.696f, -6.54f); component.m_controlGuiPos = val11; EnsureTrailershipAshlandsDamageEffects(prefab, component, val); } ApplyTrailershipMovementProfile(component, vikingShip); } else if (applyStaticFixups) { flag = false; } if (applyStaticFixups) { Transform obj7 = FindDeepChild(prefab.transform, "rudder_button"); ShipControlls val13 = ((obj7 != null) ? ((Component)obj7).GetComponent() : null); Transform val14 = prefab.transform.Find("sit locations/sit_box (4)/attachpoint"); bool flag5 = Object.op_Implicit((Object)(object)val13) && Object.op_Implicit((Object)(object)val14); if (flag5) { val13.m_attachPoint = val14; } flag = flag && flag5; } return flag; } private static void ApplyTrailershipMovementProfile(Ship ship, Ship vikingShip) { float trailershipSpeedRatio = HarnessPrefabsPlugin.TrailershipSpeedRatio; if (!Object.op_Implicit((Object)(object)vikingShip)) { ship.m_damping = 0.05f; ship.m_dampingSideway = 0.15f; ship.m_dampingForward = 0.001f / trailershipSpeedRatio; ship.m_angularDamping = 0.3f; ship.m_sailForceOffset = 2f; ship.m_sailForceFactor = 0.05f * trailershipSpeedRatio; ship.m_rudderSpeed = 1f; ship.m_stearForceOffset = -8f; ship.m_stearForce = 1f * trailershipSpeedRatio; ship.m_stearVelForceFactor = 0.8f; ship.m_backwardForce = 0.2f * trailershipSpeedRatio; ship.m_rudderRotationMax = 45f; } else { ship.m_damping = vikingShip.m_damping; ship.m_dampingSideway = vikingShip.m_dampingSideway; ship.m_dampingForward = vikingShip.m_dampingForward / trailershipSpeedRatio; ship.m_angularDamping = vikingShip.m_angularDamping; ship.m_sailForceOffset = vikingShip.m_sailForceOffset; ship.m_sailForceFactor = vikingShip.m_sailForceFactor * trailershipSpeedRatio; ship.m_rudderSpeed = vikingShip.m_rudderSpeed; ship.m_stearForceOffset = vikingShip.m_stearForceOffset; ship.m_stearForce = vikingShip.m_stearForce * trailershipSpeedRatio; ship.m_stearVelForceFactor = vikingShip.m_stearVelForceFactor; ship.m_backwardForce = vikingShip.m_backwardForce * trailershipSpeedRatio; ship.m_rudderRotationMax = vikingShip.m_rudderRotationMax; } } private static void EnsureTrailershipAshlandsDamageEffects(GameObject prefab, Ship ship, GameObject vikingShip) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)ship.m_ashdamageEffects)) { Transform val = (Object.op_Implicit((Object)(object)vikingShip) ? FindDeepChild(vikingShip.transform, "ashdamageeffects") : null); GameObject val2 = (GameObject)(Object.op_Implicit((Object)(object)val) ? ((object)Object.Instantiate(((Component)val).gameObject)) : ((object)new GameObject("ashdamageeffects"))); ((Object)val2).name = "ashdamageeffects"; val2.transform.SetParent(prefab.transform, false); if (Object.op_Implicit((Object)(object)val)) { val2.transform.localPosition = val.localPosition; val2.transform.localRotation = val.localRotation; val2.transform.localScale = val.localScale; } else { val2.transform.localPosition = new Vector3(0f, -0.8f, 0f); } ship.m_ashdamageEffects = val2; } if (Object.op_Implicit((Object)(object)ship.m_ashdamageEffects)) { ship.m_ashdamageEffects.SetActive(false); ship.m_ashlandsFxAudio = ship.m_ashdamageEffects.GetComponentsInChildren(true).ToList(); } } private static Transform FindDeepChild(Transform root, string childName) { if (!Object.op_Implicit((Object)(object)root) || string.IsNullOrWhiteSpace(childName)) { return null; } Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren(true); foreach (Transform val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val) && ((Object)val).name == childName) { return val; } } return null; } private static bool AddCornerSnapPoints(GameObject prefab, bool right) { //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) if (right) { return AddSnapPoints(prefab, new Vector3(-0.25f, 0f, -1f), new Vector3(-0.25f, 0f, 0f), new Vector3(0.75f, 0f, 0f), new Vector3(-0.25f, 2f, -1f), new Vector3(-0.25f, 2f, 0f), new Vector3(0.75f, 2f, 0f), new Vector3(-1.25f, 0f, -1f), new Vector3(-1.25f, 0f, 1f), new Vector3(0.75f, 0f, 1f), new Vector3(-1.25f, 2f, -1f), new Vector3(-1.25f, 2f, 1f), new Vector3(0.75f, 2f, 1f)); } return AddSnapPoints(prefab, new Vector3(0f, 0f, -1.25f), new Vector3(0f, 0f, -0.5f), new Vector3(1.25f, 0f, -0.5f), new Vector3(0f, 2f, -1.25f), new Vector3(0f, 2f, -0.5f), new Vector3(1.25f, 2f, -0.5f), new Vector3(-1f, 0f, -1.25f), new Vector3(-1f, 0f, 0.5f), new Vector3(1.25f, 0f, 0.5f), new Vector3(-1f, 2f, -1.25f), new Vector3(-1f, 2f, 0.5f), new Vector3(1.25f, 2f, 0.5f)); } private static IEnumerable BoxCornerPoints(float x, float y, float z) { yield return new Vector3(0f - x, y, 0f - z); yield return new Vector3(x, y, z); yield return new Vector3(0f - x, y, z); yield return new Vector3(x, y, 0f - z); } private static bool AddSnapPoints(GameObject prefab, IEnumerable points) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) bool flag = false; foreach (Vector3 point in points) { flag |= AddSnapPoint(prefab, point, "Snappoint"); } return flag; } private static bool AddSnapPoints(GameObject prefab, params Vector3[] points) { return AddSnapPoints(prefab, (IEnumerable)points); } private static bool AddSnapPoint(GameObject prefab, Vector3 point, string name) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (HasSnapPointAt(prefab, point)) { return true; } GameObject val = new GameObject(name); val.transform.SetParent(prefab.transform, false); val.transform.localPosition = point; val.tag = "snappoint"; val.SetActive(false); return true; } private static bool HasSnapPointAt(GameObject prefab, Vector3 point) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_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) Transform[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Transform val in componentsInChildren) { if (string.Equals(((Component)val).gameObject.tag, "snappoint", StringComparison.Ordinal)) { Vector3 val2 = val.localPosition - point; if (((Vector3)(ref val2)).sqrMagnitude <= 1.0000001E-06f) { return true; } } } return false; } private static bool MoveSnapPoints(GameObject prefab, params (string name, Vector3 localPosition)[] moves) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) bool result = true; for (int i = 0; i < moves.Length; i++) { (string name, Vector3 localPosition) tuple = moves[i]; string item = tuple.name; Vector3 item2 = tuple.localPosition; Transform val = prefab.transform.Find(item); if (!Object.op_Implicit((Object)(object)val)) { result = false; continue; } val.localPosition = item2; ((Component)val).tag = "snappoint"; } return result; } private static bool AddSnapPointsToMeshCorners(GameObject prefab, string meshName) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) MeshFilter val = ((IEnumerable)prefab.GetComponentsInChildren(true)).FirstOrDefault((Func)((MeshFilter filter) => Object.op_Implicit((Object)(object)filter) && Object.op_Implicit((Object)(object)filter.sharedMesh) && ((Object)filter).name == meshName)); if (!Object.op_Implicit((Object)(object)val)) { return false; } Bounds bounds = val.sharedMesh.bounds; List list = new List(); foreach (Vector3 boundsCorner in GetBoundsCorners(bounds)) { Vector3 val2 = ((Component)val).transform.TransformPoint(boundsCorner); list.Add(prefab.transform.InverseTransformPoint(val2)); } return AddSnapPoints(prefab, (IEnumerable)list); } private static IEnumerable GetBoundsCorners(Bounds bounds) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) Vector3 center = ((Bounds)(ref bounds)).center; Vector3 extents = ((Bounds)(ref bounds)).extents; for (int x = -1; x <= 1; x += 2) { for (int y = -1; y <= 1; y += 2) { for (int z = -1; z <= 1; z += 2) { yield return center + Vector3.Scale(extents, new Vector3((float)x, (float)y, (float)z)); } } } } private static void FixPieceLayers(GameObject gameObject) { int layer = LayerMask.NameToLayer("piece"); Collider[] componentsInChildren = gameObject.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = layer; } } private static void RemoveColliders(GameObject prefab) { Collider[] componentsInChildren = prefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } } private static void AddBoxCollider(GameObject prefab, Vector3 center, Vector3 size) { //IL_0007: 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) BoxCollider obj = prefab.AddComponent(); obj.center = center; obj.size = size; } private static void RemoveComponent(GameObject prefab) where T : Component { T component = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { Object.DestroyImmediate((Object)(object)component); } } private static void RemoveRandomPieceRotation(GameObject prefab, string childName) { Transform val = prefab.transform.Find(childName); RandomPieceRotation val2 = (Object.op_Implicit((Object)(object)val) ? ((Component)val).GetComponent() : null); if (Object.op_Implicit((Object)(object)val2)) { Object.DestroyImmediate((Object)(object)val2); } } private static bool SetWearNTearSupports(GameObject prefab) { WearNTear component = prefab.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { return false; } component.m_supports = true; return true; } private static bool AddChair(GameObject prefab, Vector3 attachPointPosition) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) Chair obj = prefab.GetComponent() ?? prefab.AddComponent(); Transform val = prefab.transform.Find("attachPoint"); if (!Object.op_Implicit((Object)(object)val)) { GameObject val2 = new GameObject("attachPoint"); val2.transform.SetParent(prefab.transform, false); val = val2.transform; } val.localPosition = attachPointPosition; obj.m_attachPoint = val; return true; } private static void AdjustNamedBoxCollider(GameObject prefab, string colliderName, Vector3 centerDelta, Vector3 sizeDelta) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) BoxCollider[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (BoxCollider val in componentsInChildren) { if (!(((Object)val).name != colliderName)) { val.center += centerDelta; val.size += sizeDelta; } } } } internal sealed class HarnessPrefabsMvbpFixupMarker : MonoBehaviour { } internal static class PrefabOwnerCatalog { private enum CatalogState { Uninitialized, Loaded, Unavailable } private sealed class PluginResourceSnapshot { public string OwnerName { get; set; } = ""; public string PluginName { get; set; } = ""; public string PluginGuid { get; set; } = ""; public string AssemblyName { get; set; } = ""; public string[] ResourceNames { get; set; } = Array.Empty(); } public const string VanillaOwnerName = "Valheim"; public const string UnknownOwnerName = "Unknown / Untracked"; private static readonly object VanillaSync = new object(); private static readonly object ModSync = new object(); private static readonly HashSet VanillaPrefabNames = new HashSet(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary ModPrefabOwners = new Dictionary(StringComparer.OrdinalIgnoreCase); private static CatalogState _vanillaState; private static string _loadedModSignature = ""; public static IReadOnlyDictionary GetOwnerNames(IEnumerable prefabNames) { EnsureVanillaCatalogLoaded(); EnsureModMappingsLoaded(); Dictionary dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string item in prefabNames.Where((string name) => !string.IsNullOrWhiteSpace(name)).Distinct(StringComparer.OrdinalIgnoreCase)) { if (_vanillaState == CatalogState.Loaded && VanillaPrefabNames.Contains(item)) { dictionary[item] = "Valheim"; } else { dictionary[item] = ResolveLoadedModOwner(item); } } return dictionary; } private static string ResolveLoadedModOwner(string prefabName) { foreach (string item in EnumerateLookupCandidates(prefabName)) { if (ModPrefabOwners.TryGetValue(item, out string value) && !string.IsNullOrWhiteSpace(value)) { return value; } } return "Unknown / Untracked"; } private static void EnsureVanillaCatalogLoaded() { if (_vanillaState != CatalogState.Uninitialized) { return; } lock (VanillaSync) { if (_vanillaState != CatalogState.Uninitialized) { return; } string text = Path.Combine(Application.dataPath, "StreamingAssets", "SoftRef", "manifest_extended"); if (!File.Exists(text)) { _vanillaState = CatalogState.Unavailable; HarnessPrefabsPlugin.Log.LogWarning((object)("Vanilla asset manifest was not found at '" + text + "'. Reference sections may place vanilla entries under 'Unknown / Untracked'.")); return; } foreach (string item in File.ReadLines(text)) { int num = item.IndexOf("path in bundle:", StringComparison.OrdinalIgnoreCase); if (num < 0) { continue; } string text2 = item.Substring(num + "path in bundle:".Length).Trim(); if (text2.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text2); if (!string.IsNullOrWhiteSpace(fileNameWithoutExtension)) { VanillaPrefabNames.Add(fileNameWithoutExtension); } } } _vanillaState = CatalogState.Loaded; } } private static void EnsureModMappingsLoaded() { List pluginResources = GetPluginResources(); string text = BuildSignature(pluginResources); if (string.Equals(text, _loadedModSignature, StringComparison.Ordinal)) { return; } lock (ModSync) { if (string.Equals(text, _loadedModSignature, StringComparison.Ordinal)) { return; } ModPrefabOwners.Clear(); foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { string text2 = ((Object)allLoadedAssetBundle).name ?? ""; if (text2.Length == 0) { continue; } string value = ResolveOwnerName(text2, pluginResources); if (string.IsNullOrWhiteSpace(value)) { continue; } string[] allAssetNames = allLoadedAssetBundle.GetAllAssetNames(); foreach (string text3 in allAssetNames) { if (text3.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase)) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text3); if (!string.IsNullOrWhiteSpace(fileNameWithoutExtension)) { ModPrefabOwners[fileNameWithoutExtension] = value; } } } } _loadedModSignature = text; } } private static IEnumerable EnumerateLookupCandidates(string prefabName) { string normalizedName = (prefabName ?? "").Replace("(Clone)", "").Trim(); if (normalizedName.Length != 0) { yield return normalizedName; int num = normalizedName.IndexOf(':'); if (num > 0) { yield return normalizedName.Substring(0, num); } } } private static List GetPluginResources() { return (from plugin in Chainloader.PluginInfos.Values.Select(delegate(PluginInfo pluginInfo) { string text = (pluginInfo.Metadata.Name ?? "").Trim(); string text2 = (pluginInfo.Metadata.GUID ?? "").Trim(); string assemblyName = ""; string[] resourceNames = Array.Empty(); try { assemblyName = ((object)pluginInfo.Instance)?.GetType().Assembly.GetName().Name ?? ""; resourceNames = ((object)pluginInfo.Instance)?.GetType().Assembly.GetManifestResourceNames() ?? Array.Empty(); } catch { } return new PluginResourceSnapshot { OwnerName = ((text.Length > 0) ? text : text2), PluginName = text, PluginGuid = text2, AssemblyName = assemblyName, ResourceNames = resourceNames }; }) where plugin.OwnerName.Length > 0 select plugin).ToList(); } private static string ResolveOwnerName(string bundleName, List plugins) { PluginResourceSnapshot pluginResourceSnapshot = plugins.FirstOrDefault((PluginResourceSnapshot plugin) => plugin.ResourceNames.Any((string resourceName) => resourceName.EndsWith(bundleName, StringComparison.OrdinalIgnoreCase))); if (pluginResourceSnapshot != null) { return pluginResourceSnapshot.OwnerName; } string normalizedBundleName = NormalizeToken(Path.GetFileNameWithoutExtension(bundleName)); if (normalizedBundleName.Length == 0) { return ""; } return plugins.FirstOrDefault((PluginResourceSnapshot plugin) => IsTokenMatch(normalizedBundleName, NormalizeToken(plugin.PluginName)) || IsTokenMatch(normalizedBundleName, NormalizeToken(plugin.PluginGuid)) || IsTokenMatch(normalizedBundleName, NormalizeToken(plugin.AssemblyName)))?.OwnerName ?? ""; } private static bool IsTokenMatch(string bundleName, string pluginToken) { if (pluginToken.Length > 0) { if (bundleName.IndexOf(pluginToken, StringComparison.OrdinalIgnoreCase) < 0) { return pluginToken.IndexOf(bundleName, StringComparison.OrdinalIgnoreCase) >= 0; } return true; } return false; } private static string NormalizeToken(string value) { if (string.IsNullOrWhiteSpace(value)) { return ""; } StringBuilder stringBuilder = new StringBuilder(); foreach (char c in value) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(char.ToLowerInvariant(c)); } } return stringBuilder.ToString(); } private static string BuildSignature(IEnumerable plugins) { IEnumerable values = (from bundle in AssetBundle.GetAllLoadedAssetBundles() select ((Object)bundle).name ?? "" into name where name.Length > 0 select name).OrderBy((string name) => name, StringComparer.OrdinalIgnoreCase); IEnumerable values2 = plugins.Select((PluginResourceSnapshot plugin) => plugin.PluginGuid + ":" + plugin.PluginName + ":" + plugin.AssemblyName + ":" + string.Join(",", plugin.ResourceNames.OrderBy((string name) => name, StringComparer.OrdinalIgnoreCase))).OrderBy((string token) => token, StringComparer.OrdinalIgnoreCase); return string.Join("|", values) + "||" + string.Join("|", values2); } } internal static class HarnessPrefabsSfxManager { private static readonly Dictionary PlacementSfx = new Dictionary(StringComparer.Ordinal) { ["sfx_build_hammer_metal"] = null, ["sfx_build_hammer_stone"] = null, ["sfx_build_hammer_default"] = null }; private static readonly Dictionary RemovalSfx = new Dictionary(StringComparer.Ordinal) { ["sfx_rock_destroyed"] = null, ["sfx_wood_destroyed"] = null }; private static bool _initialized; public static void Initialize() { if (!_initialized) { _initialized = true; InitializeSfx(PlacementSfx); InitializeSfx(RemovalSfx); } } public static void FixPlacementSfx(Piece piece) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)piece)) { return; } Initialize(); if (piece.m_placeEffect == null) { piece.m_placeEffect = new EffectList(); } EffectData[] array = piece.m_placeEffect.m_effectPrefabs ?? Array.Empty(); EffectData[] array2 = array; foreach (EffectData val in array2) { if (Object.op_Implicit((Object)(object)val?.m_prefab) && ((Object)val.m_prefab).name.StartsWith("sfx_", StringComparison.Ordinal)) { val.m_enabled = true; return; } } string key = ResolvePlacementSfxName(piece.m_craftingStation); if (PlacementSfx.TryGetValue(key, out var value) && value != null) { List list = array.ToList(); list.Add(CloneEffectData(value)); piece.m_placeEffect.m_effectPrefabs = list.ToArray(); } } public static bool HasSfx(EffectList effectList) { EffectData[] array = effectList?.m_effectPrefabs; if (array == null || array.Length == 0) { return false; } return array.Any((EffectData effect) => Object.op_Implicit((Object)(object)effect?.m_prefab) && ((Object)effect.m_prefab).name.StartsWith("sfx_", StringComparison.Ordinal)); } public static EffectList FixRemovalSfx(WearNTear wearNTear) { Piece val = (Object.op_Implicit((Object)(object)wearNTear) ? ((Component)wearNTear).GetComponent() : null); CraftingStation station = (Object.op_Implicit((Object)(object)val) ? val.m_craftingStation : null); return FixRemovalSfx(Object.op_Implicit((Object)(object)wearNTear) ? wearNTear.m_destroyedEffect : null, station); } private static EffectList FixRemovalSfx(EffectList effectList, CraftingStation station) { //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown Initialize(); List list = (effectList?.m_effectPrefabs ?? Array.Empty()).Where((EffectData effect) => effect != null).Select(CloneEffectData).ToList(); string key = ((Object.op_Implicit((Object)(object)station) && ((Object)station).name == CraftingStations.Stonecutter) ? "sfx_rock_destroyed" : "sfx_wood_destroyed"); if (RemovalSfx.TryGetValue(key, out var value) && value != null) { list.Add(CloneEffectData(value)); } return new EffectList { m_effectPrefabs = list.ToArray() }; } private static string ResolvePlacementSfxName(CraftingStation station) { if (!Object.op_Implicit((Object)(object)station) || string.IsNullOrEmpty(station.m_name) || ((Object)station).name == CraftingStations.Workbench || ((Object)station).name == CraftingStations.BlackForge) { return "sfx_build_hammer_default"; } if (((Object)station).name == CraftingStations.Stonecutter) { return "sfx_build_hammer_stone"; } if (!(((Object)station).name == CraftingStations.Forge)) { return "sfx_build_hammer_default"; } return "sfx_build_hammer_metal"; } private static void InitializeSfx(Dictionary sfxDict) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown foreach (string item in sfxDict.Keys.ToList()) { GameObject prefab = PrefabManager.Instance.GetPrefab(item); if (!Object.op_Implicit((Object)(object)prefab) && Object.op_Implicit((Object)(object)ZNetScene.instance)) { prefab = ZNetScene.instance.GetPrefab(item); } if (!Object.op_Implicit((Object)(object)prefab)) { if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogWarning((object)("SFX prefab '" + item + "' could not be found.")); } } else { sfxDict[item] = new EffectData { m_prefab = prefab, m_enabled = true, m_variant = -1 }; } } } private static EffectData CloneEffectData(EffectData source) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown if (source == null) { return null; } return new EffectData { m_prefab = source.m_prefab, m_enabled = source.m_enabled, m_variant = source.m_variant, m_attach = source.m_attach, m_follow = source.m_follow, m_inheritParentRotation = source.m_inheritParentRotation, m_inheritParentScale = source.m_inheritParentScale, m_multiplyParentVisualScale = source.m_multiplyParentVisualScale, m_randomRotation = source.m_randomRotation, m_scale = source.m_scale, m_childTransform = source.m_childTransform }; } } internal static class PrefabPlacementPatchRegistry { private const float MinBoundsSize = 0.001f; private static readonly HashSet PrefabNames = new HashSet(StringComparer.Ordinal); private static readonly Dictionary PlacementOffsets = new Dictionary(StringComparer.Ordinal); public static void Clear() { PrefabNames.Clear(); PlacementOffsets.Clear(); } public static void Set(string prefabName, bool enabled, Vector3? placementOffset) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(prefabName)) { return; } prefabName = HarnessPrefabsRuntime.NormalizePrefabName(prefabName); if (enabled) { PrefabNames.Add(prefabName); } else { PrefabNames.Remove(prefabName); } if (placementOffset.HasValue) { Vector3 value = placementOffset.Value; if (((Vector3)(ref value)).sqrMagnitude > 1.0000001E-06f) { PlacementOffsets[prefabName] = placementOffset.Value; return; } } PlacementOffsets.Remove(prefabName); } public static void PatchGhost(GameObject ghost) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)ghost)) { return; } string text = HarnessPrefabsRuntime.NormalizePrefabName(((Object)ghost).name); if (PrefabNames.Contains(text) && !Object.op_Implicit((Object)(object)ghost.GetComponent()) && TryGetRendererBounds(ghost, out var bounds)) { BoxCollider obj = ghost.AddComponent(); obj.center = ghost.transform.InverseTransformPoint(((Bounds)(ref bounds)).center); obj.size = WorldSizeToLocalSize(ghost.transform, ((Bounds)(ref bounds)).size); ((Collider)obj).isTrigger = false; ghost.AddComponent(); if (HarnessPrefabsPlugin.Verbose) { HarnessPrefabsPlugin.Log.LogInfo((object)("Applied placement collider patch to ghost '" + text + "'.")); } } } public static void ApplyGhostOffset(GameObject ghost) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)ghost)) { string key = HarnessPrefabsRuntime.NormalizePrefabName(((Object)ghost).name); if (PlacementOffsets.TryGetValue(key, out var value)) { Transform transform = ghost.transform; transform.position += ghost.transform.rotation * value; } } } private static bool TryGetRendererBounds(GameObject prefab, out Bounds bounds) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) bounds = default(Bounds); bool flag = false; Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); foreach (Renderer val in componentsInChildren) { if (Object.op_Implicit((Object)(object)val)) { if (!flag) { bounds = val.bounds; flag = true; } else { ((Bounds)(ref bounds)).Encapsulate(val.bounds); } } } if (flag) { Vector3 size = ((Bounds)(ref bounds)).size; return ((Vector3)(ref size)).sqrMagnitude > 1.0000001E-06f; } return false; } private static Vector3 WorldSizeToLocalSize(Transform transform, Vector3 worldSize) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) Vector3 lossyScale = transform.lossyScale; return new Vector3(DivideByScale(worldSize.x, lossyScale.x), DivideByScale(worldSize.y, lossyScale.y), DivideByScale(worldSize.z, lossyScale.z)); } private static float DivideByScale(float value, float scale) { float num = Mathf.Abs(scale); if (!(num < 0.001f)) { return value / num; } return value; } } internal sealed class HarnessPrefabsPlacementPatchMarker : MonoBehaviour { } internal static class PrefabRequirementParser { public static List ParseMany(string requirements) { if (string.IsNullOrWhiteSpace(requirements) || requirements.Equals("None", StringComparison.OrdinalIgnoreCase)) { return new List(); } return requirements.Split(new char[1] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(ParseOne).ToList(); } public static List Clone(IEnumerable? requirements) { List list = new List(); if (requirements == null) { return list; } foreach (PrefabRequirement requirement in requirements) { string text = requirement?.Item?.Trim() ?? ""; if (text.Length == 0) { throw new FormatException("Prefab requirement item names cannot be empty."); } if (requirement.Amount < 1) { throw new FormatException("Prefab requirement '" + text + "' must have a positive integer amount."); } list.Add(new PrefabRequirement { Item = text, Amount = requirement.Amount }); } return list; } private static PrefabRequirement ParseOne(string entry) { int num = entry.IndexOfAny(new char[3] { ',', ':', '=' }); if (num < 0) { string text = entry.Trim(); if (text.Length == 0) { throw new FormatException("Prefab requirement item names cannot be empty."); } return new PrefabRequirement { Item = text, Amount = 1 }; } string text2 = entry.Substring(0, num).Trim(); if (text2.Length == 0) { throw new FormatException("Prefab requirement item names cannot be empty."); } if (!int.TryParse(entry.Substring(num + 1).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 1) { throw new FormatException("Prefab requirement '" + text2 + "' must have a positive integer amount."); } return new PrefabRequirement { Item = text2, Amount = result }; } } public sealed class PrefabRuleEntry { public string Prefab { get; set; } = ""; public bool? Enabled { get; set; } public string? Category { get; set; } public string? DisplayName { get; set; } public string? Description { get; set; } public string? CraftingStation { get; set; } public List? Requirements { get; set; } public string? Flags { get; set; } public ComponentList? Components { get; set; } } public sealed class PrefabRule { public PrefabAccess Access { get; set; } public string Category { get; set; } = "Harness Props"; public string DisplayName { get; set; } = ""; public string Description { get; set; } = ""; public string CraftingStation { get; set; } = "None"; public List Requirements { get; set; } = new List(); public bool ClipEverything { get; set; } public bool ClipGround { get; set; } public bool AllowedInDungeons { get; set; } public bool CanBeRemoved { get; set; } = true; public ComponentList Components { get; set; } = new ComponentList(); } public sealed class PrefabRequirement { public string Item { get; set; } = ""; public int Amount { get; set; } = 1; } public sealed class ComponentList : List { public ComponentList() { } public ComponentList(IEnumerable values) : base(values) { } } internal sealed class PrefabDiscovery { public string Name { get; set; } = ""; public PrefabAccess Access { get; set; } public string Category { get; set; } = "Harness Props"; public bool ClipEverything { get; set; } public bool ClipGround { get; set; } public bool AllowedInDungeons { get; set; } public ComponentList Components { get; set; } = new ComponentList(); public GameObject? Prefab { get; set; } } internal static class PrefabRuleStore { private sealed class PrefabRequirementYamlConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(PrefabRequirement); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var @event)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); throw new YamlException(scalar.Start, scalar.End, "Prefab requirements must use shorthand, for example '- FineWood: 2'."); } List> list = new List>(); MappingEnd event2; while (!parser.Accept(out event2)) { YamlDotNet.Core.Events.Scalar scalar2 = parser.Consume(); if (parser.Accept(out @event) || parser.Accept(out var _)) { throw new YamlException(scalar2.Start, scalar2.End, "Unsupported nested requirement shorthand for '" + scalar2.Value + "'."); } YamlDotNet.Core.Events.Scalar scalar3 = parser.Consume(); list.Add(new KeyValuePair(scalar2.Value, scalar3.Value)); } parser.Consume(); if (list.Count != 1) { throw new YamlException("Prefab requirements must use shorthand, for example '- FineWood: 2'."); } return ParseRequirement(list[0].Key, list[0].Value); } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { PrefabRequirement prefabRequirement = (PrefabRequirement)value; string text = prefabRequirement?.Item?.Trim() ?? ""; if (text.Length == 0 || prefabRequirement.Amount < 1) { throw new YamlException("Prefab requirements must have a non-empty item and a positive integer amount."); } emitter.Emit(new MappingStart()); emitter.Emit(new YamlDotNet.Core.Events.Scalar(text)); emitter.Emit(new YamlDotNet.Core.Events.Scalar(prefabRequirement.Amount.ToString(CultureInfo.InvariantCulture))); emitter.Emit(new MappingEnd()); } private static PrefabRequirement ParseRequirement(string item, string value) { string text = item.Trim(); if (text.Length == 0) { throw new YamlException("Prefab requirement item names cannot be empty."); } if (!int.TryParse(value.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 1) { throw new YamlException("Prefab requirement '" + text + "' must have a positive integer amount."); } return new PrefabRequirement { Item = text, Amount = result }; } } private sealed class ComponentListYamlConverter : IYamlTypeConverter { public bool Accepts(Type type) { return type == typeof(ComponentList); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var _)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); throw new YamlException(scalar.Start, scalar.End, "Prefab components must use a YAML sequence, for example 'components: [Piece, WearNTear]'."); } ComponentList componentList = new ComponentList(); SequenceEnd event2; while (!parser.Accept(out event2)) { YamlDotNet.Core.Events.Scalar scalar2 = parser.Consume(); if (!string.IsNullOrWhiteSpace(scalar2.Value)) { componentList.Add(scalar2.Value.Trim()); } } parser.Consume(); return componentList; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { ComponentList obj = (ComponentList)value; emitter.Emit(new SequenceStart(AnchorName.Empty, TagName.Empty, isImplicit: true, SequenceStyle.Flow)); foreach (string item in obj) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(item)); } emitter.Emit(new SequenceEnd()); } } public const string OverrideFileName = "prefabs.yml"; public const string ReferenceFileName = "prefabs.reference.yml"; public const string FullScaffoldFileName = "prefabs.full.yml"; private const string DomainName = "prefabs"; private static readonly ISerializer SparseSerializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(new PrefabRequirementYamlConverter()).WithTypeConverter(new ComponentListYamlConverter()) .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) .DisableAliases() .Build(); private static readonly ISerializer FullSerializer = new SerializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(new PrefabRequirementYamlConverter()).WithTypeConverter(new ComponentListYamlConverter()) .DisableAliases() .Build(); private static readonly IDeserializer Deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).WithTypeConverter(new PrefabRequirementYamlConverter()).WithTypeConverter(new ComponentListYamlConverter()) .IgnoreUnmatchedProperties() .Build(); private static CustomSyncedValue _syncedRules = null; private static Dictionary _activeRules = new Dictionary(StringComparer.Ordinal); private static List _lastDiscoveries = new List(); private static string? _lastSyncedRulesPayload; public static string RulesDirectory => Path.Combine(Paths.ConfigPath, "HarnessPrefabs"); public static string RulesPath => Path.Combine(RulesDirectory, "prefabs.yml"); public static string ReferencePath => Path.Combine(RulesDirectory, "prefabs.reference.yml"); public static string FullScaffoldPath => Path.Combine(RulesDirectory, "prefabs.full.yml"); public static IReadOnlyList LastDiscoveries => _lastDiscoveries; public static bool HasCachedDiscoveries => _lastDiscoveries.Count > 0; public static int ActiveRuleCount => _activeRules.Count; public static void Initialize(CustomSyncedValue syncedRules) { _syncedRules = syncedRules; } public static bool IsOverrideFileEvent(FileSystemEventArgs e) { return IsOverrideFileName(Path.GetFileName(e.FullPath)); } public static bool PublishRulesFromDisk() { if (!HarnessPrefabsPlugin.IsSourceOfTruth) { return false; } if (!TryBuildActiveRulesFromDisk(_lastDiscoveries, out Dictionary rules)) { return false; } CommitSourceRules(rules, _lastDiscoveries); return true; } public static bool LoadSyncedRulesForCurrentAuthority() { if (HarnessPrefabsPlugin.IsSourceOfTruth) { return false; } string text = _syncedRules.Value ?? string.Empty; if (!string.IsNullOrWhiteSpace(text) && string.Equals(_lastSyncedRulesPayload, text, StringComparison.Ordinal)) { return false; } if (!TryBuildSyncedRules(_lastDiscoveries, text, out Dictionary rules)) { return false; } _activeRules = rules; _lastSyncedRulesPayload = text; return true; } public static void LoadRulesForCurrentAuthority(IEnumerable discoveries) { _lastDiscoveries = discoveries.OrderBy((PrefabDiscovery discovery) => discovery.Name, StringComparer.OrdinalIgnoreCase).ToList(); if (HarnessPrefabsPlugin.IsSourceOfTruth) { if (TryBuildActiveRulesFromDisk(_lastDiscoveries, out Dictionary rules)) { CommitSourceRules(rules, _lastDiscoveries); } else if (_activeRules.Count == 0) { CommitSourceRules(BuildActiveRules(_lastDiscoveries, includeDiskOverrides: false), _lastDiscoveries); } return; } string value = _syncedRules.Value; if (!string.IsNullOrWhiteSpace(value)) { if (TryBuildSyncedRules(_lastDiscoveries, value, out Dictionary rules2)) { _activeRules = rules2; _lastSyncedRulesPayload = value; } else if (_activeRules.Count == 0) { _activeRules = BuildActiveRules(_lastDiscoveries, includeDiskOverrides: false); } } else { _activeRules = BuildActiveRules(_lastDiscoveries, includeDiskOverrides: false); } } public static bool TryGetRule(string prefabName, out PrefabRule rule) { return _activeRules.TryGetValue(prefabName, out rule); } public static bool TryWriteFullScaffoldConfigurationFile(out string path, out string error) { path = FullScaffoldPath; error = ""; if (_activeRules.Count == 0) { error = "HarnessPrefabs: no active prefab rules are available yet."; return false; } try { WriteIfChanged(path, GeneratedHeader("full scaffold") + SerializeFull(_activeRules)); HarnessPrefabsPlugin.Log.LogInfo((object)("Wrote prefab full scaffold to " + path + ".")); return true; } catch (Exception ex) { error = ex.Message; return false; } } private static Dictionary BuildActiveRules(IEnumerable discoveries, bool includeDiskOverrides = true) { if (includeDiskOverrides) { EnsureOverrideFile(); } Dictionary dictionary = (includeDiskOverrides ? LoadOverridesFromDisk() : new Dictionary(StringComparer.Ordinal)); Dictionary dictionary2 = new Dictionary(StringComparer.Ordinal); foreach (PrefabDiscovery discovery in discoveries) { PrefabRule prefabRule = CreateDefaultRule(discovery); if (dictionary.TryGetValue(discovery.Name, out var value)) { ApplyOverride(prefabRule, value); } dictionary2[discovery.Name] = prefabRule; } return NormalizeRules(dictionary2); } private static bool TryBuildActiveRulesFromDisk(IEnumerable discoveries, out Dictionary rules) { try { rules = BuildActiveRules(discoveries); return true; } catch (Exception ex) { rules = null; HarnessPrefabsPlugin.Log.LogError((object)("Failed to load prefab overrides. Keeping the last known good policy. Error: " + ex.Message)); return false; } } private static bool TryBuildSyncedRules(IEnumerable discoveries, string yaml, out Dictionary rules) { try { rules = ((!string.IsNullOrWhiteSpace(yaml)) ? BuildRulesFromSyncedPayload(discoveries, yaml) : BuildActiveRules(discoveries, includeDiskOverrides: false)); return true; } catch (Exception ex) { rules = null; HarnessPrefabsPlugin.Log.LogError((object)("Failed to load synced prefab policy. Keeping the last known good policy. Error: " + ex.Message)); return false; } } private static Dictionary BuildRulesFromSyncedPayload(IEnumerable discoveries, string yaml) { Dictionary dictionary = BuildActiveRules(discoveries, includeDiskOverrides: false); foreach (PrefabRuleEntry item in DeserializeEntries(yaml, "synced prefab payload")) { string text = NormalizePrefabName(item.Prefab); if (text.Length != 0 && dictionary.TryGetValue(text, out var value)) { item.Prefab = text; NormalizeEntry(item); ApplyOverride(value, item); } } return NormalizeRules(dictionary); } private static PrefabRule CreateDefaultRule(PrefabDiscovery discovery) { PrefabRule rule; return NormalizeRule(MvbpPrefabDefaults.TryCreateRule(discovery, out rule) ? rule : new PrefabRule { Access = discovery.Access, Category = discovery.Category, ClipEverything = discovery.ClipEverything, ClipGround = discovery.ClipGround, AllowedInDungeons = discovery.AllowedInDungeons, CanBeRemoved = true, Components = new ComponentList(discovery.Components) }); } private static void ApplyOverride(PrefabRule rule, PrefabRuleEntry entry) { if (entry.Category != null) { rule.Category = NormalizeCategory(entry.Category); if (rule.Access != PrefabAccess.Hidden && !entry.Enabled.HasValue) { rule.Access = ResolveAccess(enabled: true, rule.Category); } } if (entry.DisplayName != null) { rule.DisplayName = entry.DisplayName; } if (entry.Description != null) { rule.Description = entry.Description; } if (entry.CraftingStation != null) { rule.CraftingStation = entry.CraftingStation; } if (entry.Requirements != null) { rule.Requirements = PrefabRequirementParser.Clone(entry.Requirements); } if (entry.Flags != null) { ApplyFlags(rule, entry.Flags); } if (entry.Enabled.HasValue) { rule.Access = ResolveAccess(entry.Enabled.Value, rule.Category); } } private static Dictionary LoadOverridesFromDisk() { Dictionary dictionary = new Dictionary(StringComparer.Ordinal); foreach (string item in EnumerateOverrideFiles()) { foreach (PrefabRuleEntry item2 in DeserializeEntries(File.ReadAllText(item), item)) { string text = NormalizePrefabName(item2.Prefab); if (text.Length != 0) { item2.Prefab = text; NormalizeEntry(item2); if (!dictionary.TryGetValue(text, out var value)) { dictionary[text] = item2; } else { OverlayEntry(value, item2); } } } } return dictionary; } private static void OverlayEntry(PrefabRuleEntry target, PrefabRuleEntry source) { target.Enabled = source.Enabled ?? target.Enabled; target.Category = source.Category ?? target.Category; target.DisplayName = source.DisplayName ?? target.DisplayName; target.Description = source.Description ?? target.Description; target.CraftingStation = source.CraftingStation ?? target.CraftingStation; target.Requirements = source.Requirements ?? target.Requirements; target.Flags = source.Flags ?? target.Flags; } private static IEnumerable EnumerateOverrideFiles() { if (!Directory.Exists(RulesDirectory)) { return Array.Empty(); } return (from path in Directory.GetFiles(RulesDirectory, "*.yml").Concat(Directory.GetFiles(RulesDirectory, "*.yaml")) where IsOverrideFileName(Path.GetFileName(path)) orderby (!IsBaseOverrideFile(path)) ? 1 : 0 select path).ThenBy((string path) => path, StringComparer.OrdinalIgnoreCase).ToList(); } private static bool IsOverrideFileName(string fileName) { if (string.IsNullOrWhiteSpace(fileName)) { return false; } string extension = Path.GetExtension(fileName); if (!extension.Equals(".yml", StringComparison.OrdinalIgnoreCase) && !extension.Equals(".yaml", StringComparison.OrdinalIgnoreCase)) { return false; } if (fileName.Equals("prefabs.reference.yml", StringComparison.OrdinalIgnoreCase) || fileName.Equals("prefabs.full.yml", StringComparison.OrdinalIgnoreCase)) { return false; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); if (!fileNameWithoutExtension.Equals("prefabs", StringComparison.OrdinalIgnoreCase)) { return fileNameWithoutExtension.StartsWith("prefabs_", StringComparison.OrdinalIgnoreCase); } return true; } private static bool IsBaseOverrideFile(string path) { return Path.GetFileName(path).Equals("prefabs.yml", StringComparison.OrdinalIgnoreCase); } private static void EnsureOverrideFile() { Directory.CreateDirectory(RulesDirectory); if (!File.Exists(RulesPath)) { WriteIfChanged(RulesPath, DefaultOverrideTemplate()); } } private static string DefaultOverrideTemplate() { return string.Join(Environment.NewLine, "# HarnessPrefabs prefab overrides.", "# Top-level list schema. Copy entries from prefabs.reference.yml.", "# Later entries and later prefabs_*.yml files override earlier values for the same prefab.", "#", "# Full override example:", "# - prefab: barrell # Internal prefab name.", "# enabled: true # true exposes it; false hides/overrides it off.", "# category: Furniture # Hammer tab/category. Harness tabs are admin-only.", "# displayName: Barrel # Optional in-game piece name. Empty uses prefab name.", "# description: \"\" # Optional in-game tooltip/body text.", "# craftingStation: Workbench # None, Workbench, Forge, Stonecutter, BlackForge, etc.", "# requirements: # Optional build costs. Omit or [] for free placement.", "# - FineWood: 2 # ItemPrefabName: amount.", "# - Iron: 1", "# flags: true, true, false, true # clipEverything, clipGround, allowedInDungeons, canBeRemoved.", "# components: [Piece, WearNTear] # Reference/sort hint from full scaffold; usually leave copied.", "#", "# Run `harnessprefabs:full` in-game to generate prefabs.full.yml with displayName,", "# description, flags, and components for deeper review.", ""); } private static string GeneratedHeader(string label) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("# Generated by HarnessPrefabs: prefabs " + label + "."); stringBuilder.AppendLine("# Do not edit this generated file directly. Copy entries into prefabs.yml or prefabs_*.yml."); stringBuilder.AppendLine(label.Equals("full scaffold", StringComparison.OrdinalIgnoreCase) ? "# Schema: top-level list. flags = clipEverything, clipGround, allowedInDungeons, canBeRemoved." : "# Schema: top-level list. Reference omits full-only fields: displayName, description, flags, components."); return stringBuilder.ToString(); } private static void CommitSourceRules(Dictionary rules, IReadOnlyCollection discoveries) { string text = SerializePolicy(rules, discoveries); if (!string.Equals(_syncedRules.Value, text, StringComparison.Ordinal)) { _syncedRules.Value = text; } _activeRules = rules; try { WriteReferenceArtifact(discoveries, rules); } catch (Exception ex) { HarnessPrefabsPlugin.Log.LogWarning((object)("Failed to update prefab reference artifact: " + ex.Message)); } } private static void WriteReferenceArtifact(IReadOnlyCollection discoveries, IReadOnlyDictionary rules) { if (HarnessPrefabsPlugin.IsSourceOfTruth && discoveries.Count != 0 && rules.Count != 0) { string content = BuildReferenceContent(discoveries, rules); WriteIfChanged(ReferencePath, content); } } private static string BuildReferenceContent(IEnumerable discoveries, IReadOnlyDictionary rules) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(GeneratedHeader("reference")); List source = discoveries.Where((PrefabDiscovery discovery) => rules.ContainsKey(discovery.Name)).ToList(); IReadOnlyDictionary owners = PrefabOwnerCatalog.GetOwnerNames(source.Select((PrefabDiscovery discovery) => discovery.Name)); bool flag = false; string value2; foreach (IGrouping item in (from @group in source.GroupBy((PrefabDiscovery discovery) => (!owners.TryGetValue(discovery.Name, out value2)) ? "Unknown / Untracked" : value2, StringComparer.OrdinalIgnoreCase) orderby GetOwnerSortBucket(@group.Key) select @group).ThenBy, string>((IGrouping group) => group.Key, StringComparer.OrdinalIgnoreCase)) { stringBuilder.Append("# ===== "); stringBuilder.Append(string.IsNullOrWhiteSpace(item.Key) ? "Unknown / Untracked" : item.Key.Trim()); stringBuilder.AppendLine(" ====="); foreach (PrefabDiscovery item2 in item.OrderBy((PrefabDiscovery discovery) => discovery.Name, StringComparer.OrdinalIgnoreCase)) { string value = SparseSerializer.Serialize(new PrefabRuleEntry[1] { ToReferenceEntry(item2.Name, rules[item2.Name]) }).TrimEnd('\r', '\n'); stringBuilder.AppendLine(value); flag = true; } } if (!flag) { return GeneratedHeader("reference"); } return stringBuilder.ToString(); } private static int GetOwnerSortBucket(string ownerName) { if (string.Equals(ownerName, "Valheim", StringComparison.OrdinalIgnoreCase)) { return 0; } if (!string.Equals(ownerName, "Unknown / Untracked", StringComparison.OrdinalIgnoreCase)) { return 1; } return 2; } private static PrefabRuleEntry ToReferenceEntry(string prefabName, PrefabRule rule) { PrefabRuleEntry prefabRuleEntry = new PrefabRuleEntry { Prefab = prefabName, Enabled = (rule.Access != PrefabAccess.Hidden), Category = rule.Category, CraftingStation = rule.CraftingStation, Requirements = PrefabRequirementParser.Clone(rule.Requirements) }; if (IsNone(prefabRuleEntry.CraftingStation)) { prefabRuleEntry.CraftingStation = null; } List requirements = prefabRuleEntry.Requirements; if (requirements != null && requirements.Count == 0) { prefabRuleEntry.Requirements = null; } return prefabRuleEntry; } private static PrefabRuleEntry ToSyncedOverrideEntry(string prefabName, PrefabRule rule, PrefabRule defaultRule) { PrefabRuleEntry prefabRuleEntry = new PrefabRuleEntry { Prefab = prefabName }; if (rule.Access != defaultRule.Access) { prefabRuleEntry.Enabled = rule.Access != PrefabAccess.Hidden; } if (!string.Equals(rule.Category, defaultRule.Category, StringComparison.Ordinal)) { prefabRuleEntry.Category = rule.Category; } if (!string.Equals(rule.DisplayName, defaultRule.DisplayName, StringComparison.Ordinal)) { prefabRuleEntry.DisplayName = rule.DisplayName; } if (!string.Equals(rule.Description, defaultRule.Description, StringComparison.Ordinal)) { prefabRuleEntry.Description = rule.Description; } if (!string.Equals(rule.CraftingStation, defaultRule.CraftingStation, StringComparison.Ordinal)) { prefabRuleEntry.CraftingStation = rule.CraftingStation; } if (!RequirementsEqual(rule.Requirements, defaultRule.Requirements)) { prefabRuleEntry.Requirements = PrefabRequirementParser.Clone(rule.Requirements); } if (!FlagsEqual(rule, defaultRule)) { prefabRuleEntry.Flags = FormatFlags(rule); } return prefabRuleEntry; } private static PrefabRuleEntry ToFullEntry(string prefabName, PrefabRule rule) { return new PrefabRuleEntry { Prefab = prefabName, Enabled = (rule.Access != PrefabAccess.Hidden), Category = rule.Category, DisplayName = rule.DisplayName, Description = rule.Description, CraftingStation = rule.CraftingStation, Requirements = PrefabRequirementParser.Clone(rule.Requirements), Flags = FormatFlags(rule), Components = new ComponentList(rule.Components) }; } private static List ToFullEntries(IReadOnlyDictionary rules) { return (from pair in rules.OrderBy, string>((KeyValuePair pair) => pair.Key, StringComparer.OrdinalIgnoreCase).ThenBy, string>((KeyValuePair pair) => pair.Key, StringComparer.Ordinal) select ToFullEntry(pair.Key, pair.Value)).ToList(); } private static List ToSyncedPolicyEntries(IReadOnlyDictionary rules, IReadOnlyCollection discoveries) { Dictionary defaults = discoveries.Where((PrefabDiscovery discovery) => !string.IsNullOrWhiteSpace(discovery.Name)).GroupBy((PrefabDiscovery discovery) => NormalizePrefabName(discovery.Name), StringComparer.Ordinal).ToDictionary, string, PrefabRule>((IGrouping group) => group.Key, (IGrouping group) => CreateDefaultRule(group.First()), StringComparer.Ordinal); if (rules.Count != defaults.Count || rules.Keys.Any((string prefabName) => !defaults.ContainsKey(prefabName))) { throw new InvalidDataException("Active prefab rules must have exactly one matching discovery default before synchronization."); } return (from pair in rules.OrderBy, string>((KeyValuePair pair) => pair.Key, StringComparer.OrdinalIgnoreCase).ThenBy, string>((KeyValuePair pair) => pair.Key, StringComparer.Ordinal) select ToSyncedOverrideEntry(pair.Key, pair.Value, defaults[pair.Key])).Where(HasSyncedOverrideFields).ToList(); } private static bool HasSyncedOverrideFields(PrefabRuleEntry entry) { if (!entry.Enabled.HasValue && entry.Category == null && entry.DisplayName == null && entry.Description == null && entry.CraftingStation == null && entry.Requirements == null) { return entry.Flags != null; } return true; } private static bool FlagsEqual(PrefabRule left, PrefabRule right) { if (left.ClipEverything == right.ClipEverything && left.ClipGround == right.ClipGround && left.AllowedInDungeons == right.AllowedInDungeons) { return left.CanBeRemoved == right.CanBeRemoved; } return false; } private static bool RequirementsEqual(IReadOnlyList? left, IReadOnlyList? right) { if (left == null) { left = Array.Empty(); } if (right == null) { right = Array.Empty(); } if (left.Count != right.Count) { return false; } for (int i = 0; i < left.Count; i++) { if (!string.Equals(left[i].Item, right[i].Item, StringComparison.Ordinal) || left[i].Amount != right[i].Amount) { return false; } } return true; } private static Dictionary NormalizeRules(IEnumerable>? rules) { return (rules ?? Enumerable.Empty>()).Where>((KeyValuePair pair) => !string.IsNullOrWhiteSpace(pair.Key) && pair.Value != null).OrderBy, string>((KeyValuePair pair) => pair.Key, StringComparer.OrdinalIgnoreCase).ToDictionary, string, PrefabRule>((KeyValuePair pair) => NormalizePrefabName(pair.Key), (KeyValuePair pair) => NormalizeRule(pair.Value), StringComparer.Ordinal); } private static PrefabRule NormalizeRule(PrefabRule rule) { rule.Category = NormalizeCategory(rule.Category); if (rule.Access != PrefabAccess.Hidden) { rule.Access = ResolveAccess(enabled: true, rule.Category); } PrefabRule prefabRule = rule; if (prefabRule.DisplayName == null) { string text = (prefabRule.DisplayName = ""); } prefabRule = rule; if (prefabRule.Description == null) { string text = (prefabRule.Description = ""); } rule.CraftingStation = (string.IsNullOrWhiteSpace(rule.CraftingStation) ? "None" : rule.CraftingStation.Trim()); rule.Requirements = PrefabRequirementParser.Clone(rule.Requirements); rule.Components = NormalizeComponents(rule.Components); return rule; } private static ComponentList NormalizeComponents(IEnumerable? components) { return new ComponentList((from component in components ?? Enumerable.Empty() where !string.IsNullOrWhiteSpace(component) select component.Trim()).Where(IsComponentName).Distinct(StringComparer.Ordinal).OrderBy((string component) => component, StringComparer.OrdinalIgnoreCase)); } private static void NormalizeEntry(PrefabRuleEntry entry) { entry.Prefab = NormalizePrefabName(entry.Prefab ?? ""); entry.Category = ((entry.Category == null) ? null : NormalizeCategory(entry.Category)); entry.DisplayName = entry.DisplayName?.Trim(); entry.Description = entry.Description?.Trim(); entry.CraftingStation = ((entry.CraftingStation == null) ? null : (string.IsNullOrWhiteSpace(entry.CraftingStation) ? "None" : entry.CraftingStation.Trim())); entry.Requirements = ((entry.Requirements == null) ? null : PrefabRequirementParser.Clone(entry.Requirements)); entry.Flags = (string.IsNullOrWhiteSpace(entry.Flags) ? null : entry.Flags.Trim()); entry.Components = ((entry.Components == null) ? null : NormalizeComponents(entry.Components)); } private static bool IsComponentName(string value) { if (value.Length > 0 && !value.StartsWith("MVBP", StringComparison.Ordinal)) { return value.IndexOf(':') < 0; } return false; } private static string NormalizeCategory(string category) { if (string.IsNullOrWhiteSpace(category)) { return "Harness Props"; } return BuildCategories.NormalizeCategory(category); } private static PrefabAccess ResolveAccess(bool enabled, string category) { if (!enabled) { return PrefabAccess.Hidden; } if (!BuildCategories.IsAdminCategory(category)) { return PrefabAccess.Public; } return PrefabAccess.Admin; } private static void ApplyFlags(PrefabRule rule, string? flags) { if (!string.IsNullOrWhiteSpace(flags)) { string[] array = (from part in flags.Split(new char[1] { ',' }) select part.Trim()).ToArray(); if (array.Length != 4 || array.Any((string part) => !bool.TryParse(part, out var _))) { throw new InvalidDataException("Prefab flags must contain exactly four true/false values: clipEverything, clipGround, allowedInDungeons, canBeRemoved."); } rule.ClipEverything = bool.Parse(array[0]); rule.ClipGround = bool.Parse(array[1]); rule.AllowedInDungeons = bool.Parse(array[2]); rule.CanBeRemoved = bool.Parse(array[3]); } } private static string FormatFlags(PrefabRule rule) { return string.Join(", ", FormatBool(rule.ClipEverything), FormatBool(rule.ClipGround), FormatBool(rule.AllowedInDungeons), FormatBool(rule.CanBeRemoved)); } private static string FormatBool(bool value) { if (!value) { return "false"; } return "true"; } private static List DeserializeEntries(string yaml, string source) { if (string.IsNullOrWhiteSpace(yaml)) { return new List(); } try { return Deserializer.Deserialize>(yaml) ?? new List(); } catch (YamlException ex) { throw new InvalidDataException("Invalid HarnessPrefabs prefab YAML in " + source + ": " + ex.Message, ex); } } private static string SerializeFull(IReadOnlyDictionary rules) { return FullSerializer.Serialize(ToFullEntries(rules)); } private static string SerializePolicy(IReadOnlyDictionary rules, IReadOnlyCollection discoveries) { return SparseSerializer.Serialize(ToSyncedPolicyEntries(rules, discoveries)); } private static string NormalizePrefabName(string name) { return HarnessPrefabsRuntime.NormalizePrefabName(name); } private static bool IsNone(string? value) { string text = value?.Trim() ?? ""; if (text.Length != 0 && !text.Equals("none", StringComparison.OrdinalIgnoreCase)) { return text.Equals("null", StringComparison.OrdinalIgnoreCase); } return true; } private static void WriteIfChanged(string path, string content) { Directory.CreateDirectory(Path.GetDirectoryName(path)); if (!File.Exists(path) || !string.Equals(File.ReadAllText(path), content, StringComparison.Ordinal)) { File.WriteAllText(path, content); } } } [BepInPlugin("sighsorry.valheim.harnessprefabs", "HarnessPrefabs", "1.0.3")] [BepInDependency("com.jotunn.jotunn", "2.29.1")] public sealed class HarnessPrefabsPlugin : BaseUnityPlugin { internal enum Toggle { Off, On } internal const string ModName = "HarnessPrefabs"; internal const string ModVersion = "1.0.3"; internal const string Author = "sighsorry"; internal const string ModGuid = "sighsorry.valheim.harnessprefabs"; internal const string JotunnGuid = "com.jotunn.jotunn"; internal const string JotunnVersion = "2.29.1"; private const double ReloadDebounceMilliseconds = 500.0; private static readonly string ConfigFileName = "sighsorry.valheim.harnessprefabs.cfg"; private static readonly string ConfigFileFullPath = Path.Combine(Paths.ConfigPath, ConfigFileName); private static readonly ConfigSync SyncedConfig = new ConfigSync("sighsorry.valheim.harnessprefabs") { DisplayName = "HarnessPrefabs", CurrentVersion = "1.0.3", MinimumRequiredVersion = "1.0.3" }; private static readonly CustomSyncedValue SyncedRules = new CustomSyncedValue(SyncedConfig, "prefabs-yaml", string.Empty, 100); private readonly Harmony _harmony = new Harmony("sighsorry.valheim.harnessprefabs"); private readonly object _reloadLock = new object(); private FileSystemWatcher? _configWatcher; private FileSystemWatcher? _rulesWatcher; private System.Timers.Timer? _configReloadTimer; private System.Timers.Timer? _rulesReloadTimer; private string? _lastConfigFileText; private static bool _sourceOfTruthFileModeReady; private static ConfigEntry LockConfiguration = null; private static ConfigEntry VerboseLogging = null; private static ConfigEntry ShowHarnessPrefabTabs = null; private static ConfigEntry TrailershipVikingShipSpeedRatio = null; private static ConfigEntry EnableUnsafeBedPatches = null; private static ConfigEntry UnsafeFermenterPatchDurationPercent = null; internal static ManualLogSource Log { get; private set; } = null; internal static bool IsAdmin => SyncedConfig.IsAdmin; internal static bool IsSourceOfTruth => SyncedConfig.IsSourceOfTruth; internal static bool Verbose => VerboseLogging.Value == Toggle.On; internal static bool IsDebugMode => Player.m_debugMode; internal static bool HarnessHammerTabsEnabled { get { if (IsAdmin && IsDebugMode) { if (ShowHarnessPrefabTabs != null) { return ShowHarnessPrefabTabs.Value == Toggle.On; } return true; } return false; } } internal static bool UnsafeBedPatchesEnabled => EnableUnsafeBedPatches.Value == Toggle.On; internal static int FermenterPatchDurationPercent => Math.Min(100, Math.Max(0, UnsafeFermenterPatchDurationPercent.Value)); internal static float TrailershipSpeedRatio => Mathf.Clamp((TrailershipVikingShipSpeedRatio == null) ? 0.66f : TrailershipVikingShipSpeedRatio.Value, 0.5f, 1f); private static HarnessPrefabsPlugin? Instance { get; set; } private void Awake() { //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Instance = this; bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; try { LockConfiguration = BindSynced("1 - General", "Lock Configuration", Toggle.On, "If on, prefab policy is controlled by the server and can only be changed by admins."); VerboseLogging = BindSynced("1 - General", "Verbose Logging", Toggle.Off, "If on, writes detailed prefab discovery and hammer registration logs.", synchronizedSetting: false); ShowHarnessPrefabTabs = BindSynced("1 - General", "Show Harness Tabs", Toggle.On, "If on, Harness Hammer tabs are visible to admin clients while Valheim debugmode is enabled. If off, Harness tabs stay hidden even in debugmode.", synchronizedSetting: false); ShowHarnessPrefabTabs.SettingChanged += delegate { PrefabBuildManager.RefreshIfHarnessHammerVisibilityChanged(); }; TrailershipVikingShipSpeedRatio = BindSynced("2 - Prefab Tweaks", "Trailership VikingShip Speed Ratio", 0.66f, new ConfigDescription("Controls Trailership movement speed relative to VikingShip. 0.5 is half speed, 1.0 matches VikingShip.", (AcceptableValueBase)(object)new AcceptableValueRange(0.5f, 1f), Array.Empty())); TrailershipVikingShipSpeedRatio.SettingChanged += delegate { PrefabBuildManager.RefreshFromCachedRules("Trailership speed ratio changed"); }; EnableUnsafeBedPatches = BindSynced("2 - Prefab Tweaks", "Enable Bed Patches", Toggle.Off, "If on, player-built MVBP bed prefabs get Bed components and spawn points. Unsafe: disabling the mod later can affect spawn points."); UnsafeFermenterPatchDurationPercent = BindSynced("2 - Prefab Tweaks", "Fermenter Patch Duration Percent", 0, new ConfigDescription("0 disables the dvergrprops_barrel fermenter patch. 1-100 enables the patch and sets fermentation time as a percentage of the vanilla fermenter duration. 70 matches the old MVBP behavior. Unsafe: disabling the mod later can affect fermenting contents.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 100), Array.Empty())); SyncedConfig.AddLockingConfigEntry(LockConfiguration); PrefabLocalizationOverrideManager.Initialize(SyncedConfig); PrefabRuleStore.Initialize(SyncedRules); HarnessPrefabsConsoleCommands.Register(); SyncedRules.ValueChanged += OnSyncedRulesChanged; SyncedConfig.SourceOfTruthChanged += OnSourceOfTruthChanged; PieceManager.OnPiecesRegistered += OnJotunnPiecesRegistered; _harmony.PatchAll(typeof(HarnessPrefabsPlugin).Assembly); SetupConfigWatcher(); SaveConfig(reload: false); _lastConfigFileText = ReadFileTextIfExists(ConfigFileFullPath); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } Log.LogInfo((object)"HarnessPrefabs 1.0.3 loaded."); } private void OnDestroy() { SaveConfig(reload: false); _configWatcher?.Dispose(); _rulesWatcher?.Dispose(); _configReloadTimer?.Dispose(); _rulesReloadTimer?.Dispose(); PrefabLocalizationOverrideManager.Dispose(); SyncedRules.ValueChanged -= OnSyncedRulesChanged; SyncedConfig.SourceOfTruthChanged -= OnSourceOfTruthChanged; PieceManager.OnPiecesRegistered -= OnJotunnPiecesRegistered; if (Instance == this) { Instance = null; } _harmony.UnpatchSelf(); } private static void OnSyncedRulesChanged() { if (!IsSourceOfTruth && PrefabRuleStore.LoadSyncedRulesForCurrentAuthority()) { PrefabBuildManager.RefreshFromCachedRules("synced prefab rules changed"); } } private static void OnSourceOfTruthChanged(bool isSourceOfTruth) { if (isSourceOfTruth) { EnsureSourceOfTruthFileMode(); } else { _sourceOfTruthFileModeReady = false; Instance?.SetupRuleWatcher(); PrefabLocalizationOverrideManager.SetupFileWatcher(); } PrefabBuildManager.Refresh("config authority changed"); } private static void OnJotunnPiecesRegistered() { PrefabBuildManager.MarkJotunnPiecesRegistered(); PrefabBuildManager.Refresh("Jotunn.OnPiecesRegistered"); } internal static void EnsureSourceOfTruthFileMode() { if (IsSourceOfTruth && !_sourceOfTruthFileModeReady) { Instance?.SetupRuleWatcher(); PrefabLocalizationOverrideManager.SetupFileWatcher(); if (PrefabLocalizationOverrideManager.ReloadFromDiskAndSync()) { _sourceOfTruthFileModeReady = true; } } } private void SetupConfigWatcher() { if (_configReloadTimer == null) { _configReloadTimer = CreateReloadTimer(ReadConfigValues); } _configWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName) { IncludeSubdirectories = false, SynchronizingObject = ThreadingHelper.SynchronizingObject, EnableRaisingEvents = true }; _configWatcher.Changed += ScheduleConfigReload; _configWatcher.Created += ScheduleConfigReload; _configWatcher.Renamed += ScheduleConfigReload; } private void SetupRuleWatcher() { if (!IsSourceOfTruth) { _rulesReloadTimer?.Stop(); _rulesWatcher?.Dispose(); _rulesWatcher = null; return; } _rulesWatcher?.Dispose(); if (_rulesReloadTimer == null) { _rulesReloadTimer = CreateReloadTimer(ReadRuleValues); } string rulesDirectory = PrefabRuleStore.RulesDirectory; Directory.CreateDirectory(rulesDirectory); _rulesWatcher = new FileSystemWatcher(rulesDirectory, "*.*") { IncludeSubdirectories = false, SynchronizingObject = ThreadingHelper.SynchronizingObject, EnableRaisingEvents = true }; _rulesWatcher.Changed += ScheduleRuleReload; _rulesWatcher.Created += ScheduleRuleReload; _rulesWatcher.Deleted += ScheduleRuleReload; _rulesWatcher.Renamed += ScheduleRuleReload; } private void ScheduleConfigReload(object sender, FileSystemEventArgs e) { RestartTimer(_configReloadTimer); } private void ScheduleRuleReload(object sender, FileSystemEventArgs e) { if (IsSourceOfTruth && PrefabRuleStore.IsOverrideFileEvent(e)) { RestartTimer(_rulesReloadTimer); } } private void ReadConfigValues(object sender, ElapsedEventArgs e) { lock (_reloadLock) { if (!File.Exists(ConfigFileFullPath)) { Log.LogWarning((object)"Config file does not exist. Skipping reload."); return; } try { string b = File.ReadAllText(ConfigFileFullPath); if (!string.Equals(_lastConfigFileText, b, StringComparison.Ordinal)) { SaveConfig(reload: true); _lastConfigFileText = ReadFileTextIfExists(ConfigFileFullPath); PrefabBuildManager.Refresh("config file reloaded"); } } catch (Exception ex) { Log.LogError((object)("Error reloading configuration: " + ex.Message)); } } } private void ReadRuleValues(object sender, ElapsedEventArgs e) { if (!IsSourceOfTruth) { return; } lock (_reloadLock) { try { if (!PrefabRuleStore.HasCachedDiscoveries) { PrefabBuildManager.Refresh("prefab rules file reloaded"); } else if (PrefabRuleStore.PublishRulesFromDisk()) { PrefabBuildManager.RefreshFromCachedRules("prefab rules file reloaded"); } } catch (Exception ex) { Log.LogError((object)("Error reloading prefab rules: " + ex.Message)); } } } private static System.Timers.Timer CreateReloadTimer(ElapsedEventHandler handler) { System.Timers.Timer timer = new System.Timers.Timer(500.0); timer.AutoReset = false; timer.SynchronizingObject = ThreadingHelper.SynchronizingObject; timer.Elapsed += handler; return timer; } private static void RestartTimer(System.Timers.Timer? timer) { if (timer != null) { timer.Stop(); timer.Start(); } } private static string? ReadFileTextIfExists(string path) { if (!File.Exists(path)) { return null; } return File.ReadAllText(path); } private void SaveConfig(bool reload) { bool saveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = false; try { if (reload) { ((BaseUnityPlugin)this).Config.Reload(); } ((BaseUnityPlugin)this).Config.Save(); } finally { ((BaseUnityPlugin)this).Config.SaveOnConfigSet = saveOnConfigSet; } } private ConfigEntry BindSynced(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return BindSynced(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } private ConfigEntry BindSynced(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown object[] array = description.Tags ?? Array.Empty(); ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, array); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(group, name, value, val); SyncedConfig.AddConfigEntry(val2).SynchronizedConfig = synchronizedSetting; return val2; } } [HarmonyPatch(typeof(ZNetScene), "Awake")] internal static class ZNetSceneAwakePatch { private static void Postfix() { PrefabBuildManager.Refresh("ZNetScene.Awake"); } } [HarmonyPatch(typeof(ObjectDB), "Awake")] internal static class ObjectDbAwakePatch { private static void Postfix() { PrefabBuildManager.Refresh("ObjectDB.Awake"); } } [HarmonyPatch(typeof(ZoneSystem), "Start")] internal static class ZoneSystemStartPatch { private static void Postfix() { PrefabBuildManager.Refresh("ZoneSystem.Start"); } } [HarmonyPatch(typeof(Player), "SetLocalPlayer")] internal static class PlayerSetLocalPlayerPatch { private static void Postfix() { PrefabBuildManager.Refresh("local player ready"); } } [HarmonyPatch(typeof(Player), "Update")] internal static class PlayerUpdatePatch { private static void Postfix(Player __instance) { if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer) { PrefabBuildManager.RefreshIfHarnessHammerVisibilityChanged(); } } } [HarmonyPatch(typeof(Player), "SetupPlacementGhost")] internal static class PlayerSetupPlacementGhostPatch { private static void Postfix(Player __instance) { PrefabPlacementPatchRegistry.PatchGhost(__instance.m_placementGhost); } } [HarmonyPatch(typeof(Player), "UpdatePlacementGhost")] internal static class PlayerUpdatePlacementGhostPatch { private static void Postfix(Player __instance) { PrefabPlacementPatchRegistry.ApplyGhostOffset(__instance.m_placementGhost); } } [HarmonyPatch(typeof(PieceTable), "UpdateAvailable")] internal static class PieceTableUpdateAvailablePatch { private static void Prefix(PieceTable __instance, HashSet knownRecipies) { PrefabBuildManager.PreparePieceTableForUpdate(__instance, knownRecipies); } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } internal abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] internal sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", (Action)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } } 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 { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool Contains(this string source, char c) { return source.IndexOf(c) != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EndsWith(this string source, char c) { if (source.Length > 0) { return source[source.Length - 1] == c; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool StartsWith(this string source, char c) { if (source.Length > 0) { return source[0] == c; } return false; } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class ReflectionExtensions { private static readonly Func IsInstance = (PropertyInfo property) => !(property.GetMethod ?? property.SetMethod).IsStatic; private static readonly Func IsInstancePublic = (PropertyInfo property) => IsInstance(property) && (property.GetMethod ?? property.SetMethod).IsPublic; 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) { return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).FirstOrDefault((PropertyInfo p) => p.Name == name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetRuntimeField(name); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { Func predicate = (includeNonPublic ? IsInstance : IsInstancePublic); if (!type.IsInterface()) { return type.GetRuntimeProperties().Where(predicate); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetRuntimeProperties().Where(predicate)); } public static IEnumerable GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return from f in type.GetRuntimeFields() where !f.IsStatic && f.IsPublic select f; } public static IEnumerable GetPublicStaticMethods(this Type type) { return from m in type.GetRuntimeMethods() where m.IsPublic && m.IsStatic select m; } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => !m.IsPublic && m.IsStatic && m.Name.Equals(name)) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetRuntimeMethods().FirstOrDefault(delegate(MethodInfo m) { if (m.IsPublic && m.IsStatic && m.Name.Equals(name)) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == parameterTypes.Length) { return parameters.Zip(parameterTypes, (ParameterInfo pi, Type pt) => pi.ParameterType == pt).All((bool r) => r); } return false; } return false; }); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetRuntimeMethods().FirstOrDefault((MethodInfo m) => m.IsPublic && !m.IsStatic && m.Name.Equals(name)); } 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 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(this PropertyInfo member) { return Attribute.GetCustomAttributes(member, typeof(TAttribute), inherit: true); } public static bool AcceptsNull(this MemberInfo member) { object[] customAttributes = member.DeclaringType.GetCustomAttributes(inherit: true); object obj = customAttributes.FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); int num = 0; if (obj != null) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty("Flag"); num = (byte)property.GetValue(obj); } object[] customAttributes2 = member.GetCustomAttributes(inherit: true); object obj2 = customAttributes2.FirstOrDefault((object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableAttribute"); PropertyInfo propertyInfo = (obj2?.GetType())?.GetProperty("NullableFlags"); byte[] source = (byte[])propertyInfo.GetValue(obj2); return source.Any((byte x) => x == 2) || num == 2; } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { internal abstract class BuilderSkeleton where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention; return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride(Expression> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter() 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(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } internal sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize(TextReader input) { return Deserialize(new Parser(input)); } public T Deserialize(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(string input) { return Deserialize(input); } public object? Deserialize(TextReader input) { return Deserialize(input); } public object? Deserialize(IParser parser) { return Deserialize(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(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume(out event2); object result = null; if (!parser.Accept(out var _) && !parser.Accept(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume(); } if (flag) { parser.Consume(); } return result; } } internal sealed class DeserializerBuilder : BuilderSkeleton { private Lazy objectFactory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly Dictionary typeMappings; private readonly ITypeConverter typeConverter; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; private bool enforceNullability; private bool caseInsensitivePropertyMatching; private bool enforceRequiredProperties; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer(enumNamingConvention, BuildTypeInspector()) }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value, enumNamingConvention, BuildTypeInspector()) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties, BuildTypeConverters()) }, { typeof(FsharpListNodeDeserializer), (Nothing _) => new FsharpListNodeDeserializer(BuildTypeInspector(), enumNamingConvention) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy(() => objectFactory, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public DeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public DeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public DeserializerBuilder WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public DeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public DeserializerBuilder WithEnforceRequiredMembers() { enforceRequiredProperties = true; return this; } public DeserializerBuilder WithoutNodeTypeResolver() 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() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (!DictionaryExtensions.TryAdd(typeMappings, typeFromHandle, typeFromHandle2)) { typeMappings[typeFromHandle] = typeFromHandle2; } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public DeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } internal sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable> preProcessingPhaseVisitors; public IObjectGraphVisitor InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor innerVisitor, IEventEmitter eventEmitter, IEnumerable> preProcessingPhaseVisitors, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } internal abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } internal sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } internal interface IAliasProvider { AnchorName GetAlias(object target); } internal interface IDeserializer { T Deserialize(string input); T Deserialize(TextReader input); T Deserialize(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); } internal interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } internal interface INamingConvention { string Apply(string value); string Reverse(string value); } internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer); } internal interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } internal interface IObjectAccessor { void Set(string name, object target, object value); object? Read(string name, object target); } internal interface IObjectDescriptor { object? Value { get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal 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."); } } internal 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); } internal interface IObjectGraphTraversalStrategy { void Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer); } internal interface IObjectGraphVisitor { 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); } internal 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() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, object? value); } internal interface IRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } internal 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); } internal interface ITypeInspector { IEnumerable 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); } internal interface ITypeResolver { Type Resolve(Type staticType, object? actualValue); } internal interface IValueDeserializer { object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { event Action ValueAvailable; } internal interface IValueSerializer { void SerializeValue(IEmitter emitter, object? value, Type? type); } internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } internal delegate object? ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object? value, Type? type = null); [Obsolete("Please use IYamlConvertible instead")] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } internal 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 : IEnumerable>, IEnumerable { public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly LazyComponentRegistration newRegistration; public RegistrationLocationSelector(LazyComponentRegistrationList registrations, LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax.After() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax.Before() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly TrackingLazyComponentRegistration newRegistration; public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); Func innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } private readonly List entries = new List(); public int Count => entries.Count; public IEnumerable> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList Clone() { LazyComponentRegistrationList lazyComponentRegistrationList = new LazyComponentRegistrationList(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Clear() { entries.Clear(); } public void Add(Type componentType, Func factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if (entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax CreateRegistrationLocationSelector(Type componentType, Func factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax CreateTrackingRegistrationLocationSelector(Type componentType, Func factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator> GetEnumerator() { return entries.Select((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() { 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(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(argumentBuilder(inner))); } public static List BuildComponentList(this LazyComponentRegistrationList registrations) { return registrations.Select((Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList(this LazyComponentRegistrationList registrations, TArgument argument) { return registrations.Select((Func factory) => factory(argument)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } internal 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; } } internal delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion); internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public bool AllowNulls => baseDescriptor.AllowNulls; public string Name { get; set; } public bool Required => baseDescriptor.Required; public Type Type => baseDescriptor.Type; 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() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } internal sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public string Serialize(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()); } } internal sealed class SerializerBuilder : BuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing), NestedObjectSerializer); } traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly Dictionary tagMappings = new Dictionary(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private ScalarStyle defaultScalarStyle; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public SerializerBuilder WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; return this; } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner, BuildTypeInspector()))); return Self; } public SerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName().WithUtf16SurrogatePairs(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(Func, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(Func, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, IObjectGraphVisitor, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal class Settings { public bool AllowPrivateConstructors { get; set; } } internal abstract class StaticBuilderSkeleton where TBuilder : StaticBuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal INamingConvention enumNamingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(ITypeResolver typeResolver) { typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter() 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(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { if (typeInspectorFactory == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal 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(); } } internal sealed class StaticDeserializerBuilder : StaticBuilderSkeleton { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly ITypeConverter typeConverter; private readonly Dictionary typeMappings; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; private bool enforceNullability; private bool caseInsensitivePropertyMatching; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base(context.GetTypeResolver()) { this.context = context; factory = context.GetFactory(); typeMappings = new Dictionary(); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(StaticArrayNodeDeserializer), (Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties: false, BuildTypeConverters()) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new NullTypeConverter(); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (Nothing _) => nodeDeserializer)); return this; } public StaticDeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { if (nodeDeserializerFactory == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public StaticDeserializerBuilder WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public StaticDeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public StaticDeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (Nothing _) => nodeTypeResolver)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { if (nodeTypeResolverFactory == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver() 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() 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())); } } internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing), NestedObjectSerializer); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter, v, t); } } } private readonly StaticContext context; private readonly StaticObjectFactory factory; private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly Dictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; private ScalarStyle defaultScalarStyle; protected override StaticSerializerBuilder Self => this; public StaticSerializerBuilder(StaticContext context) : base((ITypeResolver)new DynamicTypeResolver()) { this.context = context; factory = context.GetFactory(); typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory); } public StaticSerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public StaticSerializerBuilder WithQuotingNecessaryStrings() { quoteNecessaryStrings = true; return this; } public StaticSerializerBuilder WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; return this; } public StaticSerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner, BuildTypeInspector()))); return Self; } public StaticSerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory(wrapped, inner))); return Self; } public StaticSerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override StaticSerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public StaticSerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public StaticSerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, factory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings: false, ScalarStyle.Plain, YamlFormatter.Default, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public StaticSerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public StaticSerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public StaticSerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public StaticSerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName().WithUtf16SurrogatePairs(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(Func, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(Func, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, IObjectGraphVisitor, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal sealed class StreamFragment : IYamlConvertible { private readonly List events = new List(); public IList Events => events; void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { events.Clear(); int num = 0; do { if (!parser.MoveNext()) { throw new InvalidOperationException("The parser has reached the end before deserialization completed."); } ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (ParsingEvent @event in events) { emitter.Emit(@event); } } } internal sealed class TagMappings { private readonly Dictionary mappings; public TagMappings() { mappings = new Dictionary(); } public TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } internal Type? GetMapping(string tag) { if (!mappings.TryGetValue(tag, out Type value)) { return null; } return value; } } internal sealed class YamlAttributeOverrides { private readonly struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } public override bool Equals(object? obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } public override bool Equals(object? obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); } public int Matches(Type matchType) { int num = 0; Type type = matchType; while (type != null) { num++; if (type == RegisteredType) { return num; } type = type.BaseType(); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); [return: MaybeNull] public T GetAttribute(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out List value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out List value)) { value = new List(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public YamlAttributeOverrides Clone() { YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides(); foreach (KeyValuePair> @override in overrides) { foreach (AttributeMapping item in @override.Value) { yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return yamlAttributeOverrides; } public void Add(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } internal sealed class YamlAttributeOverridesInspector : ReflectionTypeInspector { public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool Required => baseDescriptor.Required; public bool AllowNulls => baseDescriptor.AllowNulls; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public Type? ConverterType => GetCustomAttribute()?.ConverterType ?? baseDescriptor.ConverterType; public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute() where T : Attribute { T attribute = overrides.GetAttribute(classType, Name); return attribute ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable GetProperties(Type type, object? container) { IEnumerable enumerable = innerTypeDescriptor.GetProperties(type, container); if (overrides != null) { enumerable = enumerable.Select((Func)((IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type))); } return enumerable; } } internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, object? container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return propertyDescriptor; }) orderby p.Order select p; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] internal sealed class YamlConverterAttribute : Attribute { public Type ConverterType { get; } public YamlConverterAttribute(Type converterType) { ConverterType = converterType; } } internal class YamlFormatter { public static YamlFormatter Default { get; } = new YamlFormatter(); public NumberFormatInfo NumberFormat { get; set; } = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public virtual Func FormatEnum { get; set; } = delegate(object value, ITypeInspector typeInspector, INamingConvention enumNamingConvention) { string empty = string.Empty; empty = ((value != null) ? typeInspector.GetEnumValue(value) : string.Empty); return enumNamingConvention.Apply(empty); }; public virtual Func PotentiallyQuoteEnums { get; set; } = (object _) => true; public string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public string FormatNumber(double number) { return number.ToString("G", NumberFormat); } public string FormatNumber(float number) { return number.ToString("G", NumberFormat); } public string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan/*cast due to .constrained prefix*/).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlMemberAttribute : Attribute { private DefaultValuesHandling? defaultValuesHandling; public string? Description { get; set; } public Type? SerializeAs { get; set; } public int Order { get; set; } public string? Alias { get; set; } public bool ApplyNamingConventions { get; set; } public ScalarStyle ScalarStyle { get; set; } public DefaultValuesHandling DefaultValuesHandling { get { return defaultValuesHandling.GetValueOrDefault(); } set { defaultValuesHandling = value; } } public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue; public YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, Inherited = false, AllowMultiple = true)] internal sealed class YamlSerializableAttribute : Attribute { public YamlSerializableAttribute() { } public YamlSerializableAttribute(Type serializableType) { } } [AttributeUsage(AttributeTargets.Class)] internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class AliasValueDeserializer : IValueDeserializer { private sealed class AliasState : Dictionary, IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { YamlDotNet.Core.Events.AnchorAlias alias = value.Alias; throw new AnchorNotFoundException(alias.Start, alias.End, $"Anchor '{alias.Value}' not found"); } } } } private sealed class ValuePromise : IValuePromise { private object? value; public readonly YamlDotNet.Core.Events.AnchorAlias? Alias; public bool HasValue { get; private set; } public object? Value { get { if (!HasValue) { throw new InvalidOperationException("Value not set"); } return value; } set { if (HasValue) { throw new InvalidOperationException("Value already set"); } HasValue = true; this.value = value; this.ValueAvailable?.Invoke(value); } } public event Action? ValueAvailable; public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object? value) { HasValue = true; this.value = value; } } private readonly IValueDeserializer innerDeserializer; public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { AliasState aliasState = state.Get(); if (!aliasState.TryGetValue(@event.Value, out ValuePromise value)) { throw new AnchorNotFoundException(@event.Start, @event.End, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } AnchorName anchorName = AnchorName.Empty; if (parser.Accept(out var event2) && !event2.Anchor.IsEmpty) { anchorName = event2.Anchor; AliasState aliasState2 = state.Get(); if (!aliasState2.ContainsKey(anchorName)) { aliasState2[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState3 = state.Get(); if (!aliasState3.TryGetValue(anchorName, out ValuePromise value2)) { aliasState3.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState3[anchorName] = new ValuePromise(obj); } } return obj; } } internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; private readonly ITypeConverter typeConverter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public NodeValueDeserializer(IList deserializers, IList typeResolvers, ITypeConverter typeConverter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); this.typeInspector = typeInspector; } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); ObjectDeserializer rootDeserializer = (Type x) => DeserializeValue(parser, x, state, nestedObjectDeserializer); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out object value, rootDeserializer)) { return typeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "Exception during deserialization", innerException); } throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType) { foreach (INodeTypeResolver typeResolver in typeResolvers) { if (typeResolver.Resolve(nodeEvent, ref currentType)) { break; } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } internal interface ITypeConverter { object? ChangeType(object? value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector); } internal class NullTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return value; } } internal sealed class ObjectAnchorCollection { private readonly Dictionary objectsByAnchor = new Dictionary(); private readonly Dictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out object value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [MaybeNullWhen(false)] out string? anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType, ITypeInspector typeInspector) { return ChangeType(value, expectedType, NullNamingConvention.Instance, typeInspector); } public object? ChangeType(object? value, Type expectedType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return TypeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } internal sealed class SerializerState : IDisposable { private readonly Dictionary items = new Dictionary(); public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out object value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (IPostDeserializationCallback item in items.Values.OfType()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType()) { item.Dispose(); } } } internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { str = char.ToLower(str[0], CultureInfo.InvariantCulture) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } internal static class TypeConverter { public static T ChangeType(object? value, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return (T)ChangeType(value, typeof(T), enumNamingConvention, typeInspector); } public static object? ChangeType(object? value, Type destinationType, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture, enumNamingConvention, typeInspector); } public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider), enumNamingConvention, typeInspector); } public static object? ChangeType(object? value, Type destinationType, CultureInfo culture, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { if (value == null || value.IsDbNull()) { if (!destinationType.IsValueType()) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType()) { Type genericTypeDefinition = destinationType.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>) || FsharpHelper.IsOptionType(genericTypeDefinition)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture, enumNamingConvention, typeInspector); return Activator.CreateInstance(destinationType, obj); } } if (destinationType.IsEnum()) { object result = value; if (value is string value2) { string name = enumNamingConvention.Reverse(value2); name = typeInspector.GetEnumName(destinationType, name); result = Enum.Parse(destinationType, name, ignoreCase: true); } return result; } if (destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; foreach (Type type2 in array) { foreach (MethodInfo publicStaticMethod2 in type2.GetPublicStaticMethods()) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.InnerException; } } } } if (type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.InnerException; } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture, enumNamingConvention, typeInspector), CultureInfo.InvariantCulture); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static void RegisterTypeConverter() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any((TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } internal sealed class TypeConverterCache { private readonly IYamlTypeConverter[] typeConverters; private readonly ConcurrentDictionary cache = new ConcurrentDictionary(); public TypeConverterCache(IEnumerable? typeConverters) : this(typeConverters?.ToArray() ?? Array.Empty()) { } public TypeConverterCache(IYamlTypeConverter[] typeConverters) { this.typeConverters = typeConverters; } public bool TryGetConverterForType(Type type, [NotNullWhen(true)] out IYamlTypeConverter? typeConverter) { (bool, IYamlTypeConverter) orAdd = DictionaryExtensions.GetOrAdd(cache, type, (Type t, IYamlTypeConverter[] tc) => LookupTypeConverter(t, tc), typeConverters); typeConverter = orAdd.Item2; return orAdd.Item1; } public IYamlTypeConverter GetConverterByType(Type converter) { IYamlTypeConverter[] array = typeConverters; foreach (IYamlTypeConverter yamlTypeConverter in array) { if (yamlTypeConverter.GetType() == converter) { return yamlTypeConverter; } } throw new ArgumentException("IYamlTypeConverter of type " + converter.FullName + " not found", "converter"); } private static (bool HasMatch, IYamlTypeConverter? TypeConverter) LookupTypeConverter(Type type, IYamlTypeConverter[] typeConverters) { foreach (IYamlTypeConverter yamlTypeConverter in typeConverters) { if (yamlTypeConverter.Accepts(type)) { return (HasMatch: true, TypeConverter: yamlTypeConverter); } } return (HasMatch: false, TypeConverter: null); } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal class StaticTypeResolver : ITypeResolver { public virtual Type Resolve(Type staticType, object? actualValue) { if (actualValue != null) { if (actualValue.GetType().IsEnum) { return staticType; } switch (actualValue.GetType().GetTypeCode()) { case TypeCode.Boolean: return typeof(bool); case TypeCode.Char: return typeof(char); case TypeCode.SByte: return typeof(sbyte); case TypeCode.Byte: return typeof(byte); case TypeCode.Int16: return typeof(short); case TypeCode.UInt16: return typeof(ushort); case TypeCode.Int32: return typeof(int); case TypeCode.UInt32: return typeof(uint); case TypeCode.Int64: return typeof(long); case TypeCode.UInt64: return typeof(ulong); case TypeCode.Single: return typeof(float); case TypeCode.Double: return typeof(double); case TypeCode.Decimal: return typeof(decimal); case TypeCode.String: return typeof(string); case TypeCode.DateTime: return typeof(DateTime); } } return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { internal class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); private readonly ConcurrentDictionary> enumNameCache = new ConcurrentDictionary>(); private readonly ConcurrentDictionary enumValueCache = new ConcurrentDictionary(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override string GetEnumName(Type enumType, string name) { ConcurrentDictionary orAdd = enumNameCache.GetOrAdd(enumType, (Type _) => new ConcurrentDictionary()); return DictionaryExtensions.GetOrAdd(orAdd, name, delegate(string n, (Type enumType, ITypeInspector innerTypeDescriptor) context) { var (enumType2, typeInspector) = context; return typeInspector.GetEnumName(enumType2, n); }, (enumType, innerTypeDescriptor)); } public override string GetEnumValue(object enumValue) { return DictionaryExtensions.GetOrAdd(enumValueCache, enumValue, delegate(object _, (object enumValue, ITypeInspector innerTypeDescriptor) context) { var (enumValue2, typeInspector) = context; return typeInspector.GetEnumValue(enumValue2); }, (enumValue, innerTypeDescriptor)); } public override IEnumerable GetProperties(Type type, object? container) { return DictionaryExtensions.GetOrAdd(cache, type, delegate(Type t, (object container, ITypeInspector innerTypeDescriptor) context) { var (container2, typeInspector) = context; return typeInspector.GetProperties(t, container2).ToList(); }, (container, innerTypeDescriptor)); } } internal class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable)typeInspectors) { } public CompositeTypeInspector(IEnumerable typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override string GetEnumName(Type enumType, string name) { foreach (ITypeInspector typeInspector in typeInspectors) { try { return typeInspector.GetEnumName(enumType, name); } catch { } } throw new ArgumentOutOfRangeException("enumType,name", "Name not found on enum type"); } public override string GetEnumValue(object enumValue) { if (enumValue == null) { throw new ArgumentNullException("enumValue"); } foreach (ITypeInspector typeInspector in typeInspectors) { try { return typeInspector.GetEnumValue(enumValue); } catch { } } throw new ArgumentOutOfRangeException("enumValue", $"Value not found for ({enumValue})"); } public override IEnumerable GetProperties(Type type, object? container) { return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type, container)); } } internal class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, object? container) { return innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p) { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } internal class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override string GetEnumName(Type enumType, string name) { return innerTypeDescriptor.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return innerTypeDescriptor.GetEnumValue(enumValue); } public override IEnumerable GetProperties(Type type, object? container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } internal class ReadableFieldsTypeInspector : ReflectionTypeInspector { protected class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public bool Required => fieldInfo.IsRequired(); public Type Type => fieldInfo.FieldType; public Type? ConverterType { get; } public Type? TypeOverride { get; set; } public bool AllowNulls => fieldInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; YamlConverterAttribute customAttribute = fieldInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { fieldInfo.SetValue(target, value); } public T? GetCustomAttribute() where T : Attribute { object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(T), inherit: true); return (T)customAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable GetProperties(Type type, object? container) { return type.GetPublicFields().Select((Func)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } internal class ReadablePropertiesTypeInspector : ReflectionTypeInspector { protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public Type? ConverterType { get; set; } public bool AllowNulls => propertyInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; YamlConverterAttribute customAttribute = propertyInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = propertyInfo.GetAllCustomAttributes(); return (T)allCustomAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public ReadablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanRead) { return property.GetGetMethod(nonPublic: true).GetParameters().Length == 0; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class ReflectionTypeInspector : TypeInspectorSkeleton { public override string GetEnumName(Type enumType, string name) { return name; } public override string GetEnumValue(object enumValue) { if (enumValue == null) { return string.Empty; } return enumValue.ToString(); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { public abstract string GetEnumName(Type enumType, string name); public abstract string GetEnumValue(object enumValue); public abstract IEnumerable GetProperties(Type type, object? container); public IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching) { IEnumerable enumerable = ((!caseInsensitivePropertyMatching) ? (from p in GetProperties(type, container) where p.Name == name select p) : (from p in GetProperties(type, container) where p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) select p)); using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } internal class WritablePropertiesTypeInspector : ReflectionTypeInspector { protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public Type? ConverterType { get; set; } public bool AllowNulls => propertyInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; YamlConverterAttribute customAttribute = propertyInfo.GetCustomAttribute(); if (customAttribute != null) { ConverterType = customAttribute.ConverterType; } } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = propertyInfo.GetAllCustomAttributes(); return (T)allCustomAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public WritablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public WritablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanWrite) { return property.GetSetMethod(nonPublic: true).GetParameters().Length == 1; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))) .ToArray(); } } } namespace YamlDotNet.Serialization.Schemas { internal sealed class FailsafeSchema { public static class Tags { public static readonly TagName Map = new TagName("tag:yaml.org,2002:map"); public static readonly TagName Seq = new TagName("tag:yaml.org,2002:seq"); public static readonly TagName Str = new TagName("tag:yaml.org,2002:str"); } } internal sealed class JsonSchema { public static class Tags { public static readonly TagName Null = new TagName("tag:yaml.org,2002:null"); public static readonly TagName Bool = new TagName("tag:yaml.org,2002:bool"); public static readonly TagName Int = new TagName("tag:yaml.org,2002:int"); public static readonly TagName Float = new TagName("tag:yaml.org,2002:float"); } } internal sealed class CoreSchema { public static class Tags { } } internal sealed class DefaultSchema { public static class Tags { public static readonly TagName Timestamp = new TagName("tag:yaml.org,2002:timestamp"); } } } namespace YamlDotNet.Serialization.ObjectGraphVisitors { internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { private class AnchorAssignment { public AnchorName Anchor; } private readonly Dictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value, ObjectSerializer serializer) { if (value.Value != null && assignments.TryGetValue(value.Value, out AnchorAssignment value2)) { if (value2.Anchor.IsEmpty) { value2.Anchor = new AnchorName("o" + nextId.ToString(CultureInfo.InvariantCulture)); nextId++; } return false; } return true; } protected override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, ObjectSerializer serializer) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, ObjectSerializer serializer) { return true; } protected override void VisitScalar(IObjectDescriptor scalar, ObjectSerializer serializer) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, ObjectSerializer serializer) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping, ObjectSerializer serializer) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, ObjectSerializer serializer) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence, ObjectSerializer serializer) { } private void VisitObject(IObjectDescriptor value) { if (value.Value != null) { assignments.Add(value.Value, new AnchorAssignment()); } } AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out AnchorAssignment value)) { return value.Anchor; } return AnchorName.Empty; } } internal sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEventEmitter eventEmitter; private readonly IAliasProvider aliasProvider; private readonly HashSet emittedAliases = new HashSet(); public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) : base(nextVisitor) { this.eventEmitter = eventEmitter; this.aliasProvider = aliasProvider; } public override bool Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (value.Value != null) { AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { AliasEventInfo aliasEventInfo = new AliasEventInfo(value, alias); eventEmitter.Emit(aliasEventInfo, context); return aliasEventInfo.NeedsExpansion; } } return base.Enter(propertyDescriptor, value, context, serializer); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.Enter(propertyDescriptor, value, context, serializer); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitScalar(scalar, context, serializer); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context, serializer); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingEnd(mapping, context, serializer); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceStart(sequence, elementType, context, serializer); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceEnd(sequence, context, serializer); } } internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new YamlDotNet.Core.Events.Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context, serializer); } } internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly TypeConverterCache typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { this.typeConverters = new TypeConverterCache(typeConverters); this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (propertyDescriptor?.ConverterType != null) { IYamlTypeConverter converterByType = typeConverters.GetConverterByType(propertyDescriptor.ConverterType); converterByType.WriteYaml(context, value.Value, value.Type, serializer); return false; } if (typeConverters.TryGetConverterForType(value.Type, out IYamlTypeConverter typeConverter)) { typeConverter.WriteYaml(context, value.Value, value.Type, serializer); return false; } if (value.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(propertyDescriptor, value, context, serializer); } } internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } private static object? GetDefault(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context, serializer); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { DefaultValueAttribute customAttribute = key.GetCustomAttribute(); object objB = ((customAttribute != null) ? customAttribute.Value : GetDefault(key.Type)); if (!object.Equals(value.Value, objB)) { return base.EnterMapping(key, value, context, serializer); } return false; } } internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; private readonly IObjectFactory factory; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor nextVisitor, IObjectFactory factory) : base(nextVisitor) { this.handling = handling; this.factory = factory; } private object? GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { DefaultValuesHandling defaultValuesHandling = handling; YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.IsDefaultValuesHandlingSpecified) { defaultValuesHandling = customAttribute.DefaultValuesHandling; } if ((defaultValuesHandling & DefaultValuesHandling.OmitNull) != DefaultValuesHandling.Preserve && value.Value == null) { return false; } if ((defaultValuesHandling & DefaultValuesHandling.OmitEmptyCollections) != DefaultValuesHandling.Preserve && value.Value is IEnumerable enumerable) { IEnumerator enumerator = enumerable.GetEnumerator(); bool flag = enumerator.MoveNext(); if (enumerator is IDisposable disposable) { disposable.Dispose(); } if (!flag) { return false; } } if ((defaultValuesHandling & DefaultValuesHandling.OmitDefaults) != DefaultValuesHandling.Preserve) { object objB = key.GetCustomAttribute()?.Value ?? GetDefault(key.Type); if (object.Equals(value.Value, objB)) { return false; } } return base.EnterMapping(key, value, context, serializer); } } internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; private readonly TypeConverterCache typeConverterCache; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { typeConverterCache = new TypeConverterCache((IYamlTypeConverter[])(this.typeConverters = typeConverters?.ToArray() ?? Array.Empty())); } bool IObjectGraphVisitor.Enter(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { if (typeConverterCache.TryGetConverterForType(value.Type, out IYamlTypeConverter _)) { return false; } if (value.Value is IYamlConvertible) { return false; } if (value.Value is IYamlSerializable) { return false; } return Enter(value, serializer); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context, ObjectSerializer serializer) { VisitMappingEnd(mapping, serializer); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context, ObjectSerializer serializer) { VisitMappingStart(mapping, keyType, valueType, serializer); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context, ObjectSerializer serializer) { VisitScalar(scalar, serializer); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context, ObjectSerializer serializer) { VisitSequenceEnd(sequence, serializer); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context, ObjectSerializer serializer) { VisitSequenceStart(sequence, elementType, serializer); } protected abstract bool Enter(IObjectDescriptor value, ObjectSerializer serializer); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, ObjectSerializer serializer); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, ObjectSerializer serializer); protected abstract void VisitMappingEnd(IObjectDescriptor mapping, ObjectSerializer serializer); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, ObjectSerializer serializer); protected abstract void VisitScalar(IObjectDescriptor scalar, ObjectSerializer serializer); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence, ObjectSerializer serializer); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, ObjectSerializer serializer); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { protected readonly struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly ITypeResolver typeResolver; private readonly INamingConvention namingConvention; private readonly IObjectFactory objectFactory; public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, IObjectFactory objectFactory) { if (maxRecursion <= 0) { throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1"); } this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.maxRecursion = maxRecursion; this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer) { Traverse(null, "", graph, visitor, context, new Stack(maxRecursion), serializer); } protected virtual void Traverse(IPropertyDescriptor? propertyDescriptor, object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = item.Name?.ToString() ?? string.Empty; num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(propertyDescriptor, value, context, serializer)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = value.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: visitor.VisitScalar(value, context, serializer); return; case TypeCode.Empty: throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } if (value.IsDbNull()) { visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context, serializer); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context, serializer); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); Type type = underlyingType ?? FsharpHelper.GetOptionUnderlyingType(value.Type); object obj = ((type != null) ? FsharpHelper.GetValue(value) : null); if (underlyingType != null) { Traverse(propertyDescriptor, "Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path, serializer); } else if (type != null && obj != null) { Traverse(propertyDescriptor, "Value", new ObjectDescriptor(FsharpHelper.GetValue(value), type, value.Type, value.ScalarStyle), visitor, context, path, serializer); } else { TraverseObject(propertyDescriptor, value, visitor, context, path, serializer); } } finally { path.Pop(); } } protected virtual void TraverseObject(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(propertyDescriptor, value, visitor, typeof(object), typeof(object), context, path, serializer); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(propertyDescriptor, new ObjectDescriptor(dictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path, serializer); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(propertyDescriptor, value, visitor, context, path, serializer); } else { TraverseProperties(value, visitor, context, path, serializer); } } protected virtual void TraverseDictionary(IPropertyDescriptor? propertyDescriptor, IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path, ObjectSerializer serializer) { visitor.VisitMappingStart(dictionary, keyType, valueType, context, serializer); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); ObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); ObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context, serializer)) { Traverse(propertyDescriptor, obj, objectDescriptor, visitor, context, path, serializer); Traverse(propertyDescriptor, obj, objectDescriptor2, visitor, context, path, serializer); } } visitor.VisitMappingEnd(dictionary, context, serializer); } private void TraverseList(IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context, serializer); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(propertyDescriptor, num, GetObjectDescriptor(item, valueType), visitor, context, path, serializer); num++; } visitor.VisitSequenceEnd(value, context, serializer); } protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (context.GetType() != typeof(Nothing)) { objectFactory.ExecuteOnSerializing(value.Value); } visitor.VisitMappingStart(value, typeof(string), typeof(object), context, serializer); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context, serializer)) { Traverse(null, property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string), ScalarStyle.Plain), visitor, context, path, serializer); Traverse(property, property.Name, value2, visitor, context, path, serializer); } } visitor.VisitMappingEnd(value, context, serializer); if (context.GetType() != typeof(Nothing)) { objectFactory.ExecuteOnSerialized(value.Value); } } private ObjectDescriptor GetObjectDescriptor(object? value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly TypeConverterCache converters; private readonly Settings settings; public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, Settings settings, IObjectFactory factory) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention, factory) { this.converters = new TypeConverterCache(converters); this.settings = settings; } protected override void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (!value.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.TryGetConverterForType(value.Type, out IYamlTypeConverter _)) { throw new InvalidOperationException($"Type '{value.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value, visitor, context, path, serializer); } } } namespace YamlDotNet.Serialization.ObjectFactories { internal class DefaultObjectFactory : ObjectFactoryBase { private readonly Dictionary> stateMethods = new Dictionary> { { typeof(YamlDotNet.Serialization.Callbacks.OnDeserializedAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnDeserializingAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnSerializedAttribute), new ConcurrentDictionary() }, { typeof(YamlDotNet.Serialization.Callbacks.OnSerializingAttribute), new ConcurrentDictionary() } }; private readonly Dictionary defaultGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable<>), typeof(List<>) }, { typeof(ICollection<>), typeof(List<>) }, { typeof(IList<>), typeof(List<>) }, { typeof(IDictionary<, >), typeof(Dictionary<, >) } }; private readonly Dictionary defaultNonGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable), typeof(List) }, { typeof(ICollection), typeof(List) }, { typeof(IList), typeof(List) }, { typeof(IDictionary), typeof(Dictionary) } }; private readonly Settings settings; public DefaultObjectFactory() : this(new Dictionary(), new Settings()) { } public DefaultObjectFactory(IDictionary mappings) : this(mappings, new Settings()) { } public DefaultObjectFactory(IDictionary mappings, Settings settings) { foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } defaultNonGenericInterfaceImplementations.Add(mapping.Key, mapping.Value); } this.settings = settings; } public override object Create(Type type) { if (type.IsInterface()) { Type value2; if (type.IsGenericType()) { if (defaultGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out Type value)) { type = value.MakeGenericType(type.GetGenericArguments()); } } else if (defaultNonGenericInterfaceImplementations.TryGetValue(type, out value2)) { type = value2; } } try { return Activator.CreateInstance(type, settings.AllowPrivateConstructors); } catch (Exception innerException) { string message = "Failed to create an instance of type '" + type.FullName + "'."; throw new InvalidOperationException(message, innerException); } } public override void ExecuteOnDeserialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializedAttribute), value); } public override void ExecuteOnDeserializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializingAttribute), value); } public override void ExecuteOnSerialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializedAttribute), value); } public override void ExecuteOnSerializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializingAttribute), value); } private void ExecuteState(Type attributeType, object value) { if (value != null) { Type type = value.GetType(); MethodInfo[] array = GetStateMethods(attributeType, type); MethodInfo[] array2 = array; foreach (MethodInfo methodInfo in array2) { methodInfo.Invoke(value, null); } } } private MethodInfo[] GetStateMethods(Type attributeType, Type valueType) { ConcurrentDictionary concurrentDictionary = stateMethods[attributeType]; return concurrentDictionary.GetOrAdd(valueType, delegate(Type type) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return methods.Where((MethodInfo x) => x.GetCustomAttributes(attributeType, inherit: true).Length != 0).ToArray(); }); } } internal sealed class LambdaObjectFactory : ObjectFactoryBase { private readonly Func factory; public LambdaObjectFactory(Func factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public override object Create(Type type) { return factory(type); } } internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); public virtual object? CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual void ExecuteOnDeserialized(object value) { } public virtual void ExecuteOnDeserializing(object value) { } public virtual void ExecuteOnSerialized(object value) { } public virtual void ExecuteOnSerializing(object value) { } public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { Type implementationOfOpenGenericInterface = descriptor.Type.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); if (implementationOfOpenGenericInterface != null) { genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); object obj = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), descriptor.Value); dictionary = obj as IDictionary; return true; } genericArguments = null; dictionary = null; return false; } public virtual Type GetValueType(Type type) { Type implementationOfOpenGenericInterface = type.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); return (implementationOfOpenGenericInterface != null) ? implementationOfOpenGenericInterface.GetGenericArguments()[0] : typeof(object); } } internal abstract class StaticObjectFactory : IObjectFactory { public abstract object Create(Type type); public abstract Array CreateArray(Type type, int count); public abstract bool IsDictionary(Type type); public abstract bool IsArray(Type type); public abstract bool IsList(Type type); public abstract Type GetKeyType(Type type); public abstract Type GetValueType(Type type); public virtual object? CreatePrimitive(Type type) { return Type.GetTypeCode(type) switch { TypeCode.Boolean => false, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, TypeCode.Int32 => 0, TypeCode.Int64 => 0L, TypeCode.SByte => (sbyte)0, TypeCode.UInt16 => (ushort)0, TypeCode.UInt32 => 0u, TypeCode.UInt64 => 0uL, TypeCode.Single => 0f, TypeCode.Double => 0.0, TypeCode.Decimal => 0m, TypeCode.Char => '\0', TypeCode.DateTime => default(DateTime), _ => null, }; } public bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { dictionary = null; genericArguments = null; return false; } public abstract void ExecuteOnDeserializing(object value); public abstract void ExecuteOnDeserialized(object value); public abstract void ExecuteOnSerializing(object value); public abstract void ExecuteOnSerialized(object value); } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (currentType == typeof(object)) { if (nodeEvent is SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } internal class MappingNodeTypeResolver : INodeTypeResolver { private readonly IDictionary mappings; public MappingNodeTypeResolver(IDictionary mappings) { if (mappings == null) { throw new ArgumentNullException("mappings"); } foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } } this.mappings = mappings; } public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (mappings.TryGetValue(currentType, out Type value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { throw new YamlException(nodeEvent.Start, nodeEvent.End, $"Encountered an unresolved tag '{nodeEvent.Tag}'"); } return false; } } internal sealed class TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary tagMappings; public TagNodeTypeResolver(IDictionary tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out Type value)) { currentType = value; return true; } return false; } } [Obsolete("The mechanism that this class uses to specify type names is non-standard. Register the tags explicitly instead of using this convention.")] internal sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Type type = Type.GetType(nodeEvent.Tag.Value.Substring(1), throwOnError: false); if (type != null) { currentType = type; return true; } } return false; } } internal sealed class YamlConvertibleTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { internal sealed class ArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public ArrayNodeDeserializer(INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!expectedType.IsArray) { value = false; return false; } Type itemType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); Array array = null; CollectionNodeDeserializer.DeserializeHelper(itemType, parser, nestedObjectDeserializer, arrayList, canUpdate: true, enumNamingConvention, typeInspector, PromiseResolvedHandler); array = Array.CreateInstance(itemType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; void PromiseResolvedHandler(int index, object? value2) { if (array == null) { throw new InvalidOperationException("Destination array is still null"); } array.SetValue(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(value2, itemType, enumNamingConvention, typeInspector), index); } } } internal abstract class CollectionDeserializer { protected static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate, IObjectFactory objectFactory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? Mark.Empty, current?.End ?? Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(objectFactory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result[index] = v; }; } else { result.Add(obj); } } } } internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public CollectionNodeDeserializer(IObjectFactory objectFactory, INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { bool canUpdate = true; Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(ICollection<>)); Type type; IList list; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); type = genericArguments[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { Type implementationOfOpenGenericInterface2 = expectedType.GetImplementationOfOpenGenericInterface(typeof(IList<>)); canUpdate = implementationOfOpenGenericInterface2 != null; list = (IList)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(type), value); } } else { if (!typeof(IList).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); value = objectFactory.Create(expectedType); list = (IList)value; } DeserializeHelper(type, parser, nestedObjectDeserializer, list, canUpdate, enumNamingConvention, typeInspector); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate, INamingConvention enumNamingConvention, ITypeInspector typeInspector, Action? promiseResolvedHandler = null) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? Mark.Empty, current?.End ?? Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(tItem.IsValueType() ? Activator.CreateInstance(tItem) : null); if (promiseResolvedHandler != null) { valuePromise.ValueAvailable += delegate(object? v) { promiseResolvedHandler(index, v); }; } else { valuePromise.ValueAvailable += delegate(object? v) { result[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem, enumNamingConvention, typeInspector); }; } } else { result.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem, enumNamingConvention, typeInspector)); } } } } internal abstract class DictionaryDeserializer { private readonly bool duplicateKeyChecking; public DictionaryDeserializer(bool duplicateKeyChecking) { this.duplicateKeyChecking = duplicateKeyChecking; } private void TryAssign(IDictionary result, object key, object value, MappingStart propertyName) { if (duplicateKeyChecking && result.Contains(key)) { throw new YamlException(propertyName.Start, propertyName.End, $"Encountered duplicate key {key}"); } result[key] = value; } protected virtual void Deserialize(Type tKey, Type tValue, IParser parser, Func nestedObjectDeserializer, IDictionary result, ObjectDeserializer rootDeserializer) { MappingStart property = parser.Consume(); MappingEnd @event; while (!parser.TryConsume(out @event)) { object key = nestedObjectDeserializer(parser, tKey); object value = nestedObjectDeserializer(parser, tValue); IValuePromise valuePromise = value as IValuePromise; if (key is IValuePromise valuePromise2) { if (valuePromise == null) { valuePromise2.ValueAvailable += delegate(object? v) { result[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result, key, v, property); } else { value = v; hasFirstPart = true; } }; continue; } if (key == null) { throw new ArgumentException("Empty key names are not supported yet.", "tKey"); } if (valuePromise == null) { TryAssign(result, key, value, property); continue; } valuePromise.ValueAvailable += delegate(object? v) { result[key] = v; }; } } } internal class DictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly IObjectFactory objectFactory; public DictionaryNodeDeserializer(IObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } Deserialize(type, type2, parser, nestedObjectDeserializer, dictionary, rootDeserializer); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); if (implementationOfOpenGenericInterface != expectedType) { value = null; return false; } type = implementationOfOpenGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } internal sealed class FsharpListNodeDeserializer : INodeDeserializer { private readonly ITypeInspector typeInspector; private readonly INamingConvention enumNamingConvention; public FsharpListNodeDeserializer(ITypeInspector typeInspector, INamingConvention enumNamingConvention) { this.typeInspector = typeInspector; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!FsharpHelper.IsFsharpListType(expectedType)) { value = false; return false; } Type type = expectedType.GetGenericArguments()[0]; Type t = expectedType.GetGenericTypeDefinition().MakeGenericType(type); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(type, parser, nestedObjectDeserializer, arrayList, canUpdate: true, enumNamingConvention, typeInspector); Array array = Array.CreateInstance(type, arrayList.Count); arrayList.CopyTo(array, 0); object obj = FsharpHelper.CreateFsharpListFromArray(t, type, array); value = obj; return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } private static bool NodeIsNull(NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is YamlDotNet.Core.Events.Scalar { Style: ScalarStyle.Plain, IsKey: false } scalar) { string value = scalar.Value; switch (value) { default: return value == "NULL"; case "": case "~": case "null": case "Null": return true; } } return false; } } internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly ITypeInspector typeInspector; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; private readonly INamingConvention enumNamingConvention; private readonly bool enforceNullability; private readonly bool caseInsensitivePropertyMatching; private readonly bool enforceRequiredProperties; private readonly TypeConverterCache typeConverters; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeInspector, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter, INamingConvention enumNamingConvention, bool enforceNullability, bool caseInsensitivePropertyMatching, bool enforceRequiredProperties, IEnumerable typeConverters) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeInspector = typeInspector ?? throw new ArgumentNullException("typeInspector"); this.ignoreUnmatched = ignoreUnmatched; this.duplicateKeyChecking = duplicateKeyChecking; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); this.enforceNullability = enforceNullability; this.caseInsensitivePropertyMatching = caseInsensitivePropertyMatching; this.enforceRequiredProperties = enforceRequiredProperties; this.typeConverters = new TypeConverterCache(typeConverters); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? FsharpHelper.GetOptionUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); objectFactory.ExecuteOnDeserializing(value); HashSet hashSet = new HashSet(StringComparer.Ordinal); HashSet hashSet2 = new HashSet(StringComparer.Ordinal); Mark start = Mark.Empty; MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar propertyName = parser.Consume(); if (duplicateKeyChecking && !hashSet.Add(propertyName.Value)) { throw new YamlException(propertyName.Start, propertyName.End, "Encountered duplicate key " + propertyName.Value); } try { IPropertyDescriptor property = typeInspector.GetProperty(type, null, propertyName.Value, ignoreUnmatched, caseInsensitivePropertyMatching); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } hashSet2.Add(property.Name); object obj; if (property.ConverterType != null) { IYamlTypeConverter converterByType = typeConverters.GetConverterByType(property.ConverterType); obj = converterByType.ReadYaml(parser, property.Type, rootDeserializer); } else { obj = nestedObjectDeserializer(parser, property.Type); } if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += delegate(object? v) { object value3 = typeConverter.ChangeType(v, property.Type, enumNamingConvention, typeInspector); NullCheck(value3, property, propertyName); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type, enumNamingConvention, typeInspector); NullCheck(value2, property, propertyName); property.Write(value, value2); } } catch (SerializationException ex) { throw new YamlException(propertyName.Start, propertyName.End, ex.Message); } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(propertyName.Start, propertyName.End, "Exception during deserialization", innerException); } start = propertyName.End; } if (enforceRequiredProperties) { IEnumerable properties = typeInspector.GetProperties(type, value); List list = new List(); foreach (IPropertyDescriptor item in properties) { if (item.Required && !hashSet2.Contains(item.Name)) { list.Add(item.Name); } } if (list.Count > 0) { string text = string.Join(",", list); throw new YamlException(in start, in start, "Missing properties, '" + text + "' in source yaml."); } } objectFactory.ExecuteOnDeserialized(value); return true; } public void NullCheck(object value, IPropertyDescriptor property, YamlDotNet.Core.Events.Scalar propertyName) { if (enforceNullability && value == null && !property.AllowNulls) { throw new YamlException(propertyName.Start, propertyName.End, "Strict nullability enforcement error.", new NullReferenceException("Yaml value is null when target property requires non null values.")); } } } internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; private readonly bool attemptUnknownTypeDeserialization; private readonly ITypeConverter typeConverter; private readonly ITypeInspector typeInspector; private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter, ITypeInspector typeInspector, YamlFormatter formatter, INamingConvention enumNamingConvention) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.typeInspector = typeInspector; this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? FsharpHelper.GetOptionUnderlyingType(expectedType) ?? expectedType; if (type.IsEnum()) { string name = enumNamingConvention.Reverse(@event.Value); name = typeInspector.GetEnumName(type, name); value = Enum.Parse(type, name, ignoreCase: true); return true; } TypeCode typeCode = type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { if (!@event.IsKey && attemptUnknownTypeDeserialization) { value = AttemptUnknownTypeDeserialization(@event); } else { value = @event.Value; } } else { value = typeConverter.ChangeType(@event.Value, expectedType, enumNamingConvention, typeInspector); } break; } return true; } private static bool DeserializeBooleanHelper(string value) { if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { return true; } if (Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { return false; } throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } private object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; int i = 0; bool flag = false; ulong num = 0uL; if (value[0] == '-') { i++; flag = true; } else if (value[0] == '+') { i++; } if (value[i] == '0') { int num2; if (i == value.Length - 1) { num2 = 10; num = 0uL; } else { i++; if (value[i] == 'b') { num2 = 2; i++; } else if (value[i] == 'x') { num2 = 16; i++; } else { num2 = 8; } } for (; i < value.Length; i++) { if (value[i] != '_') { builder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(builder.ToString(), num2); break; case 16: num = ulong.Parse(builder.ToString(), NumberStyles.HexNumber, formatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", ""), CultureInfo.InvariantCulture); } } if (!flag) { return CastInteger(num, typeCode); } long number = ((num != 9223372036854775808uL) ? checked(-(long)num) : long.MinValue); return CastInteger(number, typeCode); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private static object CastInteger(long number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => (ulong)number, _ => number, }); } private static object CastInteger(ulong number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => (long)number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => number, _ => number, }); } private object? AttemptUnknownTypeDeserialization(YamlDotNet.Core.Events.Scalar value) { if (value.Style == ScalarStyle.SingleQuoted || value.Style == ScalarStyle.DoubleQuoted || value.Style == ScalarStyle.Folded) { return value.Value; } string v = value.Value; switch (v) { case "null": case "Null": case "NULL": case "~": case "": return null; case "true": case "True": case "TRUE": return true; case "False": case "FALSE": case "false": return false; default: if (Regex.IsMatch(v, "^0x[0-9a-fA-F]+$")) { v = v.Substring(2); if (byte.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result)) { return result; } if (short.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result2)) { return result2; } if (int.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result3)) { return result3; } if (long.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result4)) { return result4; } if (ulong.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result5)) { return result5; } return v; } if (Regex.IsMatch(v, "^0o[0-9a-fA-F]+$")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out object value2) && !TryAndSwallow(() => Convert.ToInt16(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 8), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 8), out value2)) { return v; } return value2; } if (Regex.IsMatch(v, "^[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$")) { if (byte.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result6)) { return result6; } if (short.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result7)) { return result7; } if (int.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result8)) { return result8; } if (long.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result9)) { return result9; } if (ulong.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result10)) { return result10; } if (float.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result11)) { return result11; } if (double.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result12)) { return result12; } return v; } if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (Polyfills.StartsWith(v, '-')) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } } private static bool TryAndSwallow(Func attempt, out object? value) { try { value = attempt(); return true; } catch { value = null; return false; } } } internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly StaticObjectFactory factory; public StaticArrayNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!factory.IsArray(expectedType)) { value = false; return false; } Type valueType = factory.GetValueType(expectedType); ArrayList arrayList = new ArrayList(); StaticCollectionNodeDeserializer.DeserializeHelper(valueType, parser, nestedObjectDeserializer, arrayList, factory); Array array = factory.CreateArray(expectedType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal sealed class StaticCollectionNodeDeserializer : INodeDeserializer { private readonly StaticObjectFactory factory; public StaticCollectionNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!factory.IsList(expectedType)) { value = null; return false; } DeserializeHelper(result: (IList)(value = factory.Create(expectedType) as IList), tItem: factory.GetValueType(expectedType), parser: parser, nestedObjectDeserializer: nestedObjectDeserializer, factory: factory); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, IObjectFactory factory) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result[index] = v; }; } else { result.Add(obj); } } } } internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (objectFactory.IsDictionary(expectedType)) { if (!(objectFactory.Create(expectedType) is IDictionary dictionary)) { value = null; return false; } Type keyType = objectFactory.GetKeyType(expectedType); Type valueType = objectFactory.GetValueType(expectedType); value = dictionary; base.Deserialize(keyType, valueType, reader, nestedObjectDeserializer, dictionary, rootDeserializer); return true; } value = null; return false; } } internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly TypeConverterCache converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = new TypeConverterCache(converters); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!converters.TryGetConverterForType(expectedType, out IYamlTypeConverter typeConverter)) { value = null; return false; } value = typeConverter.ReadYaml(parser, expectedType, rootDeserializer); return true; } } internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser, expectedType, (Type type) => nestedObjectDeserializer(parser, type)); value = yamlConvertible; return true; } value = null; return false; } } internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (typeof(IYamlSerializable).IsAssignableFrom(expectedType)) { IYamlSerializable yamlSerializable = (IYamlSerializable)objectFactory.Create(expectedType); yamlSerializable.ReadYaml(parser); value = yamlSerializable; return true; } value = null; return false; } } } namespace YamlDotNet.Serialization.NamingConventions { internal sealed class CamelCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase(); } public string Reverse(string value) { return value.ToPascalCase(); } } internal sealed class HyphenatedNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("-"); } public string Reverse(string value) { return value.ToPascalCase(); } } internal sealed class LowerCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase().ToLower(CultureInfo.InvariantCulture); } public string Reverse(string value) { if (string.IsNullOrEmpty(value)) { return value; } return char.ToUpperInvariant(value[0]) + value.Substring(1); } } internal sealed class NullNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } public string Apply(string value) { return value; } public string Reverse(string value) { return value; } } internal sealed class PascalCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } public string Apply(string value) { return value.ToPascalCase(); } public string Reverse(string value) { return value.ToPascalCase(); } } internal sealed class UnderscoredNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("_"); } public string Reverse(string value) { return value.ToPascalCase(); } } } namespace YamlDotNet.Serialization.EventEmitters { internal abstract class ChainedEventEmitter : IEventEmitter { protected readonly IEventEmitter nextEmitter; protected ChainedEventEmitter(IEventEmitter nextEmitter) { this.nextEmitter = nextEmitter ?? throw new ArgumentNullException("nextEmitter"); } public virtual void Emit(AliasEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } } internal sealed class JsonEventEmitter : ChainedEventEmitter { private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public JsonEventEmitter(IEventEmitter nextEmitter, YamlFormatter formatter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) : base(nextEmitter) { this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) { eventInfo.NeedsExpansion = true; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { eventInfo.IsPlainImplicit = true; eventInfo.Style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.RenderedValue = "null"; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.RenderedValue = formatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum()) { eventInfo.RenderedValue = formatter.FormatEnum(value, typeInspector, enumNamingConvention); eventInfo.Style = ((!formatter.PotentiallyQuoteEnums(value)) ? ScalarStyle.Plain : ScalarStyle.DoubleQuoted); } else { eventInfo.RenderedValue = formatter.FormatNumber(value); } break; case TypeCode.Single: { float f = (float)value; eventInfo.RenderedValue = f.ToString("G", CultureInfo.InvariantCulture); if (float.IsNaN(f) || float.IsInfinity(f)) { eventInfo.Style = ScalarStyle.DoubleQuoted; } break; } case TypeCode.Double: { double d = (double)value; eventInfo.RenderedValue = d.ToString("G", CultureInfo.InvariantCulture); if (double.IsNaN(d) || double.IsInfinity(d)) { eventInfo.Style = ScalarStyle.DoubleQuoted; } break; } case TypeCode.Decimal: eventInfo.RenderedValue = ((decimal)value).ToString(CultureInfo.InvariantCulture); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = formatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = formatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; private readonly Regex? isSpecialStringValue_Regex; private static readonly string SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\\.inf|\\.Inf|\\.INF)|\\.nan|\\.NaN|\\.NAN|\\s.*)$"; private static readonly string CombinedYaml1_1SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?0b[0-1_]+|[-+]?0o?[0-7_]+|[-+]?(0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(:[0-5]?[0-9])+|[-+]?([0-9][0-9_]*)?\\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(inf|Inf|INF)|\\.(nan|NaN|NAN))$"; private readonly ScalarStyle defaultScalarStyle; private readonly YamlFormatter formatter; private readonly INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, IDictionary tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings, ScalarStyle defaultScalarStyle, YamlFormatter formatter, INamingConvention enumNamingConvention, ITypeInspector typeInspector) : base(nextEmitter) { this.defaultScalarStyle = defaultScalarStyle; this.formatter = formatter; this.tagMappings = tagMappings; this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(quoteYaml1_1Strings ? CombinedYaml1_1SpecialStrings_Pattern : SpecialStrings_Pattern, RegexOptions.Compiled); this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { ScalarStyle style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = JsonSchema.Tags.Bool; eventInfo.RenderedValue = formatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum) { eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = formatter.FormatEnum(value, typeInspector, enumNamingConvention); style = ((!quoteNecessaryStrings || !IsSpecialStringValue(eventInfo.RenderedValue) || !formatter.PotentiallyQuoteEnums(value)) ? defaultScalarStyle : ScalarStyle.DoubleQuoted); } else { eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = formatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((!quoteNecessaryStrings || !IsSpecialStringValue(eventInfo.RenderedValue)) ? defaultScalarStyle : ScalarStyle.DoubleQuoted); break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = formatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = formatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } eventInfo.IsPlainImplicit = true; if (eventInfo.Style == ScalarStyle.Any) { eventInfo.Style = style; } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } private void AssignTypeIfNeeded(ObjectEventInfo eventInfo) { if (tagMappings.TryGetValue(eventInfo.Source.Type, out var value)) { eventInfo.Tag = value; } } private bool IsSpecialStringValue(string value) { if (value.Trim() == string.Empty) { return true; } return isSpecialStringValue_Regex?.IsMatch(value) ?? false; } } internal sealed class WriterEventEmitter : IEventEmitter { void IEventEmitter.Emit(AliasEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(eventInfo.Alias)); } void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); } void IEventEmitter.Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingEnd()); } void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceEnd()); } } } namespace YamlDotNet.Serialization.Converters { internal class DateTime8601Converter : IYamlTypeConverter { private readonly ScalarStyle scalarStyle; public DateTime8601Converter() : this(ScalarStyle.Any) { } public DateTime8601Converter(ScalarStyle scalarStyle) { this.scalarStyle = scalarStyle; } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTime dateTime = DateTime.ParseExact(value, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); return dateTime; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { string value2 = ((DateTime)value).ToString("O", CultureInfo.InvariantCulture); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, scalarStyle, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class DateTimeConverter : IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly bool doubleQuotes; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, IFormatProvider? provider = null, bool doubleQuotes = false, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.doubleQuotes = doubleQuotes; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTimeStyles style = ((kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal); DateTime dt = DateTime.ParseExact(value, formats, provider, style); dt = EnsureDateTimeKind(dt, kind); return dt; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, doubleQuotes ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } private static DateTime EnsureDateTimeKind(DateTime dt, DateTimeKind kind) { if (dt.Kind == DateTimeKind.Local && kind == DateTimeKind.Utc) { return dt.ToUniversalTime(); } if (dt.Kind == DateTimeKind.Utc && kind == DateTimeKind.Local) { return dt.ToLocalTime(); } return dt; } } internal class DateTimeOffsetConverter : IYamlTypeConverter { private readonly IFormatProvider provider; private readonly ScalarStyle style; private readonly DateTimeStyles dateStyle; private readonly string[] formats; public DateTimeOffsetConverter(IFormatProvider? provider = null, ScalarStyle style = ScalarStyle.Any, DateTimeStyles dateStyle = DateTimeStyles.None, params string[] formats) { this.provider = provider ?? CultureInfo.InvariantCulture; this.style = style; this.dateStyle = dateStyle; this.formats = formats.DefaultIfEmpty("O").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTimeOffset); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; DateTimeOffset dateTimeOffset = DateTimeOffset.ParseExact(value, formats, provider, dateStyle); return dateTimeOffset; } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { string value2 = ((DateTimeOffset)value).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, style, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; return new Guid(value); } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { Guid guid = (Guid)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume().Value; return Type.GetType(value, throwOnError: true); } public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer) { Type type2 = (Type)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, type2.AssemblyQualifiedName, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } } namespace YamlDotNet.Serialization.Callbacks { [AttributeUsage(AttributeTargets.Method)] internal sealed class OnDeserializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnDeserializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnSerializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] internal sealed class OnSerializingAttribute : Attribute { } } namespace YamlDotNet.Serialization.BufferedDeserialization { internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : IParser { private readonly LinkedList buffer; private LinkedListNode? current; public ParsingEvent? Current => current?.Value; public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength) { buffer = new LinkedList(); buffer.AddLast(parserToBuffer.Consume()); int num = 0; do { ParsingEvent parsingEvent = parserToBuffer.Consume(); num += parsingEvent.NestingIncrease; buffer.AddLast(parsingEvent); if (maxDepth > -1 && num > maxDepth) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max depth"); } if (maxLength > -1 && buffer.Count > maxLength) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max length"); } } while (num >= 0); current = buffer.First; } public bool MoveNext() { current = current?.Next; return current != null; } public void Reset() { current = buffer.First; } } internal class TypeDiscriminatingNodeDeserializer : INodeDeserializer { private readonly IList innerDeserializers; private readonly IList typeDiscriminators; private readonly int maxDepthToBuffer; private readonly int maxLengthToBuffer; public TypeDiscriminatingNodeDeserializer(IList innerDeserializers, IList typeDiscriminators, int maxDepthToBuffer, int maxLengthToBuffer) { this.innerDeserializers = innerDeserializers; this.typeDiscriminators = typeDiscriminators; this.maxDepthToBuffer = maxDepthToBuffer; this.maxLengthToBuffer = maxLengthToBuffer; } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value, ObjectDeserializer rootDeserializer) { if (!reader.Accept(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where((ITypeDiscriminator t) => t.BaseType.IsAssignableFrom(expectedType)); if (!enumerable.Any()) { value = null; return false; } Mark start = reader.Current.Start; Type expectedType2 = expectedType; ParserBuffer parserBuffer; try { parserBuffer = new ParserBuffer(reader, maxDepthToBuffer, maxLengthToBuffer); } catch (Exception innerException) { throw new YamlException(in start, reader.Current.End, "Failed to buffer yaml node", innerException); } try { foreach (ITypeDiscriminator item in enumerable) { parserBuffer.Reset(); if (item.TryDiscriminate(parserBuffer, out Type suggestedType)) { expectedType2 = suggestedType; break; } } } catch (Exception innerException2) { throw new YamlException(in start, reader.Current.End, "Failed to discriminate type", innerException2); } parserBuffer.Reset(); foreach (INodeDeserializer innerDeserializer in innerDeserializers) { if (innerDeserializer.Deserialize(parserBuffer, expectedType2, nestedObjectDeserializer, out value, rootDeserializer)) { return true; } } value = null; return false; } } internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(IParser buffer, out Type? suggestedType); } internal class KeyValueTypeDiscriminator : ITypeDiscriminator { private readonly string targetKey; private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public KeyValueTypeDiscriminator(Type baseType, string targetKey, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.targetKey = targetKey; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar2) => targetKey == scalar2.Value, out YamlDotNet.Core.Events.Scalar _, out ParsingEvent value) && value is YamlDotNet.Core.Events.Scalar scalar && typeMapping.TryGetValue(scalar.Value, out Type value2)) { suggestedType = value2; return true; } suggestedType = null; return false; } } internal class UniqueKeyTypeDiscriminator : ITypeDiscriminator { private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public UniqueKeyTypeDiscriminator(Type baseType, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => typeMapping.ContainsKey(scalar.Value), out YamlDotNet.Core.Events.Scalar key, out ParsingEvent _)) { suggestedType = typeMapping[key.Value]; return true; } suggestedType = null; return false; } } } namespace YamlDotNet.RepresentationModel { internal class DocumentLoadingState { private readonly Dictionary anchors = new Dictionary(); private readonly List nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } anchors[node.Anchor] = node; } public YamlNode GetNode(AnchorName anchor, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out YamlNode value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } public bool TryGetNode(AnchorName anchor, [NotNullWhen(true)] out YamlNode? node) { return anchors.TryGetValue(anchor, out node); } public void AddNodeWithUnresolvedAliases(YamlNode node) { nodesWithUnresolvedAliases.Add(node); } public void ResolveAliases() { foreach (YamlNode nodesWithUnresolvedAlias in nodesWithUnresolvedAliases) { nodesWithUnresolvedAlias.ResolveAliases(this); } } } internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } internal interface IYamlVisitor { void Visit(YamlStream stream); void Visit(YamlDocument document); void Visit(YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(YamlMappingNode mapping); } internal class LibYamlEventStream { private readonly IParser parser; public LibYamlEventStream(IParser iParser) { parser = iParser ?? throw new ArgumentNullException("iParser"); } public void WriteTo(TextWriter textWriter) { while (parser.MoveNext()) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.AnchorAlias anchorAlias)) { if (!(current is YamlDotNet.Core.Events.DocumentEnd documentEnd)) { if (!(current is YamlDotNet.Core.Events.DocumentStart documentStart)) { if (!(current is MappingEnd)) { if (!(current is MappingStart nodeEvent)) { if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (!(current is SequenceEnd)) { if (!(current is SequenceStart nodeEvent2)) { if (!(current is YamlDotNet.Core.Events.StreamEnd)) { if (current is YamlDotNet.Core.Events.StreamStart) { textWriter.Write("+STR"); } } else { textWriter.Write("-STR"); } } else { textWriter.Write("+SEQ"); WriteAnchorAndTag(textWriter, nodeEvent2); } } else { textWriter.Write("-SEQ"); } } else { textWriter.Write("=VAL"); WriteAnchorAndTag(textWriter, scalar); switch (scalar.Style) { case ScalarStyle.DoubleQuoted: textWriter.Write(" \""); break; case ScalarStyle.SingleQuoted: textWriter.Write(" '"); break; case ScalarStyle.Folded: textWriter.Write(" >"); break; case ScalarStyle.Literal: textWriter.Write(" |"); break; default: textWriter.Write(" :"); break; } string value = scalar.Value; foreach (char c in value) { switch (c) { case '\b': textWriter.Write("\\b"); break; case '\t': textWriter.Write("\\t"); break; case '\n': textWriter.Write("\\n"); break; case '\r': textWriter.Write("\\r"); break; case '\\': textWriter.Write("\\\\"); break; default: textWriter.Write(c); break; } } } } else { textWriter.Write("+MAP"); WriteAnchorAndTag(textWriter, nodeEvent); } } else { textWriter.Write("-MAP"); } } else { textWriter.Write("+DOC"); if (!documentStart.IsImplicit) { textWriter.Write(" ---"); } } } else { textWriter.Write("-DOC"); if (!documentEnd.IsImplicit) { textWriter.Write(" ..."); } } } else { textWriter.Write("=ALI *"); textWriter.Write(anchorAlias.Value); } textWriter.WriteLine(); } } private static void WriteAnchorAndTag(TextWriter textWriter, NodeEvent nodeEvent) { if (!nodeEvent.Anchor.IsEmpty) { textWriter.Write(" &"); textWriter.Write(nodeEvent.Anchor); } if (!nodeEvent.Tag.IsEmpty) { textWriter.Write(" <"); textWriter.Write(nodeEvent.Tag.Value); textWriter.Write(">"); } } } internal class YamlAliasNode : YamlNode { public override YamlNodeType NodeType => YamlNodeType.Alias; internal YamlAliasNode(AnchorName anchor) { base.Anchor = anchor; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); } public override void Accept(IYamlVisitor visitor) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); } public override bool Equals(object? obj) { if (obj is YamlAliasNode yamlAliasNode && Equals(yamlAliasNode)) { return object.Equals(base.Anchor, yamlAliasNode.Anchor); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal override string ToString(RecursionLevel level) { return "*" + base.Anchor; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } } internal class YamlDocument { private class AnchorAssigningVisitor : YamlVisitorBase { private readonly HashSet existingAnchors = new HashSet(); private readonly Dictionary visitedNodes = new Dictionary(); public void AssignAnchors(YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (KeyValuePair visitedNode in visitedNodes) { if (!visitedNode.Value) { continue; } AnchorName anchorName; if (!visitedNode.Key.Anchor.IsEmpty && !existingAnchors.Contains(visitedNode.Key.Anchor)) { anchorName = visitedNode.Key.Anchor; } else { do { anchorName = new AnchorName(random.Next().ToString(CultureInfo.InvariantCulture)); } while (existingAnchors.Contains(anchorName)); } existingAnchors.Add(anchorName); visitedNode.Key.Anchor = anchorName; } } private bool VisitNodeAndFindDuplicates(YamlNode node) { if (visitedNodes.TryGetValue(node, out var value)) { if (!value) { visitedNodes[node] = true; } return !value; } visitedNodes.Add(node, value: false); return false; } public override void Visit(YamlScalarNode scalar) { VisitNodeAndFindDuplicates(scalar); } public override void Visit(YamlMappingNode mapping) { if (!VisitNodeAndFindDuplicates(mapping)) { base.Visit(mapping); } } public override void Visit(YamlSequenceNode sequence) { if (!VisitNodeAndFindDuplicates(sequence)) { base.Visit(sequence); } } } public YamlNode RootNode { get; private set; } public IEnumerable AllNodes => RootNode.AllNodes; public YamlDocument(YamlNode rootNode) { RootNode = rootNode; } public YamlDocument(string rootNode) { RootNode = new YamlScalarNode(rootNode); } internal YamlDocument(IParser parser) { DocumentLoadingState documentLoadingState = new DocumentLoadingState(); parser.Consume(); YamlDotNet.Core.Events.DocumentEnd @event; while (!parser.TryConsume(out @event)) { RootNode = YamlNode.ParseNode(parser, documentLoadingState); if (RootNode is YamlAliasNode) { throw new YamlException("A document cannot contain only an alias"); } } documentLoadingState.ResolveAliases(); if (RootNode == null) { throw new ArgumentException("Atempted to parse an empty document"); } } private void AssignAnchors() { AnchorAssigningVisitor anchorAssigningVisitor = new AnchorAssigningVisitor(); anchorAssigningVisitor.AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: false)); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } } internal sealed class YamlMappingNode : YamlNode, IEnumerable>, IEnumerable, IYamlConvertible { private readonly OrderedDictionary children = new OrderedDictionary(); public IOrderedDictionary Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { MappingStart mappingStart = parser.Consume(); Load(mappingStart, state); Style = mappingStart.Style; bool flag = false; MappingEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); YamlNode yamlNode2 = YamlNode.ParseNode(parser, state); if (!children.TryAdd(yamlNode, yamlNode2)) { throw new YamlException(yamlNode.Start, yamlNode.End, $"Duplicate key {yamlNode}"); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode(params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode(IEnumerable> children) { foreach (KeyValuePair child in children) { this.children.Add(child); } } public YamlMappingNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlMappingNode(IEnumerable children) { using IEnumerator enumerator = children.GetEnumerator(); while (enumerator.MoveNext()) { YamlNode current = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(current, enumerator.Current); } } public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } internal override void ResolveAliases(DocumentLoadingState state) { Dictionary dictionary = null; Dictionary dictionary2 = null; foreach (KeyValuePair child in children) { if (child.Key is YamlAliasNode) { if (dictionary == null) { dictionary = new Dictionary(); } dictionary.Add(child.Key, state.GetNode(child.Key.Anchor, child.Key.Start, child.Key.End)); } if (child.Value is YamlAliasNode) { if (dictionary2 == null) { dictionary2 = new Dictionary(); } dictionary2.Add(child.Key, state.GetNode(child.Value.Anchor, child.Value.Start, child.Value.End)); } } if (dictionary2 != null) { foreach (KeyValuePair item in dictionary2) { children[item.Key] = item.Value; } } if (dictionary == null) { return; } foreach (KeyValuePair item2 in dictionary) { YamlNode value = children[item2.Key]; children.Remove(item2.Key); children.Add(item2.Value, value); } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(base.Anchor, base.Tag, isImplicit: true, Style)); foreach (KeyValuePair child in children) { child.Key.Save(emitter, state); child.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlMappingNode yamlMappingNode) || !object.Equals(base.Tag, yamlMappingNode.Tag) || children.Count != yamlMappingNode.children.Count) { return false; } foreach (KeyValuePair child in children) { if (!yamlMappingNode.children.TryGetValue(child.Key, out YamlNode value) || !object.Equals(child.Value, value)) { return false; } } return true; } public override int GetHashCode() { int num = base.GetHashCode(); foreach (KeyValuePair child in children) { num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Key); num = (child.Value.Anchor.IsEmpty ? YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value) : YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value.Anchor)); } return num; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair child in children) { foreach (YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("{ "); foreach (KeyValuePair child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } builder.Append(" }"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } public IEnumerator> GetEnumerator() { return children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } public static YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } YamlMappingNode yamlMappingNode = new YamlMappingNode(); foreach (PropertyInfo publicProperty in mapping.GetType().GetPublicProperties()) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); YamlNode yamlNode = value as YamlNode; if (yamlNode == null) { string text = Convert.ToString(value, CultureInfo.InvariantCulture); yamlNode = text ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } internal abstract class YamlNode { private const int MaximumRecursionLevel = 1000; internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; public AnchorName Anchor { get; set; } public TagName Tag { get; set; } public Mark Start { get; private set; } = Mark.Empty; public Mark End { get; private set; } = Mark.Empty; public IEnumerable AllNodes { get { RecursionLevel level = new RecursionLevel(1000); return SafeAllNodes(level); } } public abstract YamlNodeType NodeType { get; } public YamlNode this[int index] { get { if (!(this is YamlSequenceNode yamlSequenceNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {index}. Only Sequences can be indexed by number."); } return yamlSequenceNode.Children[index]; } } public YamlNode this[YamlNode key] { get { if (!(this is YamlMappingNode yamlMappingNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {key}. Only Mappings can be indexed by key."); } return yamlMappingNode.Children[key]; } } internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) { Tag = yamlEvent.Tag; if (!yamlEvent.Anchor.IsEmpty) { Anchor = yamlEvent.Anchor; state.AddAnchor(this); } Start = yamlEvent.Start; End = yamlEvent.End; } internal static YamlNode ParseNode(IParser parser, DocumentLoadingState state) { if (parser.Accept(out var _)) { return new YamlScalarNode(parser, state); } if (parser.Accept(out var _)) { return new YamlSequenceNode(parser, state); } if (parser.Accept(out var _)) { return new YamlMappingNode(parser, state); } if (parser.TryConsume(out var event4)) { if (!state.TryGetNode(event4.Value, out YamlNode node)) { return new YamlAliasNode(event4.Value); } return node; } throw new ArgumentException("The current event is of an unsupported type.", "parser"); } internal abstract void ResolveAliases(DocumentLoadingState state); internal void Save(IEmitter emitter, EmitterState state) { if (!Anchor.IsEmpty && !state.EmittedAnchors.Add(Anchor)) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(Anchor)); } else { Emit(emitter, state); } } internal abstract void Emit(IEmitter emitter, EmitterState state); public abstract void Accept(IYamlVisitor visitor); public override string ToString() { RecursionLevel recursionLevel = new RecursionLevel(1000); return ToString(recursionLevel); } internal abstract string ToString(RecursionLevel level); internal abstract IEnumerable SafeAllNodes(RecursionLevel level); public static implicit operator YamlNode(string value) { return new YamlScalarNode(value); } public static implicit operator YamlNode(string[] sequence) { return new YamlSequenceNode(((IEnumerable)sequence).Select((Func)((string i) => i))); } public static explicit operator string?(YamlNode node) { if (!(node is YamlScalarNode yamlScalarNode)) { throw new ArgumentException($"Attempted to convert a '{node.NodeType}' to string. This conversion is valid only for Scalars."); } return yamlScalarNode.Value; } } internal sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer { public bool Equals([AllowNull] YamlNode x, [AllowNull] YamlNode y) { return x == y; } public int GetHashCode(YamlNode obj) { return obj.GetHashCode(); } } internal enum YamlNodeType { Alias, Mapping, Scalar, Sequence } [DebuggerDisplay("{Value}")] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { private bool forceImplicitPlain; private string? value; public string? Value { get { return value; } set { if (value == null) { forceImplicitPlain = true; } else { forceImplicitPlain = false; } this.value = value; } } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); string text = scalar.Value; if (scalar.Style == ScalarStyle.Plain && base.Tag.IsEmpty) { forceImplicitPlain = text.Length switch { 0 => true, 1 => text == "~", 4 => text == "null" || text == "Null" || text == "NULL", _ => false, }; } value = text; Style = scalar.Style; } public YamlScalarNode() { } public YamlScalarNode(string? value) { Value = value; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { TagName tag = base.Tag; bool isPlainImplicit = tag.IsEmpty; if (forceImplicitPlain && Style == ScalarStyle.Plain && (Value == null || Value == "")) { tag = JsonSchema.Tags.Null; isPlainImplicit = true; } else if (tag.IsEmpty && Value == null && (Style == ScalarStyle.Plain || Style == ScalarStyle.Any)) { tag = JsonSchema.Tags.Null; isPlainImplicit = true; } emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, tag, Value ?? string.Empty, Style, isPlainImplicit, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (obj is YamlScalarNode yamlScalarNode && object.Equals(base.Tag, yamlScalarNode.Tag)) { return object.Equals(Value, yamlScalarNode.Value); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(base.Tag.GetHashCode(), Value); } public static explicit operator string?(YamlScalarNode value) { return value.Value; } internal override string ToString(RecursionLevel level) { return Value ?? string.Empty; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } [DebuggerDisplay("Count = {children.Count}")] internal sealed class YamlSequenceNode : YamlNode, IEnumerable, IEnumerable, IYamlConvertible { private readonly List children = new List(); public IList Children => children; public SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { SequenceStart sequenceStart = parser.Consume(); Load(sequenceStart, state); Style = sequenceStart.Style; bool flag = false; SequenceEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); children.Add(yamlNode); flag = flag || yamlNode is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlSequenceNode(IEnumerable children) { foreach (YamlNode child in children) { this.children.Add(child); } } public void Add(YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new YamlScalarNode(child)); } internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlSequenceNode yamlSequenceNode) || !object.Equals(base.Tag, yamlSequenceNode.Tag) || children.Count != yamlSequenceNode.children.Count) { return false; } for (int i = 0; i < children.Count; i++) { if (!object.Equals(children[i], yamlSequenceNode.children[i])) { return false; } } return true; } public override int GetHashCode() { int h = 0; foreach (YamlNode child in children) { h = YamlDotNet.Core.HashCode.CombineHashCodes(h, child); } return YamlDotNet.Core.HashCode.CombineHashCodes(h, base.Tag); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (YamlNode child in children) { foreach (YamlNode item in child.SafeAllNodes(level)) { yield return item; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("[ "); foreach (YamlNode child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append(child.ToString(level)); } builder.Append(" ]"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } public IEnumerator GetEnumerator() { return Children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } internal class YamlStream : IEnumerable, IEnumerable { private readonly List documents = new List(); public IList Documents => documents; public YamlStream() { } public YamlStream(params YamlDocument[] documents) : this((IEnumerable)documents) { } public YamlStream(IEnumerable documents) { foreach (YamlDocument document in documents) { this.documents.Add(document); } } public void Add(YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(IParser parser) { documents.Clear(); parser.Consume(); YamlDotNet.Core.Events.StreamEnd @event; while (!parser.TryConsume(out @event)) { YamlDocument item = new YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); foreach (YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Obsolete("Use YamlVisitorBase")] internal abstract class YamlVisitor : IYamlVisitor { protected virtual void Visit(YamlStream stream) { } protected virtual void Visited(YamlStream stream) { } protected virtual void Visit(YamlDocument document) { } protected virtual void Visited(YamlDocument document) { } protected virtual void Visit(YamlScalarNode scalar) { } protected virtual void Visited(YamlScalarNode scalar) { } protected virtual void Visit(YamlSequenceNode sequence) { } protected virtual void Visited(YamlSequenceNode sequence) { } protected virtual void Visit(YamlMappingNode mapping) { } protected virtual void Visited(YamlMappingNode mapping) { } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { child.Key.Accept(this); child.Value.Accept(this); } } void IYamlVisitor.Visit(YamlStream stream) { Visit(stream); VisitChildren(stream); Visited(stream); } void IYamlVisitor.Visit(YamlDocument document) { Visit(document); VisitChildren(document); Visited(document); } void IYamlVisitor.Visit(YamlScalarNode scalar) { Visit(scalar); Visited(scalar); } void IYamlVisitor.Visit(YamlSequenceNode sequence) { Visit(sequence); VisitChildren(sequence); Visited(sequence); } void IYamlVisitor.Visit(YamlMappingNode mapping) { Visit(mapping); VisitChildren(mapping); Visited(mapping); } } internal abstract class YamlVisitorBase : IYamlVisitor { public virtual void Visit(YamlStream stream) { VisitChildren(stream); } public virtual void Visit(YamlDocument document) { VisitChildren(document); } public virtual void Visit(YamlScalarNode scalar) { } public virtual void Visit(YamlSequenceNode sequence) { VisitChildren(sequence); } public virtual void Visit(YamlMappingNode mapping) { VisitChildren(mapping); } protected virtual void VisitPair(YamlNode key, YamlNode value) { key.Accept(this); value.Accept(this); } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { VisitPair(child.Key, child.Value); } } } } namespace YamlDotNet.Helpers { internal class DefaultFsharpHelper : IFsharpHelper { private static bool IsFsharpCore(Type t) { return t.Namespace == "Microsoft.FSharp.Core"; } public bool IsOptionType(Type t) { if (IsFsharpCore(t)) { return t.Name == "FSharpOption`1"; } return false; } public Type? GetOptionUnderlyingType(Type t) { if (!t.IsGenericType || !IsOptionType(t)) { return null; } return t.GenericTypeArguments[0]; } public object? GetValue(IObjectDescriptor objectDescriptor) { if (!IsOptionType(objectDescriptor.Type)) { throw new InvalidOperationException("Should not be called on non-Option<> type"); } if (objectDescriptor.Value == null) { return null; } return objectDescriptor.Type.GetProperty("Value").GetValue(objectDescriptor.Value); } public bool IsFsharpListType(Type t) { if (t.Namespace == "Microsoft.FSharp.Collections") { return t.Name == "FSharpList`1"; } return false; } public object? CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { if (!IsFsharpListType(t)) { return null; } return t.Assembly.GetType("Microsoft.FSharp.Collections.ListModule").GetMethod("OfArray").MakeGenericMethod(itemsType) .Invoke(null, new object[1] { arr }); } } internal static class DictionaryExtensions { public static bool TryAdd(this Dictionary dictionary, T key, V value) { if (dictionary.ContainsKey(key)) { return false; } dictionary.Add(key, value); return true; } public static TValue GetOrAdd(this ConcurrentDictionary dictionary, TKey key, Func valueFactory, TArg arg) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } if (key == null) { throw new ArgumentNullException("key"); } if (valueFactory == null) { throw new ArgumentNullException("valueFactory"); } TValue value; do { if (dictionary.TryGetValue(key, out value)) { return value; } value = valueFactory(key, arg); } while (!dictionary.TryAdd(key, value)); return value; } } internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { PropertyInfo propertyInfo = TryGetMemberExpression(propertyAccessor); if (propertyInfo == null) { throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } return propertyInfo; } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression(LambdaExpression lambdaExpression) where TMemberInfo : MemberInfo { if (lambdaExpression.Parameters.Count != 1) { return null; } Expression expression = lambdaExpression.Body; if (expression is UnaryExpression unaryExpression) { if (unaryExpression.NodeType != ExpressionType.Convert) { return null; } expression = unaryExpression.Operand; } if (expression is MemberExpression memberExpression) { if (memberExpression.Expression != lambdaExpression.Parameters[0]) { return null; } return memberExpression.Member as TMemberInfo; } return null; } } internal static class FsharpHelper { public static IFsharpHelper? Instance { get; set; } public static bool IsOptionType(Type t) { return Instance?.IsOptionType(t) ?? false; } public static Type? GetOptionUnderlyingType(Type t) { return Instance?.GetOptionUnderlyingType(t); } public static object? GetValue(IObjectDescriptor objectDescriptor) { return Instance?.GetValue(objectDescriptor); } public static bool IsFsharpListType(Type t) { return Instance?.IsFsharpListType(t) ?? false; } public static object? CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return Instance?.CreateFsharpListFromArray(t, itemsType, arr); } } internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { private readonly ICollection genericCollection; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public object? this[int index] { get { throw new NotSupportedException(); } set { ((IList)genericCollection)[index] = (T)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericCollectionToNonGenericAdapter(ICollection genericCollection) { this.genericCollection = genericCollection ?? throw new ArgumentNullException("genericCollection"); } public int Add(object? value) { int count = genericCollection.Count; genericCollection.Add((T)value); return count; } public void Clear() { genericCollection.Clear(); } public bool Contains(object? value) { throw new NotSupportedException(); } public int IndexOf(object? value) { throw new NotSupportedException(); } public void Insert(int index, object? value) { throw new NotSupportedException(); } public void Remove(object? value) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } internal sealed class GenericDictionaryToNonGenericAdapter : IDictionary, ICollection, IEnumerable where TKey : notnull { private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; public object? Value => enumerator.Current.Value; public object Current => Entry; public DictionaryEnumerator(IEnumerator> enumerator) { this.enumerator = enumerator; } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } private readonly IDictionary genericDictionary; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public ICollection Keys { get { throw new NotSupportedException(); } } public ICollection Values { get { throw new NotSupportedException(); } } public object? this[object key] { get { throw new NotSupportedException(); } set { genericDictionary[(TKey)key] = (TValue)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericDictionaryToNonGenericAdapter(IDictionary genericDictionary) { this.genericDictionary = genericDictionary ?? throw new ArgumentNullException("genericDictionary"); } public void Add(object key, object? value) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(object key) { throw new NotSupportedException(); } public IDictionaryEnumerator GetEnumerator() { return new DictionaryEnumerator(genericDictionary.GetEnumerator()); } public void Remove(object key) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IFsharpHelper { bool IsOptionType(Type t); Type? GetOptionUnderlyingType(Type t); object? GetValue(IObjectDescriptor objectDescriptor); bool IsFsharpListType(Type t); object? CreateFsharpListFromArray(Type t, Type itemsType, Array arr); } internal interface IOrderedDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { KeyValuePair this[int index] { get; set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } internal class NullFsharpHelper : IFsharpHelper { public object? CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return null; } public Type? GetOptionUnderlyingType(Type t) { return null; } public object? GetValue(IObjectDescriptor objectDescriptor) { return null; } public bool IsFsharpListType(Type t) { return false; } public bool IsOptionType(Type t) { return false; } } internal static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] internal sealed class OrderedDictionary : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { private class KeyCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TKey item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TKey item) { return orderedDictionary.dictionary.ContainsKey(item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class ValueCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TValue item) { return orderedDictionary.dictionary.ContainsValue(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { if (dictionary.ContainsKey(key)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); dictionary[key] = value; list[index] = new KeyValuePair(key, value); } else { Add(key, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; public KeyValuePair this[int index] { get { return list[index]; } set { list[index] = value; } } public OrderedDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public OrderedDictionary(IEqualityComparer comparer) { list = new List>(); dictionary = new Dictionary(comparer); this.comparer = comparer; } public void Add(KeyValuePair item) { if (!TryAdd(item)) { ThrowDuplicateKeyException(item.Key); } } public void Add(TKey key, TValue value) { if (!TryAdd(key, value)) { ThrowDuplicateKeyException(key); } } private static void ThrowDuplicateKeyException(TKey key) { throw new ArgumentException($"An item with the same key {key} has already been added."); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { if (DictionaryExtensions.TryAdd(dictionary, key, value)) { list.Add(new KeyValuePair(key, value)); return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd(KeyValuePair item) { if (DictionaryExtensions.TryAdd(dictionary, item.Key, item.Value)) { list.Add(item); return true; } return false; } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains(KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public IEnumerator> GetEnumerator() { return list.GetEnumerator(); } public void Insert(int index, TKey key, TValue value) { dictionary.Add(key, value); list.Insert(index, new KeyValuePair(key, value)); } public bool Remove(TKey key) { if (dictionary.ContainsKey(key)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); list.RemoveAt(index); if (!dictionary.Remove(key)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove(KeyValuePair item) { return Remove(item.Key); } public void RemoveAt(int index) { TKey key = list[index].Key; dictionary.Remove(key); list.RemoveAt(index); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return dictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } [System.Runtime.Serialization.OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { dictionary = new Dictionary(); foreach (KeyValuePair item in list) { dictionary[item.Key] = item.Value; } } } internal static class ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionary(this Dictionary dictionary) where TKey : notnull { return dictionary; } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } } namespace YamlDotNet.Core { internal readonly struct AnchorName : IEquatable { public static readonly AnchorName Empty; private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of an empty anchor"); public bool IsEmpty => value == null; public AnchorName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (!AnchorPattern.IsMatch(value)) { throw new ArgumentException("Anchor cannot be empty or contain disallowed characters: []{},\nThe value was '" + value + "'.", "value"); } } public override string ToString() { return value ?? "[empty]"; } public bool Equals(AnchorName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is AnchorName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(AnchorName left, AnchorName right) { return left.Equals(right); } public static bool operator !=(AnchorName left, AnchorName right) { return !(left == right); } public static implicit operator AnchorName(string? value) { if (value != null) { return new AnchorName(value); } return Empty; } } internal class AnchorNotFoundException : YamlException { public AnchorNotFoundException(string message) : base(message) { } public AnchorNotFoundException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } [DebuggerStepThrough] internal readonly struct CharacterAnalyzer where TBuffer : ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { if (buffer == null) { throw new ArgumentNullException("buffer"); } Buffer = buffer; } public char Peek(int offset) { return Buffer.Peek(offset); } public void Skip(int length) { Buffer.Skip(length); } public bool IsAlphaNumericDashOrUnderscore(int offset = 0) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && c != '_') { return c == '-'; } return true; } public bool IsAscii(int offset = 0) { return Buffer.Peek(offset) <= '\u007f'; } public bool IsPrintable(int offset = 0) { char c = Buffer.Peek(offset); switch (c) { default: if (c != '\u0085' && (c < '\u00a0' || c > '\ud7ff')) { if (c >= '\ue000') { return c <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } public bool IsDigit(int offset = 0) { char c = Buffer.Peek(offset); if (c >= '0') { return c <= '9'; } return false; } public int AsDigit(int offset = 0) { return Buffer.Peek(offset) - 48; } public bool IsHex(int offset) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } public int AsHex(int offset) { char c = Buffer.Peek(offset); if (c <= '9') { return c - 48; } if (c <= 'F') { return c - 65 + 10; } return c - 97 + 10; } public bool IsSpace(int offset = 0) { return Check(' ', offset); } public bool IsZero(int offset = 0) { return Check('\0', offset); } public bool IsTab(int offset = 0) { return Check('\t', offset); } public bool IsWhite(int offset = 0) { if (!IsSpace(offset)) { return IsTab(offset); } return true; } public bool IsBreak(int offset = 0) { return Check("\r\n\u0085\u2028\u2029", offset); } public bool IsCrLf(int offset = 0) { if (Check('\r', offset)) { return Check('\n', offset + 1); } return false; } public bool IsBreakOrZero(int offset = 0) { if (!IsBreak(offset)) { return IsZero(offset); } return true; } public bool IsWhiteBreakOrZero(int offset = 0) { if (!IsWhite(offset)) { return IsBreakOrZero(offset); } return true; } public bool Check(char expected, int offset = 0) { return Buffer.Peek(offset) == expected; } public bool Check(string expectedCharacters, int offset = 0) { char c = Buffer.Peek(offset); return Polyfills.Contains(expectedCharacters, c); } } internal static class Constants { public static readonly TagDirective[] DefaultTagDirectives = new TagDirective[2] { new TagDirective("!", "!"), new TagDirective("!!", "tag:yaml.org,2002:") }; public const int MajorVersion = 1; public const int MinorVersion = 3; } [DebuggerStepThrough] internal sealed class Cursor { public long Index { get; private set; } public long Line { get; private set; } public long LineOffset { get; private set; } public Cursor() { Line = 1L; } public Cursor(Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public Mark Mark() { return new Mark(Index, Line, LineOffset + 1); } public void Skip() { Index++; LineOffset++; } public void SkipLineByOffset(int offset) { Index += offset; Line++; LineOffset = 0L; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0L) { Line++; LineOffset = 0L; } } } internal class Emitter : IEmitter { private class AnchorData { public AnchorName Anchor; public bool IsAlias; } private class TagData { public string? Handle; public string? Suffix; } private class ScalarData { public string Value = string.Empty; public bool IsMultiline; public bool IsFlowPlainAllowed; public bool IsBlockPlainAllowed; public bool IsSingleQuotedAllowed; public bool IsBlockAllowed; public bool HasSingleQuotes; public ScalarStyle Style; } private static readonly Regex UriReplacer = new Regex("[^0-9A-Za-z_\\-;?@=$~\\\\\\)\\]/:&+,\\.\\*\\(\\[!]", RegexOptions.Compiled | RegexOptions.Singleline); private static readonly string[] NewLineSeparators = new string[3] { "\r\n", "\r", "\n" }; private readonly TextWriter output; private readonly bool outputUsesUnicodeEncoding; private readonly int maxSimpleKeyLength; private readonly bool isCanonical; private readonly bool skipAnchorName; private readonly int bestIndent; private readonly int bestWidth; private EmitterState state; private readonly Stack states = new Stack(); private readonly Queue events = new Queue(); private readonly Stack indents = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private int indent; private int flowLevel; private bool isMappingContext; private bool isSimpleKeyContext; private int column; private bool isWhitespace; private bool isIndentation; private readonly bool forceIndentLess; private readonly bool useUtf16SurrogatePair; private bool isDocumentEndWritten; private readonly AnchorData anchorData = new AnchorData(); private readonly TagData tagData = new TagData(); private readonly ScalarData scalarData = new ScalarData(); public Emitter(TextWriter output) : this(output, EmitterSettings.Default) { } public Emitter(TextWriter output, int bestIndent) : this(output, bestIndent, int.MaxValue) { } public Emitter(TextWriter output, int bestIndent, int bestWidth) : this(output, bestIndent, bestWidth, isCanonical: false) { } public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : this(output, new EmitterSettings(bestIndent, bestWidth, isCanonical, 1024)) { } public Emitter(TextWriter output, EmitterSettings settings) { bestIndent = settings.BestIndent; bestWidth = settings.BestWidth; isCanonical = settings.IsCanonical; maxSimpleKeyLength = settings.MaxSimpleKeyLength; skipAnchorName = settings.SkipAnchorName; forceIndentLess = !settings.IndentSequences; useUtf16SurrogatePair = settings.UseUtf16SurrogatePairs; this.output = output; this.output.NewLine = settings.NewLine; outputUsesUnicodeEncoding = IsUnicode(output.Encoding); } public void Emit(ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { ParsingEvent evt = events.Peek(); try { AnalyzeEvent(evt); StateMachine(evt); } finally { events.Dequeue(); } } } private bool NeedMoreEvents() { if (events.Count == 0) { return true; } int num; switch (events.Peek().Type) { case EventType.DocumentStart: num = 1; break; case EventType.SequenceStart: num = 2; break; case EventType.MappingStart: num = 3; break; default: return false; } if (events.Count > num) { return false; } int num2 = 0; foreach (ParsingEvent @event in events) { switch (@event.Type) { case EventType.DocumentStart: case EventType.SequenceStart: case EventType.MappingStart: num2++; break; case EventType.DocumentEnd: case EventType.SequenceEnd: case EventType.MappingEnd: num2--; break; } if (num2 == 0) { return false; } } return true; } private void AnalyzeEvent(ParsingEvent evt) { anchorData.Anchor = AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { AnalyzeAnchor(anchorAlias.Value, isAlias: true); } else if (evt is NodeEvent nodeEvent) { if (evt is YamlDotNet.Core.Events.Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(nodeEvent.Anchor, isAlias: false); if (!nodeEvent.Tag.IsEmpty && (isCanonical || nodeEvent.IsCanonical)) { AnalyzeTag(nodeEvent.Tag); } } } private void AnalyzeAnchor(AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(YamlDotNet.Core.Events.Scalar scalar) { string value = scalar.Value; scalarData.Value = value; if (value.Length == 0) { if (scalar.Tag == "tag:yaml.org,2002:null") { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = false; scalarData.IsBlockAllowed = false; } else { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = false; } return; } bool flag = false; bool flag2 = false; if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) { flag = true; flag2 = true; } StringLookAheadBufferPool.BufferWrapper bufferWrapper = StringLookAheadBufferPool.Rent(value); try { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(bufferWrapper.Buffer); bool flag3 = true; bool flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; bool flag10 = false; bool flag11 = false; bool flag12 = false; bool flag13 = false; bool flag14 = false; bool flag15 = false; bool flag16 = !ValueIsRepresentableInOutputEncoding(value); bool flag17 = false; bool flag18 = false; bool flag19 = true; while (!characterAnalyzer.EndOfInput) { if (flag19) { if (characterAnalyzer.Check("#,[]{}&*!|>\"%@`'")) { flag = true; flag2 = true; flag9 = characterAnalyzer.Check('\''); flag17 |= characterAnalyzer.Check('\''); } if (characterAnalyzer.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (characterAnalyzer.Check(",?[]{}")) { flag = true; } if (characterAnalyzer.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= characterAnalyzer.Check('\''); } if (!flag16 && !characterAnalyzer.IsPrintable()) { flag16 = true; } if (characterAnalyzer.IsBreak()) { flag15 = true; } if (characterAnalyzer.IsSpace()) { if (flag19) { flag5 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (characterAnalyzer.IsBreak()) { if (flag19) { flag6 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag8 = true; } if (flag12) { flag11 = true; } if (flag14) { flag18 = true; } flag12 = false; flag13 = true; } else { flag12 = false; flag13 = false; flag14 = false; } flag3 = characterAnalyzer.IsWhiteBreakOrZero(); characterAnalyzer.Skip(1); if (!characterAnalyzer.EndOfInput) { flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); } flag19 = false; } scalarData.IsFlowPlainAllowed = true; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = true; if (flag5 || flag6 || flag7 || flag8 || flag9) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag7) { scalarData.IsBlockAllowed = false; } if (flag10) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag11 || flag16) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag18) { scalarData.IsBlockAllowed = false; } scalarData.IsMultiline = flag15; if (flag15) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag) { scalarData.IsFlowPlainAllowed = false; } if (flag2) { scalarData.IsBlockPlainAllowed = false; } scalarData.HasSingleQuotes = flag17; } finally { ((IDisposable)bufferWrapper/*cast due to .constrained prefix*/).Dispose(); } } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); string text = output.Encoding.GetString(bytes, 0, bytes.Length); return text.Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private static bool IsUnicode(Encoding encoding) { if (!(encoding is UTF8Encoding) && !(encoding is UnicodeEncoding)) { return encoding is UTF7Encoding; } return true; } private void AnalyzeTag(TagName tag) { tagData.Handle = tag.Value; foreach (TagDirective tagDirective in tagDirectives) { if (tag.Value.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) { tagData.Handle = tagDirective.Handle; tagData.Suffix = tag.Value.Substring(tagDirective.Prefix.Length); break; } } } private void StateMachine(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.Comment comment) { EmitComment(comment); return; } switch (state) { case EmitterState.StreamStart: EmitStreamStart(evt); break; case EmitterState.FirstDocumentStart: EmitDocumentStart(evt, isFirst: true); break; case EmitterState.DocumentStart: EmitDocumentStart(evt, isFirst: false); break; case EmitterState.DocumentContent: EmitDocumentContent(evt); break; case EmitterState.DocumentEnd: EmitDocumentEnd(evt); break; case EmitterState.FlowSequenceFirstItem: EmitFlowSequenceItem(evt, isFirst: true); break; case EmitterState.FlowSequenceItem: EmitFlowSequenceItem(evt, isFirst: false); break; case EmitterState.FlowMappingFirstKey: EmitFlowMappingKey(evt, isFirst: true); break; case EmitterState.FlowMappingKey: EmitFlowMappingKey(evt, isFirst: false); break; case EmitterState.FlowMappingSimpleValue: EmitFlowMappingValue(evt, isSimple: true); break; case EmitterState.FlowMappingValue: EmitFlowMappingValue(evt, isSimple: false); break; case EmitterState.BlockSequenceFirstItem: EmitBlockSequenceItem(evt, isFirst: true); break; case EmitterState.BlockSequenceItem: EmitBlockSequenceItem(evt, isFirst: false); break; case EmitterState.BlockMappingFirstKey: EmitBlockMappingKey(evt, isFirst: true); break; case EmitterState.BlockMappingKey: EmitBlockMappingKey(evt, isFirst: false); break; case EmitterState.BlockMappingSimpleValue: EmitBlockMappingValue(evt, isSimple: true); break; case EmitterState.BlockMappingValue: EmitBlockMappingValue(evt, isSimple: false); break; case EmitterState.StreamEnd: throw new YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(YamlDotNet.Core.Events.Comment comment) { if (flowLevel > 0 || state == EmitterState.FlowMappingFirstKey || state == EmitterState.FlowSequenceFirstItem) { return; } string[] array = comment.Value.Split(NewLineSeparators, StringSplitOptions.None); if (comment.IsInline) { Write(" # "); Write(string.Join(" ", array)); } else { bool flag = state == EmitterState.BlockMappingFirstKey; if (flag) { IncreaseIndent(isFlow: false, isIndentless: false); } string[] array2 = array; foreach (string value in array2) { WriteIndent(); Write("# "); Write(value); WriteBreak(); } if (flag) { indent = indents.Pop(); } } isIndentation = true; } private void EmitStreamStart(ParsingEvent evt) { if (!(evt is YamlDotNet.Core.Events.StreamStart)) { throw new ArgumentException("Expected STREAM-START.", "evt"); } indent = -1; column = 0; isWhitespace = true; isIndentation = true; state = EmitterState.FirstDocumentStart; } private void EmitDocumentStart(ParsingEvent evt, bool isFirst) { if (evt is YamlDotNet.Core.Events.DocumentStart documentStart) { bool flag = documentStart.IsImplicit && isFirst && !isCanonical; TagDirectiveCollection tagDirectiveCollection = NonDefaultTagsAmong(documentStart.Tags); if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || tagDirectiveCollection.Count > 0)) { isDocumentEndWritten = false; WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } if (documentStart.Version != null) { AnalyzeVersionDirective(documentStart.Version); Version version = documentStart.Version.Version; flag = false; WriteIndicator("%YAML", needWhitespace: true, whitespace: false, indentation: false); WriteIndicator(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor), needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } foreach (TagDirective item in tagDirectiveCollection) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective value in defaultTagDirectives) { AppendTagDirectiveTo(value, allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; TagDirective[] defaultTagDirectives2 = Constants.DefaultTagDirectives; foreach (TagDirective value2 in defaultTagDirectives2) { AppendTagDirectiveTo(value2, allowDuplicates: true, tagDirectiveCollection); } foreach (TagDirective item2 in tagDirectiveCollection) { WriteIndicator("%TAG", needWhitespace: true, whitespace: false, indentation: false); WriteTagHandle(item2.Handle); WriteTagContent(item2.Prefix, needsWhitespace: true); WriteIndent(); } } if (CheckEmptyDocument()) { flag = false; } if (!flag) { WriteIndent(); WriteIndicator("---", needWhitespace: true, whitespace: false, indentation: false); if (isCanonical) { WriteIndent(); } } state = EmitterState.DocumentContent; } else { if (!(evt is YamlDotNet.Core.Events.StreamEnd)) { throw new YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private static TagDirectiveCollection NonDefaultTagsAmong(IEnumerable? tagCollection) { TagDirectiveCollection tagDirectiveCollection = new TagDirectiveCollection(); if (tagCollection == null) { return tagDirectiveCollection; } foreach (TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, tagDirectiveCollection); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective item in defaultTagDirectives) { tagDirectiveCollection.Remove(item); } return tagDirectiveCollection; } private static void AnalyzeVersionDirective(VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(ParsingEvent evt, bool isMapping, bool isSimpleKey) { isMappingContext = isMapping; isSimpleKeyContext = isSimpleKey; switch (evt.Type) { case EventType.Alias: EmitAlias(); break; case EventType.Scalar: EmitScalar(evt); break; case EventType.SequenceStart: EmitSequenceStart(evt); break; case EventType.MappingStart: EmitMappingStart(evt); break; default: throw new YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(ParsingEvent evt) { YamlDotNet.Core.Events.Scalar scalar = (YamlDotNet.Core.Events.Scalar)evt; ScalarStyle scalarStyle = scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) { throw new YamlException("Neither tag nor isImplicit flags are specified."); } if (scalarStyle == ScalarStyle.Any) { scalarStyle = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { scalarStyle = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { scalarStyle = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.SingleQuoted; } if (flag && !scalar.IsPlainImplicit) { scalarStyle = ScalarStyle.SingleQuoted; } } if (scalarStyle == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { scalarStyle = ScalarStyle.DoubleQuoted; } if ((scalarStyle == ScalarStyle.Literal || scalarStyle == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.ForcePlain) { scalarStyle = ScalarStyle.Plain; } scalarData.Style = scalarStyle; } private void ProcessScalar() { switch (scalarData.Style) { case ScalarStyle.Plain: WritePlainScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.SingleQuoted: WriteSingleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.DoubleQuoted: WriteDoubleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.Literal: WriteLiteralScalar(scalarData.Value); break; case ScalarStyle.Folded: WriteFoldedScalar(scalarData.Value); break; default: throw new InvalidOperationException(); } } private void WritePlainScalar(string value, bool allowBreaks) { if (!isWhitespace) { Write(' '); } bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsSpace(c)) { if (allowBreaks && !flag && column > bestWidth && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } Write(c); isIndentation = false; flag = false; flag2 = false; } isWhitespace = false; isIndentation = false; } private void WriteSingleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("'", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == ' ') { if (allowBreaks && !flag && column > bestWidth && i != 0 && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } if (c == '\'') { Write(c); } Write(c); isIndentation = false; flag = false; flag2 = false; } WriteIndicator("'", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteDoubleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("\"", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsPrintable(c) && !IsBreak(c, out var _)) { switch (c) { case '"': case '\\': break; case ' ': if (allowBreaks && !flag && column > bestWidth && i > 0 && i + 1 < value.Length) { WriteIndent(); if (value[i + 1] == ' ') { Write('\\'); } } else { Write(c); } flag = true; continue; default: Write(c); flag = false; continue; } } Write('\\'); switch (c) { case '\0': Write('0'); break; case '\a': Write('a'); break; case '\b': Write('b'); break; case '\t': Write('t'); break; case '\n': Write('n'); break; case '\v': Write('v'); break; case '\f': Write('f'); break; case '\r': Write('r'); break; case '\u001b': Write('e'); break; case '"': Write('"'); break; case '\\': Write('\\'); break; case '\u0085': Write('N'); break; case '\u00a0': Write('_'); break; case '\u2028': Write('L'); break; case '\u2029': Write('P'); break; default: { ushort num = c; if (num <= 255) { Write('x'); Write(num.ToString("X02", CultureInfo.InvariantCulture)); } else if (IsHighSurrogate(c)) { if (i + 1 >= value.Length || !IsLowSurrogate(value[i + 1])) { throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); } if (useUtf16SurrogatePair) { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); Write('\\'); Write('u'); Write(((ushort)value[i + 1]).ToString("X04", CultureInfo.InvariantCulture)); } else { Write('U'); Write(char.ConvertToUtf32(c, value[i + 1]).ToString("X08", CultureInfo.InvariantCulture)); } i++; } else { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); } break; } } flag = false; } WriteIndicator("\"", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteLiteralScalar(string value) { bool flag = true; WriteIndicator("|", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (IsBreak(c, out var breakChar)) { WriteBreak(breakChar); isIndentation = true; flag = true; continue; } if (flag) { WriteIndent(); } Write(c); isIndentation = false; flag = false; } } private void WriteFoldedScalar(string value) { bool flag = true; bool flag2 = true; WriteIndicator(">", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsBreak(c, out var breakChar)) { if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (!flag && !flag2 && breakChar == '\n') { int j; char breakChar2; for (j = 0; i + j < value.Length && IsBreak(value[i + j], out breakChar2); j++) { } if (i + j < value.Length && !IsBlank(value[i + j]) && !IsBreak(value[i + j], out breakChar2)) { WriteBreak(); } } WriteBreak(breakChar); isIndentation = true; flag = true; } else { if (flag) { WriteIndent(); flag2 = IsBlank(c); } if (!flag && c == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) { WriteIndent(); } else { Write(c); } isIndentation = false; flag = false; } } } private static bool IsSpace(char character) { return character == ' '; } private static bool IsBreak(char character, out char breakChar) { switch (character) { case '\n': case '\r': case '\u0085': breakChar = '\n'; return true; case '\u2028': case '\u2029': breakChar = character; return true; default: breakChar = '\0'; return false; } } private static bool IsBlank(char character) { if (character != ' ') { return character == '\t'; } return true; } private static bool IsPrintable(char character) { switch (character) { default: if (character != '\u0085' && (character < '\u00a0' || character > '\ud7ff')) { if (character >= '\ue000') { return character <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } private static bool IsHighSurrogate(char c) { if ('\ud800' <= c) { return c <= '\udbff'; } return false; } private static bool IsLowSurrogate(char c) { if ('\udc00' <= c) { return c <= '\udfff'; } return false; } private void EmitSequenceStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) { state = EmitterState.FlowMappingFirstKey; } else { state = EmitterState.BlockMappingFirstKey; } } private void ProcessAnchor() { if (!anchorData.Anchor.IsEmpty && !skipAnchorName) { WriteIndicator(anchorData.IsAlias ? "*" : "&", needWhitespace: true, whitespace: false, indentation: false); WriteAnchor(anchorData.Anchor); } } private void ProcessTag() { if (tagData.Handle == null && tagData.Suffix == null) { return; } if (tagData.Handle != null) { WriteTagHandle(tagData.Handle); if (tagData.Suffix != null) { WriteTagContent(tagData.Suffix, needsWhitespace: false); } } else { WriteIndicator("!<", needWhitespace: true, whitespace: false, indentation: false); WriteTagContent(tagData.Suffix, needsWhitespace: false); WriteIndicator(">", needWhitespace: false, whitespace: false, indentation: false); } } private void EmitDocumentEnd(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.DocumentEnd documentEnd) { WriteIndent(); if (!documentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is SequenceEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("]", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); } else { if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } states.Push(EmitterState.FlowSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } } private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is MappingEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("}", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); return; } if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } if (!isCanonical && CheckSimpleKey()) { states.Push(EmitterState.FlowMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: false); states.Push(EmitterState.FlowMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { if (isCanonical || column > bestWidth) { WriteIndent(); } WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: false); } states.Push(EmitterState.FlowMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is SequenceEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); WriteIndicator("-", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is MappingEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); if (CheckSimpleKey()) { states.Push(EmitterState.BlockMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) { if (!isSimple) { WriteIndent(); WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: true); } states.Push(EmitterState.BlockMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void IncreaseIndent(bool isFlow, bool isIndentless) { indents.Push(indent); if (indent < 0) { indent = (isFlow ? bestIndent : 0); } else if (!isIndentless || !forceIndentLess) { indent += bestIndent; } } private bool CheckEmptyDocument() { int num = 0; foreach (ParsingEvent @event in events) { num++; if (num == 2) { if (@event is YamlDotNet.Core.Events.Scalar scalar) { return string.IsNullOrEmpty(scalar.Value); } break; } } return false; } private bool CheckSimpleKey() { if (events.Count < 1) { return false; } int num; switch (events.Peek().Type) { case EventType.Alias: num = AnchorNameLength(anchorData.Anchor); break; case EventType.Scalar: if (scalarData.IsMultiline) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix) + SafeStringLength(scalarData.Value); break; case EventType.SequenceStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; case EventType.MappingStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; default: return false; } return num <= maxSimpleKeyLength; } private static int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } private static int SafeStringLength(string? value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } private bool CheckEmptyStructure() where TStart : NodeEvent where TEnd : ParsingEvent { if (events.Count < 2) { return false; } using Queue.Enumerator enumerator = events.GetEnumerator(); return enumerator.MoveNext() && enumerator.Current is TStart && enumerator.MoveNext() && enumerator.Current is TEnd; } private void WriteBlockScalarHints(string value) { StringLookAheadBufferPool.BufferWrapper bufferWrapper = StringLookAheadBufferPool.Rent(value); try { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(bufferWrapper.Buffer); if (characterAnalyzer.IsSpace() || characterAnalyzer.IsBreak()) { int num = bestIndent; string indicator = num.ToString(CultureInfo.InvariantCulture); WriteIndicator(indicator, needWhitespace: false, whitespace: false, indentation: false); } string text = null; if (value.Length == 0 || !characterAnalyzer.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && characterAnalyzer.IsBreak(value.Length - 2)) { text = "+"; } if (text != null) { WriteIndicator(text, needWhitespace: false, whitespace: false, indentation: false); } } finally { ((IDisposable)bufferWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) { if (needWhitespace && !isWhitespace) { Write(' '); } Write(indicator); isWhitespace = whitespace; isIndentation &= indentation; } private void WriteIndent() { int num = Math.Max(indent, 0); if (!isIndentation || column > num || (column == num && !isWhitespace)) { WriteBreak(); } while (column < num) { Write(' '); } isWhitespace = true; isIndentation = true; } private void WriteAnchor(AnchorName value) { Write(value.Value); isWhitespace = false; isIndentation = false; } private void WriteTagHandle(string value) { if (!isWhitespace) { Write(' '); } Write(value); isWhitespace = false; isIndentation = false; } private void WriteTagContent(string value, bool needsWhitespace) { if (needsWhitespace && !isWhitespace) { Write(' '); } Write(UrlEncode(value)); isWhitespace = false; isIndentation = false; } private static string UrlEncode(string text) { return UriReplacer.Replace(text, delegate(Match match) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { builder.AppendFormat(CultureInfo.InvariantCulture, "%{0:X02}", b); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } }); } private void Write(char value) { output.Write(value); column++; } private void Write(string value) { output.Write(value); column += value.Length; } private void WriteBreak(char breakCharacter = '\n') { if (breakCharacter == '\n') { output.WriteLine(); } else { output.Write(breakCharacter); } column = 0; } } internal sealed class EmitterSettings { public static readonly EmitterSettings Default = new EmitterSettings(); public int BestIndent { get; } = 2; public int BestWidth { get; } = int.MaxValue; public string NewLine { get; } = Environment.NewLine; public bool IsCanonical { get; } public bool SkipAnchorName { get; private set; } public int MaxSimpleKeyLength { get; } = 1024; public bool IndentSequences { get; } public bool UseUtf16SurrogatePairs { get; } public EmitterSettings() { } public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = false, string? newLine = null, bool useUtf16SurrogatePairs = false) { if (bestIndent < 2 || bestIndent > 9) { throw new ArgumentOutOfRangeException("bestIndent", "BestIndent must be between 2 and 9, inclusive"); } if (bestWidth <= bestIndent * 2) { throw new ArgumentOutOfRangeException("bestWidth", "BestWidth must be greater than BestIndent x 2."); } if (maxSimpleKeyLength < 0) { throw new ArgumentOutOfRangeException("maxSimpleKeyLength", "MaxSimpleKeyLength must be >= 0"); } BestIndent = bestIndent; BestWidth = bestWidth; IsCanonical = isCanonical; MaxSimpleKeyLength = maxSimpleKeyLength; SkipAnchorName = skipAnchorName; IndentSequences = indentSequences; NewLine = newLine ?? Environment.NewLine; UseUtf16SurrogatePairs = useUtf16SurrogatePairs; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithNewLine(string newLine) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine, UseUtf16SurrogatePairs); } public EmitterSettings Canonical() { return new EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithoutAnchorName() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine, UseUtf16SurrogatePairs); } public EmitterSettings WithUtf16SurrogatePairs() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, useUtf16SurrogatePairs: true); } } internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } internal sealed class ForwardAnchorNotSupportedException : YamlException { public ForwardAnchorNotSupportedException(string message) : base(message) { } public ForwardAnchorNotSupportedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public ForwardAnchorNotSupportedException(string message, Exception inner) : base(message, inner) { } } internal static class HashCode { public static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } public static int CombineHashCodes(int h1, object? o2) { return CombineHashCodes(h1, GetHashCode(o2)); } private static int GetHashCode(object? obj) { return obj?.GetHashCode() ?? 0; } } internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } internal sealed class InsertionQueue : IEnumerable, IEnumerable { private const int DefaultInitialCapacity = 128; private T[] items; private int readPtr; private int writePtr; private int mask; private int count; public int Count => count; public int Capacity => items.Length; public InsertionQueue(int initialCapacity = 128) { if (initialCapacity <= 0) { throw new ArgumentOutOfRangeException("initialCapacity", "The initial capacity must be a positive number."); } if (!initialCapacity.IsPowerOfTwo()) { throw new ArgumentException("The initial capacity must be a power of 2.", "initialCapacity"); } items = new T[initialCapacity]; readPtr = initialCapacity / 2; writePtr = initialCapacity / 2; mask = initialCapacity - 1; } public void Enqueue(T item) { ResizeIfNeeded(); items[writePtr] = item; writePtr = (writePtr - 1) & mask; count++; } public T Dequeue() { if (count == 0) { throw new InvalidOperationException("The queue is empty"); } T result = items[readPtr]; readPtr = (readPtr - 1) & mask; count--; return result; } public void Insert(int index, T item) { if (index > count) { throw new InvalidOperationException("Cannot insert outside of the bounds of the queue"); } ResizeIfNeeded(); CalculateInsertionParameters(mask, count, index, ref readPtr, ref writePtr, out var insertPtr, out var copyIndex, out var copyOffset, out var copyLength); if (copyLength != 0) { Array.Copy(items, copyIndex, items, copyIndex + copyOffset, copyLength); } items[insertPtr] = item; count++; } private void ResizeIfNeeded() { int num = items.Length; if (count == num) { T[] destinationArray = new T[num * 2]; int num2 = readPtr + 1; if (num2 > 0) { Array.Copy(items, 0, destinationArray, 0, num2); } writePtr += num; int num3 = num - num2; if (num3 > 0) { Array.Copy(items, readPtr + 1, destinationArray, writePtr + 1, num3); } items = destinationArray; mask = mask * 2 + 1; } } internal static void CalculateInsertionParameters(int mask, int count, int index, ref int readPtr, ref int writePtr, out int insertPtr, out int copyIndex, out int copyOffset, out int copyLength) { int num = (readPtr + 1) & mask; if (index == 0) { insertPtr = (readPtr = num); copyIndex = 0; copyOffset = 0; copyLength = 0; return; } insertPtr = (readPtr - index) & mask; if (index == count) { writePtr = (writePtr - 1) & mask; copyIndex = 0; copyOffset = 0; copyLength = 0; return; } int num2 = ((num >= insertPtr) ? (readPtr - insertPtr) : int.MaxValue); int num3 = ((writePtr <= insertPtr) ? (insertPtr - writePtr) : int.MaxValue); if (num2 <= num3) { insertPtr++; readPtr++; copyIndex = insertPtr; copyOffset = 1; copyLength = num2; } else { copyIndex = writePtr + 1; copyOffset = -1; copyLength = num3; writePtr = (writePtr - 1) & mask; } } public IEnumerator GetEnumerator() { int ptr = readPtr; for (int i = 0; i < Count; i++) { yield return items[ptr]; ptr = (ptr - 1) & mask; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IParser { ParsingEvent? Current { get; } bool MoveNext(); } internal interface IScanner { Mark CurrentPosition { get; } Token? Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [DebuggerStepThrough] internal sealed class LookAheadBuffer : ILookAheadBuffer { private readonly TextReader input; private readonly char[] buffer; private readonly int blockSize; private readonly int mask; private int firstIndex; private int writeOffset; private int count; private bool endOfInput; public bool EndOfInput { get { if (endOfInput) { return count == 0; } return false; } } public LookAheadBuffer(TextReader input, int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); } if (!capacity.IsPowerOfTwo()) { throw new ArgumentException("The capacity must be a power of 2.", "capacity"); } this.input = input ?? throw new ArgumentNullException("input"); blockSize = capacity; buffer = new char[capacity * 2]; mask = capacity * 2 - 1; } private int GetIndexForOffset(int offset) { return (firstIndex + offset) & mask; } public char Peek(int offset) { if (offset >= count) { FillBuffer(); } if (offset < count) { return buffer[(firstIndex + offset) & mask]; } return '\0'; } public void Cache(int length) { if (length >= count) { FillBuffer(); } } private void FillBuffer() { if (endOfInput) { return; } int num = blockSize; do { int num2 = input.Read(buffer, writeOffset, num); if (num2 == 0) { endOfInput = true; return; } num -= num2; writeOffset += num2; count += num2; } while (num > 0); if (writeOffset == buffer.Length) { writeOffset = 0; } } public void Skip(int length) { if (length < 1 || length > blockSize) { throw new ArgumentOutOfRangeException("length", "The length must be between 1 and the number of characters in the buffer. Use the Peek() and / or Cache() methods to fill the buffer."); } firstIndex = GetIndexForOffset(length); count -= length; } } internal readonly struct Mark : IEquatable, IComparable, IComparable { public static readonly Mark Empty = new Mark(0L, 1L, 1L); public long Index { get; } public long Line { get; } public long Column { get; } public Mark(long index, long line, long column) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); } if (line < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); } if (column < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("column", "Column must be greater than or equal to 1."); } Index = index; Line = line; Column = column; } public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } public override bool Equals(object? obj) { return Equals((Mark)(obj ?? ((object)Empty))); } public bool Equals(Mark other) { if (Index == other.Index && Line == other.Line) { return Column == other.Column; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Index.GetHashCode(), HashCode.CombineHashCodes(Line.GetHashCode(), Column.GetHashCode())); } public int CompareTo(object? obj) { return CompareTo((Mark)(obj ?? ((object)Empty))); } public int CompareTo(Mark other) { int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } public static bool operator ==(Mark left, Mark right) { return left.Equals(right); } public static bool operator !=(Mark left, Mark right) { return !(left == right); } public static bool operator <(Mark left, Mark right) { return left.CompareTo(right) < 0; } public static bool operator <=(Mark left, Mark right) { return left.CompareTo(right) <= 0; } public static bool operator >(Mark left, Mark right) { return left.CompareTo(right) > 0; } public static bool operator >=(Mark left, Mark right) { return left.CompareTo(right) >= 0; } } internal sealed class MaximumRecursionLevelReachedException : YamlException { public MaximumRecursionLevelReachedException(string message) : base(message) { } public MaximumRecursionLevelReachedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public MaximumRecursionLevelReachedException(string message, Exception inner) : base(message, inner) { } } internal sealed class MergingParser : IParser { private sealed class ParsingEventCollection : IEnumerable>, IEnumerable { private readonly LinkedList events; private readonly HashSet> deleted; private readonly Dictionary> references; public ParsingEventCollection() { events = new LinkedList(); deleted = new HashSet>(); references = new Dictionary>(); } public void AddAfter(LinkedListNode node, IEnumerable items) { foreach (ParsingEvent item in items) { node = events.AddAfter(node, item); } } public void Add(ParsingEvent item) { LinkedListNode node = events.AddLast(item); AddReference(item, node); } public void MarkDeleted(LinkedListNode node) { deleted.Add(node); } public bool IsDeleted(LinkedListNode node) { return deleted.Contains(node); } public void CleanMarked() { foreach (LinkedListNode item in deleted) { events.Remove(item); } } public IEnumerable> FromAnchor(AnchorName anchor) { LinkedListNode next = references[anchor].Next; return Enumerate(next); } public IEnumerator> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static IEnumerable> Enumerate(LinkedListNode? node) { while (node != null) { yield return node; node = node.Next; } } private void AddReference(ParsingEvent item, LinkedListNode node) { if (item is MappingStart { Anchor: { IsEmpty: false } anchor }) { references[anchor] = node; } } } private sealed class ParsingEventCloner : IParsingEventVisitor { private ParsingEvent? clonedEvent; public ParsingEvent Clone(ParsingEvent e) { e.Accept(this); if (clonedEvent == null) { throw new InvalidOperationException($"Could not clone event of type '{e.Type}'"); } return clonedEvent; } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.AnchorAlias e) { clonedEvent = new YamlDotNet.Core.Events.AnchorAlias(e.Value, e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Scalar e) { clonedEvent = new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceStart e) { clonedEvent = new SequenceStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceEnd e) { clonedEvent = new SequenceEnd(e.Start, e.End); } void IParsingEventVisitor.Visit(MappingStart e) { clonedEvent = new MappingStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(MappingEnd e) { clonedEvent = new MappingEnd(e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Comment e) { throw new NotSupportedException(); } } private readonly ParsingEventCollection events; private readonly IParser innerParser; private IEnumerator> iterator; private bool merged; public ParsingEvent? Current => iterator.Current?.Value; public MergingParser(IParser innerParser) { events = new ParsingEventCollection(); merged = false; iterator = events.GetEnumerator(); this.innerParser = innerParser; } public bool MoveNext() { if (!merged) { Merge(); events.CleanMarked(); iterator = events.GetEnumerator(); merged = true; } return iterator.MoveNext(); } private void Merge() { while (innerParser.MoveNext()) { events.Add(innerParser.Current); } foreach (LinkedListNode @event in events) { if (IsMergeToken(@event)) { events.MarkDeleted(@event); if (!HandleMerge(@event.Next)) { throw new SemanticErrorException(@event.Value.Start, @event.Value.End, "Unrecognized merge key pattern"); } } } } private bool HandleMerge(LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(node, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool HandleMergeSequence(LinkedListNode sequenceStart, LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(sequenceStart, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private static bool IsMergeToken(LinkedListNode node) { if (node.Value is YamlDotNet.Core.Events.Scalar scalar) { return scalar.Value == "<<"; } return false; } private bool HandleAnchorAlias(LinkedListNode node, LinkedListNode anchorNode, YamlDotNet.Core.Events.AnchorAlias anchorAlias) { IEnumerable mappingEvents = GetMappingEvents(anchorAlias.Value); events.AddAfter(node, mappingEvents); events.MarkDeleted(anchorNode); return true; } private bool HandleSequence(LinkedListNode node) { events.MarkDeleted(node); LinkedListNode linkedListNode = node; while (linkedListNode != null) { if (linkedListNode.Value is SequenceEnd) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable GetMappingEvents(AnchorName anchor) { ParsingEventCloner parsingEventCloner = new ParsingEventCloner(); int nesting = 0; return (from e in events.FromAnchor(anchor) where !events.IsDeleted(e) select e.Value).TakeWhile((ParsingEvent e) => (nesting += e.NestingIncrease) >= 0).Select(parsingEventCloner.Clone); } } internal class Parser : IParser { private class EventQueue { private readonly Queue highPriorityEvents = new Queue(); private readonly Queue normalPriorityEvents = new Queue(); public int Count => highPriorityEvents.Count + normalPriorityEvents.Count; public void Enqueue(ParsingEvent @event) { EventType type = @event.Type; if (type == EventType.StreamStart || type == EventType.DocumentStart) { highPriorityEvents.Enqueue(@event); } else { normalPriorityEvents.Enqueue(@event); } } public ParsingEvent Dequeue() { if (highPriorityEvents.Count <= 0) { return normalPriorityEvents.Dequeue(); } return highPriorityEvents.Dequeue(); } } private readonly Stack states = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly IScanner scanner; private Token? currentToken; private VersionDirective? version; private readonly EventQueue pendingEvents = new EventQueue(); public ParsingEvent? Current { get; private set; } private Token? GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (!(currentToken is YamlDotNet.Core.Tokens.Comment comment)) { break; } pendingEvents.Enqueue(new YamlDotNet.Core.Events.Comment(comment.Value, comment.IsInline, comment.Start, comment.End)); scanner.ConsumeCurrent(); } } return currentToken; } public Parser(TextReader input) : this(new Scanner(input)) { } public Parser(IScanner scanner) { this.scanner = scanner; } public bool MoveNext() { if (state == ParserState.StreamEnd) { Current = null; return false; } if (pendingEvents.Count == 0) { pendingEvents.Enqueue(StateMachine()); } Current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { return state switch { ParserState.StreamStart => ParseStreamStart(), ParserState.ImplicitDocumentStart => ParseDocumentStart(isImplicit: true), ParserState.DocumentStart => ParseDocumentStart(isImplicit: false), ParserState.DocumentContent => ParseDocumentContent(), ParserState.DocumentEnd => ParseDocumentEnd(), ParserState.BlockNode => ParseNode(isBlock: true, isIndentlessSequence: false), ParserState.BlockNodeOrIndentlessSequence => ParseNode(isBlock: true, isIndentlessSequence: true), ParserState.FlowNode => ParseNode(isBlock: false, isIndentlessSequence: false), ParserState.BlockSequenceFirstEntry => ParseBlockSequenceEntry(isFirst: true), ParserState.BlockSequenceEntry => ParseBlockSequenceEntry(isFirst: false), ParserState.IndentlessSequenceEntry => ParseIndentlessSequenceEntry(), ParserState.BlockMappingFirstKey => ParseBlockMappingKey(isFirst: true), ParserState.BlockMappingKey => ParseBlockMappingKey(isFirst: false), ParserState.BlockMappingValue => ParseBlockMappingValue(), ParserState.FlowSequenceFirstEntry => ParseFlowSequenceEntry(isFirst: true), ParserState.FlowSequenceEntry => ParseFlowSequenceEntry(isFirst: false), ParserState.FlowSequenceEntryMappingKey => ParseFlowSequenceEntryMappingKey(), ParserState.FlowSequenceEntryMappingValue => ParseFlowSequenceEntryMappingValue(), ParserState.FlowSequenceEntryMappingEnd => ParseFlowSequenceEntryMappingEnd(), ParserState.FlowMappingFirstKey => ParseFlowMappingKey(isFirst: true), ParserState.FlowMappingKey => ParseFlowMappingKey(isFirst: false), ParserState.FlowMappingValue => ParseFlowMappingValue(isEmpty: false), ParserState.FlowMappingEmptyValue => ParseFlowMappingValue(isEmpty: true), _ => throw new InvalidOperationException(), }; } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } private YamlDotNet.Core.Events.StreamStart ParseStreamStart() { Token token = GetCurrentToken(); if (!(token is YamlDotNet.Core.Tokens.StreamStart streamStart)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "Did not find expected ."); } Skip(); state = ParserState.ImplicitDocumentStart; return new YamlDotNet.Core.Events.StreamStart(streamStart.Start, streamStart.End); } private ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is VersionDirective) { throw new SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token token = GetCurrentToken(); if (!isImplicit) { while (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); token = GetCurrentToken(); } } if (token == null) { throw new SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (token is YamlDotNet.Core.Tokens.Scalar && (state == ParserState.ImplicitDocumentStart || state == ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(token is VersionDirective) && !(token is TagDirective) && !(token is YamlDotNet.Core.Tokens.DocumentStart) && !(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) || token is BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new YamlDotNet.Core.Events.DocumentStart(null, tags, isImplicit: true, token.Start, token.End); } if (!(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark start = token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); VersionDirective versionDirective = ProcessDirectives(tags2); token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(token is YamlDotNet.Core.Tokens.DocumentStart)) { throw new SemanticErrorException(token.Start, token.End, "Did not find expected ."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; Mark end = token.End; Skip(); return new YamlDotNet.Core.Events.DocumentStart(versionDirective, tags2, isImplicit: false, start, end); } if (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); } state = ParserState.StreamEnd; token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); YamlDotNet.Core.Events.StreamEnd result = new YamlDotNet.Core.Events.StreamEnd(token.Start, token.End); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } private VersionDirective? ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; VersionDirective result = null; while (true) { if (GetCurrentToken() is VersionDirective versionDirective) { if (version != null) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found duplicate %YAML directive."); } if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found incompatible YAML document."); } result = (version = versionDirective); flag = true; } else { if (!(GetCurrentToken() is TagDirective tagDirective)) { break; } if (tags.Contains(tagDirective.Handle)) { throw new SemanticErrorException(tagDirective.Start, tagDirective.End, "Found duplicate %TAG directive."); } tags.Add(tagDirective); flag = true; } Skip(); } if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && version == null) { version = new VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) { foreach (TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentEnd || GetCurrentToken() is YamlDotNet.Core.Tokens.StreamEnd) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static YamlDotNet.Core.Events.Scalar ProcessEmptyScalar(in Mark position) { return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, string.Empty, ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false, position, position); } private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { if (GetCurrentToken() is Error { Start: var start } error) { throw new SemanticErrorException(in start, error.End, error.Value); } Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { state = states.Pop(); ParsingEvent result = new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); Skip(); return result; } Mark start2 = token.Start; AnchorName anchor = AnchorName.Empty; TagName tag = TagName.Empty; Anchor anchor2 = null; Tag tag2 = null; while (true) { if (anchor.IsEmpty && token is Anchor anchor3) { anchor2 = anchor3; anchor = anchor3.Value; Skip(); } else { if (!tag.IsEmpty || !(token is Tag tag3)) { if (token is Anchor { Start: var start3 } anchor4) { throw new SemanticErrorException(in start3, anchor4.End, "While parsing a node, found more than one anchor."); } if (token is YamlDotNet.Core.Tokens.AnchorAlias { Start: var start4 } anchorAlias2) { throw new SemanticErrorException(in start4, anchorAlias2.End, "While parsing a node, did not find expected token."); } if (!(token is Error error2)) { break; } if (tag2 != null && anchor2 != null && !anchor.IsEmpty) { return new YamlDotNet.Core.Events.Scalar(anchor, default(TagName), string.Empty, ScalarStyle.Any, isPlainImplicit: false, isQuotedImplicit: false, anchor2.Start, anchor2.End); } throw new SemanticErrorException(error2.Start, error2.End, error2.Value); } tag2 = tag3; if (string.IsNullOrEmpty(tag3.Handle)) { tag = new TagName(tag3.Suffix); } else { if (!tagDirectives.Contains(tag3.Handle)) { throw new SemanticErrorException(tag3.Start, tag3.End, "While parsing a node, found undefined tag handle."); } tag = new TagName(tagDirectives[tag3.Handle].Prefix + tag3.Suffix); } Skip(); } token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); } bool isEmpty = tag.IsEmpty; if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, token.End); } if (token is YamlDotNet.Core.Tokens.Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tag.IsEmpty) || tag.IsNonSpecific) { isPlainImplicit = true; } else if (tag.IsEmpty) { isQuotedImplicit = true; } state = states.Pop(); Skip(); ParsingEvent result2 = new YamlDotNet.Core.Events.Scalar(anchor, tag, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start2, scalar.End, scalar.IsKey); if (!anchor.IsEmpty && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken is Error) { Error error3 = currentToken as Error; throw new SemanticErrorException(error3.Start, error3.End, error3.Value); } } if (state == ParserState.FlowMappingKey && !(scanner.Current is FlowMappingEnd) && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { throw new SemanticErrorException(currentToken.Start, currentToken.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (token is FlowSequenceStart flowSequenceStart) { state = ParserState.FlowSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Flow, start2, flowSequenceStart.End); } if (token is FlowMappingStart flowMappingStart) { state = ParserState.FlowMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start2, flowMappingStart.End); } if (isBlock) { if (token is BlockSequenceStart blockSequenceStart) { state = ParserState.BlockSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, blockSequenceStart.End); } if (token is BlockMappingStart blockMappingStart) { state = ParserState.BlockMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start2, blockMappingStart.End); } } if (!anchor.IsEmpty || !tag.IsEmpty) { state = states.Pop(); return new YamlDotNet.Core.Events.Scalar(anchor, tag, string.Empty, ScalarStyle.Plain, isEmpty, isQuotedImplicit: false, start2, token.End); } throw new SemanticErrorException(token.Start, token.End, "While parsing a node, did not find expected node content."); } private YamlDotNet.Core.Events.DocumentEnd ParseDocumentEnd() { Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; Mark start = token.Start; Mark end = start; if (token is YamlDotNet.Core.Tokens.DocumentEnd) { end = token.End; Skip(); isImplicit = false; } else if (!(currentToken is YamlDotNet.Core.Tokens.StreamEnd) && !(currentToken is YamlDotNet.Core.Tokens.DocumentStart) && !(currentToken is FlowSequenceEnd) && !(currentToken is VersionDirective) && (!(Current is YamlDotNet.Core.Events.Scalar) || !(currentToken is Error))) { throw new SemanticErrorException(in start, in end, "Did not find expected ."); } if (version != null && version.Version.Major == 1 && version.Version.Minor > 1) { version = null; } state = ParserState.DocumentStart; return new YamlDotNet.Core.Events.DocumentEnd(isImplicit, start, end); } private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is BlockEntry { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(in position); } if (token is BlockEnd blockEnd) { state = states.Pop(); ParsingEvent result = new SequenceEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a block collection, did not find expected '-' indicator."); } private ParsingEvent ParseIndentlessSequenceEntry() { Token token = GetCurrentToken(); if (token is BlockEntry { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(in position); } state = states.Pop(); return new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is Key { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingValue; return ProcessEmptyScalar(in position); } if (token is Value value) { Skip(); return ProcessEmptyScalar(value.End); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { Skip(); return new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); } if (token is BlockEnd blockEnd) { state = states.Pop(); ParsingEvent result = new MappingEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } if (GetCurrentToken() is Error { Start: var start } error) { throw new SyntaxErrorException(in start, error.End, error.Value); } throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a block mapping, did not find expected key."); } private ParsingEvent ParseBlockMappingValue() { Token token = GetCurrentToken(); if (token is Value { End: var position }) { Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(in position); } if (token is Error { Start: var start } error) { throw new SemanticErrorException(in start, error.End, error.Value); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); ParsingEvent result; if (!(token is FlowSequenceEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); token = GetCurrentToken(); } if (token is Key) { state = ParserState.FlowSequenceEntryMappingKey; result = new MappingStart(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); result = new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); Skip(); return result; } private ParsingEvent ParseFlowSequenceEntryMappingKey() { Token token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } Mark position = token?.End ?? Mark.Empty; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingValue() { Token token = GetCurrentToken(); if (token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private MappingEnd ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; Token token = GetCurrentToken(); return new MappingEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (!(token is FlowMappingEnd)) { if (!isFirst) { if (token is FlowEntry) { Skip(); token = GetCurrentToken(); } else if (!(token is YamlDotNet.Core.Tokens.Scalar)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (token is Key) { Skip(); token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } state = ParserState.FlowMappingValue; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } if (token is YamlDotNet.Core.Tokens.Scalar) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } if (!(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); Skip(); return new MappingEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseFlowMappingValue(bool isEmpty) { Token token = GetCurrentToken(); if (!isEmpty && token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowMappingKey; if (!isEmpty && token is YamlDotNet.Core.Tokens.Scalar scalar) { Skip(); return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, scalar.Value, scalar.Style, isPlainImplicit: false, isQuotedImplicit: false, token.Start, scalar.End); } return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } } internal static class ParserExtensions { public static T Consume(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Accept(out @event)) { parser.MoveNext(); return true; } return false; } public static T Require(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { ParsingEvent current = parser.Current; if (current == null) { throw new YamlException("Expected '" + typeof(T).Name + "', got nothing."); } throw new YamlException(current.Start, current.End, $"Expected '{typeof(T).Name}', got '{current.GetType().Name}' (at {current.Start})."); } return @event; } public static bool Accept(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Current == null && !parser.MoveNext()) { throw new EndOfStreamException(); } if (parser.Current is T val) { @event = val; return true; } @event = null; return false; } public static void SkipThisAndNestedEvents(this IParser parser) { int num = 0; do { ParsingEvent parsingEvent = parser.Consume(); num += parsingEvent.NestingIncrease; } while (num > 0); } [Obsolete("Please use Consume() instead")] public static T Expect(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: MaybeNull] public static T? Allow(this IParser parser) where T : ParsingEvent { if (!parser.TryConsume(out var @event)) { return null; } return @event; } [Obsolete("Please use Accept(out var evt) instead")] [return: MaybeNull] public static T? Peek(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { return null; } return @event; } [Obsolete("Please use TryConsume(out var evt) or Accept(out var evt) instead")] public static bool Accept(this IParser parser) where T : ParsingEvent { T @event; return parser.Accept(out @event); } public static bool TryFindMappingEntry(this IParser parser, Func selector, [MaybeNullWhen(false)] out YamlDotNet.Core.Events.Scalar? key, [MaybeNullWhen(false)] out ParsingEvent? value) { if (parser.TryConsume(out var _)) { while (parser.Current != null) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (current is MappingStart || current is SequenceStart) { parser.SkipThisAndNestedEvents(); } else { parser.MoveNext(); } continue; } bool flag = selector(scalar); parser.MoveNext(); if (flag) { value = parser.Current; key = scalar; return true; } parser.SkipThisAndNestedEvents(); } } key = null; value = null; return false; } } internal enum ParserState { StreamStart, StreamEnd, ImplicitDocumentStart, DocumentStart, DocumentContent, DocumentEnd, BlockNode, BlockNodeOrIndentlessSequence, FlowNode, BlockSequenceFirstEntry, BlockSequenceEntry, IndentlessSequenceEntry, BlockMappingFirstKey, BlockMappingKey, BlockMappingValue, FlowSequenceFirstEntry, FlowSequenceEntry, FlowSequenceEntryMappingKey, FlowSequenceEntryMappingValue, FlowSequenceEntryMappingEnd, FlowMappingFirstKey, FlowMappingKey, FlowMappingValue, FlowMappingEmptyValue } internal sealed class RecursionLevel { private int current; public int Maximum { get; } public RecursionLevel(int maximum) { Maximum = maximum; } public void Increment() { if (!TryIncrement()) { throw new MaximumRecursionLevelReachedException("Maximum level of recursion reached"); } } public bool TryIncrement() { if (current < Maximum) { current++; return true; } return false; } public void Decrement() { if (current == 0) { throw new InvalidOperationException("Attempted to decrement RecursionLevel to a negative value"); } current--; } } internal enum ScalarStyle { Any, Plain, SingleQuoted, DoubleQuoted, Literal, Folded, ForcePlain } internal class Scanner : IScanner { private const int MaxVersionNumberLength = 9; private static readonly SortedDictionary SimpleEscapeCodes = new SortedDictionary { { '0', '\0' }, { 'a', '\a' }, { 'b', '\b' }, { 't', '\t' }, { '\t', '\t' }, { 'n', '\n' }, { 'v', '\v' }, { 'f', '\f' }, { 'r', '\r' }, { 'e', '\u001b' }, { ' ', ' ' }, { '"', '"' }, { '\\', '\\' }, { '/', '/' }, { 'N', '\u0085' }, { '_', '\u00a0' }, { 'L', '\u2028' }, { 'P', '\u2029' } }; private readonly Stack indents = new Stack(); private readonly InsertionQueue tokens = new InsertionQueue(); private readonly Stack simpleKeys = new Stack(); private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private bool flowCollectionFetched; private bool startFlowCollectionFetched; private long indent = -1L; private bool flowScalarFetched; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; private Token? previous; private Anchor? previousAnchor; private YamlDotNet.Core.Tokens.Scalar? lastScalar; private readonly int maxKeySize; private static readonly byte[] EmptyBytes = Array.Empty(); public bool SkipComments { get; private set; } public Token? Current { get; private set; } public Mark CurrentPosition => cursor.Mark(); private bool IsDocumentStart() { if (!analyzer.EndOfInput && cursor.LineOffset == 0L && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0L && analyzer.Check('.') && analyzer.Check('.', 1) && analyzer.Check('.', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentIndicator() { if (!IsDocumentStart()) { return IsDocumentEnd(); } return true; } public Scanner(TextReader input, bool skipComments = true) : this(input, skipComments, 1024) { } public Scanner(TextReader input, bool skipComments, int maxKeySize) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; this.maxKeySize = maxKeySize; } public bool MoveNext() { if (Current != null) { ConsumeCurrent(); } return MoveNextWithoutConsuming(); } public bool MoveNextWithoutConsuming() { if (!tokenAvailable && !streamEndProduced) { FetchMoreTokens(); } if (tokens.Count > 0) { Current = tokens.Dequeue(); tokenAvailable = false; return true; } Current = null; return false; } public void ConsumeCurrent() { tokensParsed++; tokenAvailable = false; previous = Current; Current = null; } private char ReadCurrentCharacter() { char result = analyzer.Peek(0); Skip(); return result; } private char ReadLine() { if (analyzer.Check("\r\n\u0085")) { SkipLine(); return '\n'; } char result = analyzer.Peek(0); SkipLine(); return result; } private void FetchMoreTokens() { while (true) { bool flag = false; if (tokens.Count == 0) { flag = true; } else { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) { flag = true; break; } } } if (!flag) { break; } FetchNextToken(); } tokenAvailable = true; } private static bool StartsWith(StringBuilder what, char start) { if (what.Length > 0) { return what[0] == start; } return false; } private void StaleSimpleKeys() { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + maxKeySize < cursor.Index)) { if (simpleKey.IsRequired) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a simple key, could not find expected ':'.", mark, mark)); } simpleKey.MarkAsImpossible(); } } } private void FetchNextToken() { if (!streamStartProduced) { FetchStreamStart(); return; } ScanToNextToken(); StaleSimpleKeys(); UnrollIndent(cursor.LineOffset); analyzer.Buffer.Cache(4); if (analyzer.Buffer.EndOfInput) { lastScalar = null; FetchStreamEnd(); } if (cursor.LineOffset == 0L && analyzer.Check('%')) { lastScalar = null; FetchDirective(); return; } if (IsDocumentStart()) { lastScalar = null; FetchDocumentIndicator(isStartToken: true); return; } if (IsDocumentEnd()) { lastScalar = null; FetchDocumentIndicator(isStartToken: false); return; } if (analyzer.Check('[')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: true); return; } if (analyzer.Check('{')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: false); return; } if (analyzer.Check(']')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: true); return; } if (analyzer.Check('}')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: false); return; } if (analyzer.Check(',')) { lastScalar = null; FetchFlowEntry(); return; } if (analyzer.Check('-')) { if (analyzer.IsWhiteBreakOrZero(1)) { FetchBlockEntry(); return; } if (flowLevel > 0 && analyzer.Check(",[]{}", 1)) { tokens.Enqueue(new Error("Invalid key indicator format.", cursor.Mark(), cursor.Mark())); } } if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && analyzer.IsWhiteBreakOrZero(1)) { FetchKey(); } else if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && (!simpleKeyAllowed || flowLevel <= 0) && (!flowScalarFetched || !analyzer.Check(':', 1)) && (analyzer.IsWhiteBreakOrZero(1) || analyzer.Check(',', 1) || flowScalarFetched || flowCollectionFetched || startFlowCollectionFetched)) { if (lastScalar != null) { lastScalar.IsKey = true; lastScalar = null; } FetchValue(); } else if (analyzer.Check('*')) { FetchAnchor(isAlias: true); } else if (analyzer.Check('&')) { FetchAnchor(isAlias: false); } else if (analyzer.Check('!')) { FetchTag(); } else if (analyzer.Check('|') && flowLevel == 0) { FetchBlockScalar(isLiteral: true); } else if (analyzer.Check('>') && flowLevel == 0) { FetchBlockScalar(isLiteral: false); } else if (analyzer.Check('\'')) { FetchQuotedScalar(isSingleQuoted: true); } else if (analyzer.Check('"')) { FetchQuotedScalar(isSingleQuoted: false); } else if ((!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("-?:,[]{}#&*!|>'\"%@`")) || (analyzer.Check('-') && !analyzer.IsWhite(1)) || (analyzer.Check("?:") && !analyzer.IsWhiteBreakOrZero(1)) || (simpleKeyAllowed && flowLevel > 0)) { if (plainScalarFollowedByComment) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning plain scalar, found a comment between adjacent scalars.", mark, mark)); } if ((flowScalarFetched || (flowCollectionFetched && !startFlowCollectionFetched)) && analyzer.Check(':')) { Skip(); } flowScalarFetched = false; flowCollectionFetched = false; startFlowCollectionFetched = false; plainScalarFollowedByComment = false; FetchPlainScalar(); } else { if (simpleKeyAllowed && indent >= cursor.LineOffset && analyzer.IsTab()) { throw new SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark start = cursor.Mark(); Skip(); throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning for the next token, found character that cannot start any token."); } Skip(); } } private bool CheckWhiteSpace() { if (!analyzer.Check(' ')) { if (flowLevel > 0 || !simpleKeyAllowed) { return analyzer.Check('\t'); } return false; } return true; } private void Skip() { cursor.Skip(); analyzer.Buffer.Skip(1); } private void SkipLine() { if (analyzer.IsCrLf()) { cursor.SkipLineByOffset(2); analyzer.Buffer.Skip(2); } else if (analyzer.IsBreak()) { cursor.SkipLineByOffset(1); analyzer.Buffer.Skip(1); } else if (!analyzer.IsZero()) { throw new InvalidOperationException("Not at a break."); } } private void ScanToNextToken() { while (true) { if (CheckWhiteSpace()) { Skip(); continue; } ProcessComment(); if (analyzer.IsBreak()) { SkipLine(); if (flowLevel == 0) { simpleKeyAllowed = true; } continue; } break; } } private void ProcessComment() { if (!analyzer.Check('#')) { return; } Mark start = cursor.Mark(); Skip(); while (analyzer.IsSpace()) { Skip(); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } if (!SkipComments) { bool isInline = previous != null && previous.End.Line == start.Line && previous.End.Column != 1 && !(previous is YamlDotNet.Core.Tokens.StreamStart); tokens.Enqueue(new YamlDotNet.Core.Tokens.Comment(builder.ToString(), isInline, start, cursor.Mark())); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchStreamStart() { simpleKeys.Push(new SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamStart(in start, in start)); } private void UnrollIndent(long column) { if (flowLevel == 0) { while (indent > column) { Mark start = cursor.Mark(); tokens.Enqueue(new BlockEnd(in start, in start)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } private Token? ScanDirective() { Mark start = cursor.Mark(); Skip(); string text = ScanDirectiveName(in start); Token result; if (!(text == "YAML")) { if (!(text == "TAG")) { while (!analyzer.EndOfInput && !analyzer.Check('#') && !analyzer.IsBreak()) { Skip(); } return null; } result = ScanTagDirectiveValue(in start); } else { if (!(previous is YamlDotNet.Core.Tokens.DocumentStart) && !(previous is YamlDotNet.Core.Tokens.StreamStart) && !(previous is YamlDotNet.Core.Tokens.DocumentEnd)) { throw new SemanticErrorException(in start, cursor.Mark(), "While scanning a version directive, did not find preceding ."); } result = ScanVersionDirectiveValue(in start); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); } return result; } private void FetchDocumentIndicator(bool isStartToken) { UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentStart(in start, cursor.Mark())); return; } Token token = null; while (!analyzer.EndOfInput && !analyzer.IsBreak() && !analyzer.Check('#')) { if (!analyzer.IsWhite()) { token = new Error("While scanning a document end, found invalid content after '...' marker.", start, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentEnd(in start, in start)); if (token != null) { tokens.Enqueue(token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Token item = ((!isSequenceToken) ? ((Token)new FlowMappingStart(in start, in start)) : ((Token)new FlowSequenceStart(in start, in start))); tokens.Enqueue(item); startFlowCollectionFetched = true; } private void IncreaseFlowLevel() { simpleKeys.Push(new SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Token token = null; Token item; if (isSequenceToken) { if (analyzer.Check('#')) { token = new Error("While scanning a flow sequence end, found invalid comment after ']'.", start, start); } item = new FlowSequenceEnd(in start, in start); } else { item = new FlowMappingEnd(in start, in start); } tokens.Enqueue(item); if (token != null) { tokens.Enqueue(token); } flowCollectionFetched = true; } private void DecreaseFlowLevel() { if (flowLevel > 0) { flowLevel--; simpleKeys.Pop(); } } private void FetchFlowEntry() { RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); if (analyzer.Check('#')) { tokens.Enqueue(new Error("While scanning a flow entry, found invalid comment after comma.", start, end)); } else { tokens.Enqueue(new FlowEntry(in start, in end)); } } private void FetchBlockEntry() { if (flowLevel == 0) { if (!simpleKeyAllowed) { if (previousAnchor != null && previousAnchor.End.Line == cursor.Line) { throw new SemanticErrorException(previousAnchor.Start, previousAnchor.End, "Anchor before sequence entry on same line is not allowed."); } Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Block sequence entries are not allowed in this context.", mark, mark)); } RollIndent(cursor.LineOffset, -1, isSequence: true, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new BlockEntry(in start, cursor.Mark())); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { Mark start = cursor.Mark(); throw new SyntaxErrorException(in start, in start, "Mapping keys are not allowed in this context."); } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = flowLevel == 0; Mark start2 = cursor.Mark(); Skip(); tokens.Enqueue(new Key(in start2, cursor.Mark())); } private void FetchValue() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible) { tokens.Insert(simpleKey.TokenNumber - tokensParsed, new Key(simpleKey.Mark, simpleKey.Mark)); RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, isSequence: false, simpleKey.Mark); simpleKey.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Mapping values are not allowed in this context.", mark, mark)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0L && simpleKey.LineOffset == 0L) { tokens.Insert(tokens.Count, new Key(simpleKey.Mark, simpleKey.Mark)); flag = false; } } simpleKeyAllowed = flag; } Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new Value(in start, cursor.Mark())); } private void RollIndent(long column, int number, bool isSequence, Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new BlockMappingStart(in position, in position)) : ((Token)new BlockSequenceStart(in position, in position))); if (number == -1) { tokens.Enqueue(item); } else { tokens.Insert(number - tokensParsed, item); } } } private void FetchAnchor(bool isAlias) { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanAnchor(isAlias)); } private Token ScanAnchor(bool isAlias) { Mark start = cursor.Mark(); Skip(); bool flag = false; if (isAlias) { SimpleKey simpleKey = simpleKeys.Peek(); flag = simpleKey.IsRequired && simpleKey.IsPossible; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("[]{},") && (!flag || !analyzer.Check(':') || !analyzer.IsWhiteBreakOrZero(1))) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0 || (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("?:,]}%@`"))) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning an anchor or alias, found value containing disallowed: []{},"); } AnchorName value = new AnchorName(builder.ToString()); if (isAlias) { return new YamlDotNet.Core.Tokens.AnchorAlias(value, start, cursor.Mark()); } return previousAnchor = new Anchor(value, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchTag() { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanTag()); } private Tag ScanTag() { Mark start = cursor.Mark(); string text; string text2; if (analyzer.Check('<', 1)) { text = string.Empty; Skip(); Skip(); text2 = ScanTagUri(null, start); if (!analyzer.Check('>')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find the expected '>'."); } Skip(); } else { string text3 = ScanTagHandle(isDirective: false, start); if (text3.Length > 1 && text3[0] == '!' && text3[text3.Length - 1] == '!') { text = text3; text2 = ScanTagUri(null, start); } else { text2 = ScanTagUri(text3, start); text = "!"; if (text2.Length == 0) { text2 = text; text = string.Empty; } } } if (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check(',')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find expected whitespace, comma or line break."); } return new Tag(text, text2, start, cursor.Mark()); } private void FetchBlockScalar(bool isLiteral) { SaveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private YamlDotNet.Core.Tokens.Scalar ScanBlockScalar(bool isLiteral) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; int num = 0; int num2 = 0; long currentIndent = 0L; bool flag = false; bool? isFirstLine = null; Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); } } else if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); } } if (analyzer.Check('#')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, found a comment without whtespace after '>' indicator."); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a block scalar, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); if (!isFirstLine.HasValue) { isFirstLine = true; } else if (isFirstLine == true) { isFirstLine = false; } } Mark end = cursor.Mark(); if (num2 != 0) { currentIndent = ((indent >= 0) ? (indent + num2) : num2); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end, ref isFirstLine); isFirstLine = false; while (cursor.LineOffset == currentIndent && !analyzer.IsZero() && !IsDocumentEnd()) { bool flag2 = analyzer.IsWhite(); if (!isLiteral && StartsWith(builder2, '\n') && !flag && !flag2) { if (builder3.Length == 0) { builder.Append(' '); } builder2.Length = 0; } else { builder.Append((object?)builder2); builder2.Length = 0; } builder.Append((object?)builder3); builder3.Length = 0; flag = analyzer.IsWhite(); while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } char c = ReadLine(); if (c != 0) { builder2.Append(c); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end, ref isFirstLine); } if (num != -1) { builder.Append((object?)builder2); } if (num == 1) { builder.Append((object?)builder3); } ScalarStyle style = (isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), style, start, end); } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private long ScanBlockScalarBreaks(long currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { long num = 0L; long num2 = -1L; end = cursor.Mark(); while (true) { if ((currentIndent == 0L || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) { Skip(); continue; } if (cursor.LineOffset > num) { num = cursor.LineOffset; } if (!analyzer.IsBreak()) { break; } if (isFirstLine == true) { isFirstLine = false; num2 = cursor.LineOffset; } breaks.Append(ReadLine()); end = cursor.Mark(); } if (isLiteral && isFirstLine == true) { long num3 = cursor.LineOffset; int num4 = 0; while (!analyzer.IsBreak(num4) && analyzer.IsSpace(num4)) { num4++; num3++; } if (analyzer.IsBreak(num4) && num3 > cursor.LineOffset) { isFirstLine = false; num2 = num3; } } if (isLiteral && num2 > 1 && currentIndent < num2 - 1) { throw new SemanticErrorException(in end, cursor.Mark(), "While scanning a literal block scalar, found extra spaces in first line."); } if (!isLiteral && num > cursor.LineOffset && num2 > -1) { throw new SemanticErrorException(in end, cursor.Mark(), "While scanning a literal block scalar, found more spaces in lines above first content line."); } if (currentIndent == 0L && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1L)); } return currentIndent; } private void FetchQuotedScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; flowScalarFetched = flowLevel > 0; YamlDotNet.Core.Tokens.Scalar item = ScanFlowScalar(isSingleQuoted); tokens.Enqueue(item); lastScalar = item; if (!isSingleQuoted && analyzer.Check('#')) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", mark, mark)); } } private YamlDotNet.Core.Tokens.Scalar ScanFlowScalar(bool isSingleQuoted) { Mark start = cursor.Mark(); Skip(); StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; while (true) { if (IsDocumentIndicator()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a multi-line double-quoted scalar, found wrong indentation."); } flag = false; while (!analyzer.IsWhiteBreakOrZero()) { if (isSingleQuoted && analyzer.Check('\'') && analyzer.Check('\'', 1)) { builder.Append('\''); Skip(); Skip(); continue; } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } if (!isSingleQuoted && analyzer.Check('\\') && analyzer.IsBreak(1)) { Skip(); SkipLine(); flag = true; break; } if (!isSingleQuoted && analyzer.Check('\\')) { int num = 0; char c = analyzer.Peek(1); switch (c) { case 'x': num = 2; break; case 'u': num = 4; break; case 'U': num = 8; break; default: { if (SimpleEscapeCodes.TryGetValue(c, out var value)) { builder.Append(value); break; } throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unknown escape character."); } } Skip(); Skip(); if (num <= 0) { continue; } int num2 = 0; for (int i = 0; i < num; i++) { if (!analyzer.IsHex(i)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, did not find expected hexadecimal number."); } num2 = (num2 << 4) + analyzer.AsHex(i); } if (num2 >= 55296 && num2 <= 57343) { for (int j = 0; j < num; j++) { Skip(); } if (analyzer.Peek(0) != '\\' || (analyzer.Peek(1) != 'u' && analyzer.Peek(1) != 'U')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode surrogates."); } Skip(); num = ((analyzer.Peek(0) != 'u') ? 8 : 4); Skip(); int num3 = 0; for (int k = 0; k < num; k++) { if (!analyzer.IsHex(0)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, did not find expected hexadecimal number."); } num3 = (num3 << 4) + analyzer.AsHex(k); } for (int l = 0; l < num; l++) { Skip(); } num2 = char.ConvertToUtf32((char)num2, (char)num3); } else { if (num2 > 1114111) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode character escape code."); } for (int m = 0; m < num; m++) { Skip(); } } builder.Append(char.ConvertFromUtf32(num2)); } else { builder.Append(ReadCurrentCharacter()); } } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; } else { builder.Append((object?)builder2); builder2.Length = 0; } } Skip(); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper4/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchPlainScalar() { SaveSimpleKey(); simpleKeyAllowed = false; bool isMultiline = false; YamlDotNet.Core.Tokens.Scalar item = (lastScalar = ScanPlainScalar(ref isMultiline)); if (isMultiline && analyzer.Check(':') && flowLevel == 0 && indent < cursor.LineOffset) { tokens.Enqueue(new Error("While scanning a multiline plain scalar, found invalid mapping.", cursor.Mark(), cursor.Mark())); } tokens.Enqueue(item); } private YamlDotNet.Core.Tokens.Scalar ScanPlainScalar(ref bool isMultiline) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; long num = indent + 1; Mark start = cursor.Mark(); Mark end = start; SimpleKey simpleKey = simpleKeys.Peek(); while (!IsDocumentIndicator()) { if (analyzer.Check('#')) { if (indent < 0 && flowLevel == 0) { plainScalarFollowedByComment = true; } break; } bool flag2 = analyzer.Check('*') && (!simpleKey.IsPossible || !simpleKey.IsRequired); while (!analyzer.IsWhiteBreakOrZero()) { if ((analyzer.Check(':') && !flag2 && (analyzer.IsWhiteBreakOrZero(1) || (flowLevel > 0 && analyzer.Check(',', 1)))) || (flowLevel > 0 && analyzer.Check(",[]{}"))) { if (flowLevel == 0 && !simpleKey.IsPossible) { tokens.Enqueue(new Error("While scanning a plain scalar value, found invalid mapping.", cursor.Mark(), cursor.Mark())); } break; } if (flag || builder2.Length > 0) { if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; flag = false; } else { builder.Append((object?)builder2); builder2.Length = 0; } } if (flowLevel > 0 && cursor.LineOffset < num) { throw new InvalidOperationException(); } builder.Append(ReadCurrentCharacter()); end = cursor.Mark(); } if (!analyzer.IsWhite() && !analyzer.IsBreak()) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (flag && cursor.LineOffset < num && analyzer.IsTab()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a plain scalar, found a tab character that violate indentation."); } if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else { isMultiline = true; if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } } if (flowLevel == 0 && cursor.LineOffset < num) { break; } } if (flag) { simpleKeyAllowed = true; } return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), ScalarStyle.Plain, start, end); } finally { ((IDisposable)builderWrapper4/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper3/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper2/*cast due to .constrained prefix*/).Dispose(); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void RemoveSimpleKey() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible && simpleKey.IsRequired) { throw new SyntaxErrorException(simpleKey.Mark, simpleKey.Mark, "While scanning a simple key, could not find expected ':'."); } simpleKey.MarkAsImpossible(); } private string ScanDirectiveName(in Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, could not find expected directive name."); } if (analyzer.EndOfInput) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, found unexpected end of stream."); } if (!analyzer.IsWhiteBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, found unexpected non-alphabetical character."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void SkipWhitespaces() { while (analyzer.IsWhite()) { Skip(); } } private VersionDirective ScanVersionDirectiveValue(in Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(in start); if (!analyzer.Check('.')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, did not find expected digit or '.' character."); } Skip(); int minor = ScanVersionDirectiveNumber(in start); return new VersionDirective(new Version(major, minor), start, start); } private TagDirective ScanTagDirectiveValue(in Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace."); } SkipWhitespaces(); string prefix = ScanTagUri(null, start); if (!analyzer.IsWhiteBreakOrZero()) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace or line break."); } return new TagDirective(handle, prefix, start, start); } private string ScanTagUri(string? head, Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; if (head != null && head.Length > 1) { builder.Append(head.Substring(1)); } while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$.!~*'()[]%") || (analyzer.Check(',') && !analyzer.IsBreak(1))) { if (analyzer.Check('%')) { builder.Append(ScanUriEscapes(in start)); } else if (analyzer.Check('+')) { builder.Append(' '); Skip(); } else { builder.Append(ReadCurrentCharacter()); } } if (builder.Length == 0) { return string.Empty; } string text = builder.ToString(); if (Polyfills.EndsWith(text, ',')) { throw new SyntaxErrorException(cursor.Mark(), cursor.Mark(), "Unexpected comma at end of tag"); } return text; } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private string ScanUriEscapes(in Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find URI escaped octet."); } int num2 = (analyzer.AsHex(1) << 4) + analyzer.AsHex(2); if (num == 0) { num = (((num2 & 0x80) == 0) ? 1 : (((num2 & 0xE0) == 192) ? 2 : (((num2 & 0xF0) == 224) ? 3 : (((num2 & 0xF8) == 240) ? 4 : 0)))); if (num == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect leading UTF-8 octet."); } array = new byte[num]; } else if ((num2 & 0xC0) != 128) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect trailing UTF-8 octet."); } array[count++] = (byte)num2; Skip(); Skip(); Skip(); } while (--num > 0); string text = Encoding.UTF8.GetString(array, 0, count); if (text.Length == 0 || text.Length > 2) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect UTF-8 sequence."); } return text; } private string ScanTagHandle(bool isDirective, Mark start) { if (!analyzer.Check('!')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find expected '!'."); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append(ReadCurrentCharacter()); while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (analyzer.Check('!')) { builder.Append(ReadCurrentCharacter()); } else if (isDirective && (builder.Length != 1 || builder[0] != '!')) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag directive, did not find expected '!'."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private int ScanVersionDirectiveNumber(in Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, found extremely long version number."); } num = num * 10 + analyzer.AsDigit(); Skip(); } if (num2 == 0) { throw new SyntaxErrorException(in start, cursor.Mark(), "While scanning a %YAML directive, did not find expected version number."); } return num; } private void SaveSimpleKey() { bool isRequired = flowLevel == 0 && indent == cursor.LineOffset; if (simpleKeyAllowed) { SimpleKey item = new SimpleKey(isRequired, tokensParsed + tokens.Count, cursor); RemoveSimpleKey(); simpleKeys.Pop(); simpleKeys.Push(item); } } } internal class SemanticErrorException : YamlException { public SemanticErrorException(string message) : base(message) { } public SemanticErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SemanticErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class SimpleKey { private readonly Cursor cursor; public bool IsPossible { get; private set; } public bool IsRequired { get; } public int TokenNumber { get; } public long Index => cursor.Index; public long Line => cursor.Line; public long LineOffset => cursor.LineOffset; public Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public SimpleKey() { cursor = new Cursor(); } public SimpleKey(bool isRequired, int tokenNumber, Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new Cursor(cursor); } } internal sealed class StringLookAheadBuffer : ILookAheadBuffer, IResettable { public string Value { get; set; } = string.Empty; public int Position { get; private set; } public int Length => Value.Length; public bool EndOfInput => IsOutside(Position); public char Peek(int offset) { int index = Position + offset; if (!IsOutside(index)) { return Value[index]; } return '\0'; } private bool IsOutside(int index) { return index >= Value.Length; } public void Skip(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } Position += length; } public bool TryReset() { Position = 0; Value = string.Empty; return true; } } internal sealed class SyntaxErrorException : YamlException { public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SyntaxErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class TagDirectiveCollection : KeyedCollection { public TagDirectiveCollection() { } public TagDirectiveCollection(IEnumerable tagDirectives) { foreach (TagDirective tagDirective in tagDirectives) { Add(tagDirective); } } protected override string GetKeyForItem(TagDirective item) { return item.Handle; } public new bool Contains(TagDirective directive) { return Contains(GetKeyForItem(directive)); } } internal readonly struct TagName : IEquatable { public static readonly TagName Empty; private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of a non-specific tag"); public bool IsEmpty => value == null; public bool IsNonSpecific { get { if (!IsEmpty) { if (!(value == "!")) { return value == "?"; } return true; } return false; } } public bool IsLocal { get { if (!IsEmpty) { return Value[0] == '!'; } return false; } } public bool IsGlobal { get { if (!IsEmpty) { return !IsLocal; } return false; } } public TagName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (value.Length == 0) { throw new ArgumentException("Tag value must not be empty.", "value"); } if (IsGlobal && !Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)) { throw new ArgumentException("Global tags must be valid URIs.", "value"); } } public override string ToString() { return value ?? "?"; } public bool Equals(TagName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is TagName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(TagName left, TagName right) { return left.Equals(right); } public static bool operator !=(TagName left, TagName right) { return !(left == right); } public static bool operator ==(TagName left, string right) { return object.Equals(left.value, right); } public static bool operator !=(TagName left, string right) { return !(left == right); } public static implicit operator TagName(string? value) { if (value != null) { return new TagName(value); } return Empty; } } internal sealed class Version { public int Major { get; } public int Minor { get; } public Version(int major, int minor) { if (major < 0) { throw new ArgumentOutOfRangeException("major", $"{major} should be >= 0"); } Major = major; if (minor < 0) { throw new ArgumentOutOfRangeException("minor", $"{minor} should be >= 0"); } Minor = minor; } public override bool Equals(object? obj) { if (obj is Version version && Major == version.Major) { return Minor == version.Minor; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Major.GetHashCode(), Minor.GetHashCode()); } } internal class YamlException : Exception { public Mark Start { get; } public Mark End { get; } public YamlException(string message) : this(in Mark.Empty, in Mark.Empty, message) { } public YamlException(in Mark start, in Mark end, string message) : this(in start, in end, message, null) { } public YamlException(in Mark start, in Mark end, string message, Exception? innerException) : base(message, innerException) { Start = start; End = end; } public YamlException(string message, Exception inner) : this(in Mark.Empty, in Mark.Empty, message, inner) { } public override string ToString() { return $"({Start}) - ({End}): {Message}"; } } } namespace YamlDotNet.Core.Tokens { internal class Anchor : Token { public AnchorName Value { get; } public Anchor(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public Anchor(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class AnchorAlias : Token { public AnchorName Value { get; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class BlockEnd : Token { public BlockEnd() : this(in Mark.Empty, in Mark.Empty) { } public BlockEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockEntry : Token { public BlockEntry() : this(in Mark.Empty, in Mark.Empty) { } public BlockEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockMappingStart : Token { public BlockMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockSequenceStart : Token { public BlockSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Comment : Token { public string Value { get; } public bool IsInline { get; } public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class DocumentEnd : Token { public DocumentEnd() : this(in Mark.Empty, in Mark.Empty) { } public DocumentEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class DocumentStart : Token { public DocumentStart() : this(in Mark.Empty, in Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : base(in start, in end) { } } internal class Error : Token { public string Value { get; } public Error(string value, Mark start, Mark end) : base(in start, in end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(in Mark.Empty, in Mark.Empty) { } public FlowEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingStart : Token { public FlowMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceEnd : Token { public FlowSequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceStart : Token { public FlowSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Key : Token { public Key() : this(in Mark.Empty, in Mark.Empty) { } public Key(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Scalar : Token { public bool IsKey { get; set; } public string Value { get; } public ScalarStyle Style { get; } public Scalar(string value) : this(value, ScalarStyle.Any) { } public Scalar(string value, ScalarStyle style) : this(value, style, Mark.Empty, Mark.Empty) { } public Scalar(string value, ScalarStyle style, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class StreamEnd : Token { public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Tag : Token { public string Handle { get; } public string Suffix { get; } public Tag(string handle, string suffix) : this(handle, suffix, Mark.Empty, Mark.Empty) { } public Tag(string handle, string suffix, Mark start, Mark end) : base(in start, in end) { Handle = handle ?? throw new ArgumentNullException("handle"); Suffix = suffix ?? throw new ArgumentNullException("suffix"); } } internal class TagDirective : Token { private static readonly Regex TagHandlePattern = new Regex("^!([0-9A-Za-z_\\-]*!)?$", RegexOptions.Compiled); public string Handle { get; } public string Prefix { get; } public TagDirective(string handle, string prefix) : this(handle, prefix, Mark.Empty, Mark.Empty) { } public TagDirective(string handle, string prefix, Mark start, Mark end) : base(in start, in end) { if (string.IsNullOrEmpty(handle)) { throw new ArgumentNullException("handle", "Tag handle must not be empty."); } if (!TagHandlePattern.IsMatch(handle)) { throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); } Handle = handle; if (string.IsNullOrEmpty(prefix)) { throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); } Prefix = prefix; } public override bool Equals(object? obj) { if (obj is TagDirective tagDirective && Handle.Equals(tagDirective.Handle)) { return Prefix.Equals(tagDirective.Prefix); } return false; } public override int GetHashCode() { return Handle.GetHashCode() ^ Prefix.GetHashCode(); } public override string ToString() { return Handle + " => " + Prefix; } } internal abstract class Token { public Mark Start { get; } public Mark End { get; } protected Token(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Value : Token { public Value() : this(in Mark.Empty, in Mark.Empty) { } public Value(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class VersionDirective : Token { public Version Version { get; } public VersionDirective(Version version) : this(version, Mark.Empty, Mark.Empty) { } public VersionDirective(Version version, Mark start, Mark end) : base(in start, in end) { Version = version; } public override bool Equals(object? obj) { if (obj is VersionDirective versionDirective) { return Version.Equals(versionDirective.Version); } return false; } public override int GetHashCode() { return Version.GetHashCode(); } } } namespace YamlDotNet.Core.ObjectPool { internal class DefaultObjectPool : ObjectPool where T : class { private readonly Func createFunc; private readonly Func returnFunc; private readonly int maxCapacity; private int numItems; private protected readonly ConcurrentQueue items = new ConcurrentQueue(); private protected T? fastItem; public DefaultObjectPool(IPooledObjectPolicy policy) : this(policy, Environment.ProcessorCount * 2) { } public DefaultObjectPool(IPooledObjectPolicy policy, int maximumRetained) { createFunc = policy.Create; returnFunc = policy.Return; maxCapacity = maximumRetained - 1; } public override T Get() { T result = fastItem; if (result == null || Interlocked.CompareExchange(ref fastItem, null, result) != result) { if (items.TryDequeue(out result)) { Interlocked.Decrement(ref numItems); return result; } return createFunc(); } return result; } public override void Return(T obj) { ReturnCore(obj); } private protected bool ReturnCore(T obj) { if (!returnFunc(obj)) { return false; } if (fastItem != null || Interlocked.CompareExchange(ref fastItem, obj, null) != null) { if (Interlocked.Increment(ref numItems) <= maxCapacity) { items.Enqueue(obj); return true; } Interlocked.Decrement(ref numItems); return false; } return true; } } internal class DefaultPooledObjectPolicy : IPooledObjectPolicy where T : class, new() { public T Create() { return new T(); } public bool Return(T obj) { if (obj is IResettable resettable) { return resettable.TryReset(); } return true; } } internal interface IPooledObjectPolicy where T : notnull { T Create(); bool Return(T obj); } internal interface IResettable { bool TryReset(); } internal abstract class ObjectPool where T : class { public abstract T Get(); public abstract void Return(T obj); } internal static class ObjectPool { public static ObjectPool Create(IPooledObjectPolicy? policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy()); } public static ObjectPool Create(int maximumRetained, IPooledObjectPolicy? policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy(), maximumRetained); } } [DebuggerStepThrough] internal static class StringBuilderPool { internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ObjectPool pool; public BuilderWrapper(StringBuilder builder, ObjectPool pool) { Builder = builder; this.pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { pool.Return(Builder); } } private static readonly ObjectPool Pool = ObjectPool.Create(new StringBuilderPooledObjectPolicy { InitialCapacity = 16, MaximumRetainedCapacity = 1024 }); public static BuilderWrapper Rent() { StringBuilder builder = Pool.Get(); return new BuilderWrapper(builder, Pool); } } internal class StringBuilderPooledObjectPolicy : IPooledObjectPolicy { public int InitialCapacity { get; set; } = 100; public int MaximumRetainedCapacity { get; set; } = 4096; public StringBuilder Create() { return new StringBuilder(InitialCapacity); } public bool Return(StringBuilder obj) { if (obj.Capacity > MaximumRetainedCapacity) { return false; } obj.Clear(); return true; } } internal static class StringLookAheadBufferPool { internal readonly struct BufferWrapper : IDisposable { public readonly StringLookAheadBuffer Buffer; private readonly ObjectPool pool; public BufferWrapper(StringLookAheadBuffer buffer, ObjectPool pool) { Buffer = buffer; this.pool = pool; } public override string ToString() { return Buffer.ToString(); } public void Dispose() { pool.Return(Buffer); } } private static readonly ObjectPool Pool = ObjectPool.Create(new DefaultPooledObjectPolicy()); public static BufferWrapper Rent(string value) { StringLookAheadBuffer stringLookAheadBuffer = Pool.Get(); stringLookAheadBuffer.Value = value; return new BufferWrapper(stringLookAheadBuffer, Pool); } } } namespace YamlDotNet.Core.Events { internal sealed class AnchorAlias : ParsingEvent { internal override EventType Type => EventType.Alias; public AnchorName Value { get; } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new YamlException(in start, in end, "Anchor value must not be empty."); } Value = value; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Alias [value = {Value}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class Comment : ParsingEvent { public string Value { get; } public bool IsInline { get; } internal override EventType Type => EventType.Comment; public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value; IsInline = isInline; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } public override string ToString() { return (IsInline ? "Inline" : "Block") + " Comment [" + Value + "]"; } } internal sealed class DocumentEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.DocumentEnd; public bool IsImplicit { get; } public DocumentEnd(bool isImplicit, Mark start, Mark end) : base(in start, in end) { IsImplicit = isImplicit; } public DocumentEnd(bool isImplicit) : this(isImplicit, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document end [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class DocumentStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.DocumentStart; public TagDirectiveCollection? Tags { get; } public VersionDirective? Version { get; } public bool IsImplicit { get; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit, Mark start, Mark end) : base(in start, in end) { Version = version; Tags = tags; IsImplicit = isImplicit; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit) : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : this(null, null, isImplicit: true, start, end) { } public DocumentStart() : this(null, null, isImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } internal interface IParsingEventVisitor { void Visit(AnchorAlias e); void Visit(StreamStart e); void Visit(StreamEnd e); void Visit(DocumentStart e); void Visit(DocumentEnd e); void Visit(Scalar e); void Visit(SequenceStart e); void Visit(SequenceEnd e); void Visit(MappingStart e); void Visit(MappingEnd e); void Visit(Comment e); } internal class MappingEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.MappingEnd; public MappingEnd(in Mark start, in Mark end) : base(in start, in end) { } public MappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Mapping end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class MappingStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.MappingStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public MappingStyle Style { get; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public MappingStart() : this(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Any, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Mapping start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum MappingStyle { Any, Block, Flow } internal abstract class NodeEvent : ParsingEvent { public AnchorName Anchor { get; } public TagName Tag { get; } public abstract bool IsCanonical { get; } protected NodeEvent(AnchorName anchor, TagName tag, Mark start, Mark end) : base(in start, in end) { Anchor = anchor; Tag = tag; } protected NodeEvent(AnchorName anchor, TagName tag) : this(anchor, tag, Mark.Empty, Mark.Empty) { } } internal abstract class ParsingEvent { public virtual int NestingIncrease => 0; internal abstract EventType Type { get; } public Mark Start { get; } public Mark End { get; } public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Scalar : NodeEvent { internal override EventType Type => EventType.Scalar; public string Value { get; } public ScalarStyle Style { get; } public bool IsPlainImplicit { get; } public bool IsQuotedImplicit { get; } public override bool IsCanonical { get { if (!IsPlainImplicit) { return !IsQuotedImplicit; } return false; } } public bool IsKey { get; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end, bool isKey = false) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; IsKey = isKey; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, Mark.Empty, Mark.Empty) { } public Scalar(string value) : this(AnchorName.Empty, TagName.Empty, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(TagName tag, string value) : this(AnchorName.Empty, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(AnchorName anchor, TagName tag, string value) : this(anchor, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Scalar [anchor = {base.Anchor}, tag = {base.Tag}, value = {Value}, style = {Style}, isPlainImplicit = {IsPlainImplicit}, isQuotedImplicit = {IsQuotedImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.SequenceEnd; public SequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } public SequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Sequence end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.SequenceStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public SequenceStyle Style { get; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Sequence start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum SequenceStyle { Any, Block, Flow } internal sealed class StreamEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.StreamEnd; public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Stream end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class StreamStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.StreamStart; public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } public override string ToString() { return "Stream start"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } }