using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using CreatureGenetics; using CreatureGenetics.RPC; using CreatureLevelControl; using HarmonyLib; using JetBrains.Annotations; using LocalizationManager; using Microsoft.CodeAnalysis; using MonsterModifiers; using MonsterModifiers.Custom_Components; using Patches; using ServerSync; using StarLevelSystem; using StarLevelSystem.Data; using StarLevelSystem.common; using StarLevelSystem.modules; using StarLevelSystem.modules.Health; using StarLevelSystem.modules.Sizes; using TMPro; using UnityEngine; using UnityEngine.SceneManagement; 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: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("LetMeTameYou")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: CompilationRelaxations(8)] [assembly: AssemblyProduct("LetMeTameYou")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: Guid("d8b8b522-7ea7-41eb-a21a-d076e3ab8dc5")] [assembly: ComVisible(false)] [assembly: AssemblyCompany("")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Patches { internal class BetterRiding { public static void removeGrowupPatch() { MethodInfo method = AccessTools.Method(typeof(Growup), "GrowUpdate", (Type[])null, (Type[])null); Utils.RemovePatch(method, isPrefix: true, new string[1] { "Yggdrah.BetterRiding/Prefix" }); } public static void InheritOwnership(Character childChar, Character adultChar) { if ((Object)(object)childChar == (Object)null || (Object)(object)adultChar == (Object)null || (Object)(object)childChar.m_nview == (Object)null || (Object)(object)adultChar.m_nview == (Object)null || !childChar.m_nview.IsValid() || !adultChar.m_nview.IsValid()) { return; } ZDO zDO = childChar.m_nview.GetZDO(); ZDO zDO2 = adultChar.m_nview.GetZDO(); if (zDO != null && zDO2 != null) { long num = zDO.GetLong("playerID", 0L); string text = zDO.GetString("ownerName", ""); if (num != 0) { zDO2.Set("playerID", num); zDO2.Set("ownerName", text); DBG.blogDebug($"[BetterRiding] Ownership transferred to grown creature: {text} ({num})"); } } } } public class CLLC { public enum Effect_CLLC { None, Aggressive, Quick, Regenerating, Curious, Splitting, Armored } public enum Infusion_CLLC { None, Lightning, Fire, Frost, Poison, Chaos, Spirit } private static bool SetCLLCData(Character character, string key, string val) { if (Object.op_Implicit((Object)(object)character.m_nview)) { return true; } ItemDrop component = ((Component)character).gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { DBG.blogDebug("No item Drop"); return true; } Utils.addOrUpdateCustomData(component.m_itemData.m_customData, key, val); DBG.blogDebug("Added " + key + " to ItemDrop, skipping set creature with " + key + ": " + val); return false; } private static Effect_CLLC TryGetExtraEffect(Character thisChar) { if (Object.op_Implicit((Object)(object)thisChar.m_nview)) { return GetExtraEffectCreature(thisChar); } string value = ((Component)thisChar).gameObject.GetComponent().m_itemData.m_customData["ExtraEffect"]; if (!Enum.TryParse(value, out var result)) { result = Effect_CLLC.None; } return result; } private static Infusion_CLLC TryGetInfusion(Character thisChar) { if (Object.op_Implicit((Object)(object)thisChar.m_nview)) { return GetInfusionCreature(thisChar); } string value = ((Component)thisChar).gameObject.GetComponent().m_itemData.m_customData["Infusion"]; if (!Enum.TryParse(value, out var result)) { result = Infusion_CLLC.None; } return result; } public static int inheritValue(int mom_val, int dad_val) { if (mom_val != 0 || dad_val != 0) { int num = Random.Range(0, 100); if (num > 60) { DBG.blogDebugExtra("IsDadVal"); return dad_val; } if (num > 20) { DBG.blogDebugExtra("IsMomVal"); return mom_val; } DBG.blogDebugExtra("IsNoVal"); } return 0; } public static bool SetInfusionExtraEffect(GameObject go, Genetics motherGenes, bool isEgg) { DBG.blogDebug("In infusion effect combine"); Character component = ((Component)motherGenes).GetComponent(); Genetics.GeneticPkg partnerPkg = motherGenes.partnerPkg; bool flag = false; bool flag2 = false; if (API.IsExtraEffectEnabled()) { flag2 = true; } else { DBG.blogDebug("NoExtraEffectEnabled"); } if (API.IsInfusionEnabled()) { flag = true; } else { DBG.blogDebug("NoinfusionEnabled"); } if (!flag && !flag2) { DBG.blogDebug("SkippingCLLC"); return false; } Effect_CLLC extraEffectCreature = GetExtraEffectCreature(component); Infusion_CLLC infusionCreature = GetInfusionCreature(component); int level = component.GetLevel(); int lvl = partnerPkg.lvl; Effect_CLLC effect = partnerPkg.effect; Infusion_CLLC infusion = partnerPkg.infusion; Character component2; if (isEgg) { DBG.blogDebug("Set Infusion/Effect of Egg"); GameObject val = Object.Instantiate(go.GetComponent().m_grownPrefab, global::CreatureGenetics.CreatureGenetics.Root.transform); component2 = val.GetComponent(); DBG.blogDebug("Clone Char of Egg=" + Object.op_Implicit((Object)(object)component2)); ZNetView component3 = ((Component)component2).GetComponent(); if (!component3.IsValid() || !component3.IsOwner()) { ((Component)component2).gameObject.AddComponent(); } } else { component2 = go.GetComponent(); } component2.m_level = Mathf.RoundToInt((float)((level + lvl) / 2)); Effect_CLLC effect_CLLC = Effect_CLLC.None; Infusion_CLLC infusion_CLLC = Infusion_CLLC.None; int num = -1; int num2 = -1; if (global::CreatureGenetics.CreatureGenetics.allowEffectsMutation.Value) { if (flag2 && (float)Random.Range(0, 100) < global::CreatureGenetics.CreatureGenetics.MutationChanceEffects.Value) { num2 = 0; } if (flag && (float)Random.Range(0, 100) < global::CreatureGenetics.CreatureGenetics.MutationChanceEffects.Value) { num = 0; } for (int i = 0; i < 25; i++) { if (num2 != 0 && num != 0) { break; } DBG.blogDebug("i=" + i); if (num2 == 0) { API.SetExtraEffectCreature(component2); Effect_CLLC effect_CLLC2 = TryGetExtraEffect(component2); if (effect_CLLC2 != extraEffectCreature && effect_CLLC2 != effect && effect_CLLC2 != Effect_CLLC.None) { DBG.blogDebug("Effect(" + i + ")=" + effect_CLLC2); DBG.blogDebug("Has Mutation in Effect"); effect_CLLC = effect_CLLC2; num2 = 1; } } if (num == 0) { API.SetInfusionCreature(component2); Infusion_CLLC infusion_CLLC2 = TryGetInfusion(component2); if (infusion_CLLC2 != infusionCreature && infusion_CLLC2 != infusion && infusion_CLLC2 != Infusion_CLLC.None) { DBG.blogDebug("Infusion(" + i + ")=" + infusion_CLLC2); DBG.blogDebug("Has Mutation in Infusion"); infusion_CLLC = infusion_CLLC2; num = 1; } } } } if (num2 < 0) { DBG.blogDebug("inherit Effect"); effect_CLLC = (Effect_CLLC)inheritValue((int)extraEffectCreature, (int)effect); } if (num < 0) { DBG.blogDebug("inherit Infusion"); infusion_CLLC = (Infusion_CLLC)inheritValue((int)infusionCreature, (int)infusion); } if (!isEgg) { SetExtraEffectCreature(component2, effect_CLLC); SetInfusionCreature(component2, infusion_CLLC); } else { DBG.blogDebug("Effect=" + effect_CLLC); DBG.blogDebug("Infusion=" + infusion_CLLC); ItemDrop component4 = go.GetComponent(); ItemData itemData = component4.m_itemData; Utils.addOrUpdateCustomData(itemData.m_customData, "ExtraEffect", effect_CLLC.ToString()); Utils.addOrUpdateCustomData(itemData.m_customData, "Infusion", infusion_CLLC.ToString()); if ((int)effect_CLLC + (int)infusion_CLLC > 0) { return true; } } return false; } public static Effect_CLLC iDropGetEff(ItemDrop iDrop) { Effect_CLLC result = Effect_CLLC.None; if (!Object.op_Implicit((Object)(object)iDrop)) { return result; } DBG.blogDebug("Has iDrop"); if (iDrop.m_itemData.m_customData.TryGetValue("ExtraEffect", out var value)) { DBG.blogDebug("Custom Value=" + value); if (Enum.TryParse(value, out var result2)) { DBG.blogDebug("GotEffect=" + result2); result = result2; } } return result; } public static Infusion_CLLC iDropGetInf(ItemDrop iDrop) { Infusion_CLLC result = Infusion_CLLC.None; if (!Object.op_Implicit((Object)(object)iDrop)) { return result; } if (iDrop.m_itemData.m_customData.TryGetValue("Infusion", out var value)) { DBG.blogDebug("Custom Value=" + value); if (Enum.TryParse(value, out var result2)) { DBG.blogDebug("GotInfusion=" + result2); result = result2; } } return result; } public static Infusion_CLLC GetInfusionCreature(Character character) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected I4, but got Unknown return (Infusion_CLLC)API.GetInfusionCreature(character); } public static Effect_CLLC GetExtraEffectCreature(Character character) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected I4, but got Unknown return (Effect_CLLC)API.GetExtraEffectCreature(character); } public static void SetInfusionCreature(Character character, Infusion_CLLC infusion) { API.SetInfusionCreature(character, (CreatureInfusion)infusion); } public static void SetExtraEffectCreature(Character character, Effect_CLLC infusion) { API.SetExtraEffectCreature(character, (CreatureExtraEffect)infusion); } public static bool CheckCLLC() { try { return API.IsEnabled(); } catch { return false; } } [HarmonyPrefix] [HarmonyPatch(typeof(API), "SetExtraEffectCreature", new Type[] { typeof(Character), typeof(CreatureExtraEffect) })] private unsafe static bool Prefix_API_SetExtraEffect(Character character, CreatureExtraEffect effect) { return SetCLLCData(character, "ExtraEffect", ((object)(*(CreatureExtraEffect*)(&effect))/*cast due to .constrained prefix*/).ToString()); } [HarmonyPatch(typeof(API), "SetInfusionCreature", new Type[] { typeof(Character), typeof(CreatureInfusion) })] [HarmonyPrefix] private unsafe static bool Prefix_API_SetInfusionCreature(Character character, CreatureInfusion infusion) { return SetCLLCData(character, "Infusion", ((object)(*(CreatureInfusion*)(&infusion))/*cast due to .constrained prefix*/).ToString()); } } public class MonMod_CG { public enum CG_MonsterModifierTypes { StaminaSiphon, EitrSiphon, ShieldBreaker, FoodDrain, IgnoreArmor, PoisonDeath, FrostDeath, FireDeath, PersonalShield, ShieldDome, SoulEater, RemoveStatusEffect, StaggerImmune, FireInfused, PoisonInfused, FrostInfused, LightningInfused, ElementalImmunity, PhysicalImmunity, FastMovement, FastAttackSpeed, DistantDetection } public static string CreateChildModifiers(string mom_Mod, string dad_Mod, int level) { if (level <= 1) { return ""; } string text = string.Empty; if (!string.IsNullOrEmpty(mom_Mod)) { text = text + mom_Mod + (mom_Mod.EndsWith(",") ? "" : ","); } if (!string.IsNullOrEmpty(dad_Mod)) { text += dad_Mod; } DBG.blogDebug("combinedstring=" + text); text = text.TrimEnd(',', ' '); List combinedList = text.Split(new char[1] { ',' }).ToList(); List list = combinedList.Distinct().ToList(); int num = combinedList.Count - list.Count; int num2 = 0; foreach (string item in list) { num2 += (item.Contains("Immunity") ? 1 : 0); } DBG.blogDebug("immunityCount=" + num2); if (num2 > 3) { DBG.blogDebug("All Immunities, adding one dupe"); num++; } combinedList.Remove(""); DBG.blogDebug("count=" + combinedList.Count + "dups:=" + num); if (combinedList.Count - num < level - 1) { addNewMonMod(ref combinedList, level + num); } int num3 = 0; if (global::CreatureGenetics.CreatureGenetics.allowEffectsMutation.Value && (float)Random.Range(0, 100) < global::CreatureGenetics.CreatureGenetics.MutationChanceEffects.Value) { num3 = 1; addNewMonMod(ref combinedList, level + num, mutation: true); } int num4 = combinedList.Count; int i = num3; while (i < level - 1 + num) { int index = Random.Range(i, num4); string value = combinedList[i]; combinedList[i] = combinedList[index]; combinedList[index] = value; if (num2 > 3 && combinedList[i].Contains("Immunity")) { DBG.blogDebug("Immunity string(" + i + ")=" + string.Join(",", combinedList.ToArray())); int num5 = combinedList.RemoveAll((string x) => x == combinedList[i]); num -= num5; num4 -= num5; num2--; } DBG.blogDebug("shuffled string(" + i + ":count:" + num4 + ")=" + string.Join(",", combinedList.ToArray())); int num6 = i + 1; i = num6; } list = combinedList.Distinct().ToList(); DBG.blogDebug("distinct string=" + string.Join(",", list.ToArray())); string text2 = string.Join(",", list.Take(level - 1).ToArray()); DBG.blogDebug("cutsring=" + text2); return text2; } private static List internal_RollModifiers(int amount) { List list = new List(); try { MethodInfo method = typeof(ModifierUtils).GetMethod("RollRandomModifiers", BindingFlags.Static | BindingFlags.Public); object obj = method.Invoke(null, new object[1] { amount }); foreach (object item in (IEnumerable)obj) { list.Add(item.ToString()); } } catch (Exception ex) { DBG.blogDebug("Roll Mon Mod Error: " + ex.Message); } return list; } private static void addNewMonMod(ref List combinedList, int level, bool mutation = false) { bool flag = false; if (mutation) { DBG.blogDebug("mutation combindlist=" + string.Join(",", combinedList.ToArray())); for (int i = 0; i < 5; i++) { if (!mutation) { break; } List list = internal_RollModifiers(7); foreach (string item in list) { DBG.blogDebug("typeM=" + item); if (!combinedList.Contains(item.ToString())) { combinedList.Insert(0, item.ToString()); mutation = false; break; } } } if (!mutation) { DBG.blogDebug("Mutation in MonMod: added " + combinedList[0]); } else { DBG.blogDebug("Failed Mutation in MonMod"); } } for (int j = 0; j < 15; j++) { DBG.blogDebug("(" + j + ") combindlist=" + string.Join(",", combinedList.ToArray())); if (combinedList.Count >= level - 1) { flag = true; DBG.blogDebug("filledlist"); break; } List list2 = internal_RollModifiers(level - combinedList.Count - 1); foreach (string item2 in list2) { DBG.blogDebug("type=" + item2); if (!combinedList.Contains(item2.ToString())) { combinedList.Add(item2.ToString()); } } } if (!flag) { combinedList = internal_RollModifiers(level - 1); DBG.blogDebug("backup combindlist=" + string.Join(",", combinedList.ToArray())); } } public static void SetModifiers(Character character, string MonMod) { MonsterModifier val = default(MonsterModifier); if (((Component)character).TryGetComponent(ref val)) { if (Object.op_Implicit((Object)(object)val.character)) { DBG.blogDebug("MonMod has started"); } character.m_nview.GetZDO().Set("modifiers", MonMod); DBG.blogDebug("MonMod has been set"); DBG.blogDebug("MonMod is:" + character.m_nview.GetZDO().GetString("modifiers", string.Empty)); } else { DBG.blogDebug("No Mon Mod"); } } public static string getModifiers(Character character) { string text = ""; MonsterModifier val = default(MonsterModifier); if (((Component)character).TryGetComponent(ref val)) { text = string.Join(",", val.Modifiers); DBG.blogDebug("got modifiers from component: " + text); } else { text = character.m_nview.GetZDO().GetString("modifiers", string.Empty) ?? ""; DBG.blogDebug("got modifiers from zdo: " + text); } return text; } } public class SLS_CG { public enum ModifierType { Major, Minor, Boss } public static string getModifiers(Character character) { Dictionary creaturesModifiers = API.GetCreaturesModifiers(character); DBG.blogDebug("SLS found " + creaturesModifiers.Count + " modifiers:"); string text = ""; foreach (KeyValuePair item in creaturesModifiers) { DBG.blogDebugExtra("SLS Modifier=" + item.Key + ":" + item.Value); if (item.Key == "None") { DBG.blogDebugExtra("SLS skip Modifier: " + item.Key); continue; } text = text + item.Key + ":" + item.Value + ","; } if (text.Length > 1) { text.Trim(',', ' '); } DBG.blogDebug("SLS_Modifiers=" + text); return text; } public static void SetModifiers(Character character, string SLS_Str) { if ((SLS_Str ?? "") == "") { DBG.blogDebug("No Modifiers to set, skipping"); return; } List list = SLS_Str.Split(new char[1] { ',' }).ToList(); for (int i = 0; i < list.Count; i++) { string[] array = list[i].Split(new char[1] { ':' }); if (array.Length < 2) { array = new string[2] { array[0], "0" }; } if (!int.TryParse(array[1], out var result)) { DBG.blogDebug("Value not valid int:" + array[1]); result = 0; } DBG.blogDebug("Attempting to add sls mod:" + string.Join(",", array)); API.AddModifierToTargetCreature(character, array[0], result, i == list.Count - 1); DBG.blogDebug("Added sls mod:" + string.Join(",", array)); DBG.blogDebug("current Modifiers=" + getModifiers(character)); } } public static string CreateChildModifiers(string mom_SLS, string dad_SLS, int level) { if (level <= 1) { return ""; } string text = string.Empty; int[] array = new int[3]; int[] array2 = new int[3]; if (!string.IsNullOrEmpty(mom_SLS)) { text = text + mom_SLS + (mom_SLS.EndsWith(",") ? "" : ","); array[0] = mom_SLS.Count((char x) => x == '0'); array[1] = mom_SLS.Count((char x) => x == '1'); array[2] = mom_SLS.Count((char x) => x == '2'); Array.Copy(array, array2, array.Length); } if (!string.IsNullOrEmpty(dad_SLS)) { text += dad_SLS; array[0] = Math.Max(array[0], dad_SLS.Count((char x) => x == '0')); array[1] = Math.Max(array[1], dad_SLS.Count((char x) => x == '1')); array[2] = Math.Max(array[2], dad_SLS.Count((char x) => x == '2')); array2[0] = Math.Min(array2[0], dad_SLS.Count((char x) => x == '0')); array2[1] = Math.Min(array2[1], dad_SLS.Count((char x) => x == '1')); array2[2] = Math.Min(array2[2], dad_SLS.Count((char x) => x == '2')); } else { array2 = new int[3]; } DBG.blogDebug("SLS: All Possible Modifiers=" + text); int[] values = new int[3] { Math.Max(ValConfig.MaxMajorModifiersPerCreature.Value, array[0]), Math.Max(ValConfig.MaxMinorModifiersPerCreature.Value, array[1]), Math.Max(ValConfig.MaxBossModifiersPerBoss.Value, array[2]) }; DBG.blogDebugExtra("currentParentMods=" + string.Join(",", array)); DBG.blogDebugExtra("minParentMods=" + string.Join(",", array2)); DBG.blogDebugExtra("maxMods=" + string.Join(",", values)); text = text.TrimEnd(',', ' '); List list = text.Split(new char[1] { ',' }).ToList(); list.Remove(""); int count = list.Count; string[][] array3 = new string[3][] { list.Where((string x) => x.Contains("0")).Distinct().ToArray(), list.Where((string x) => x.Contains("1")).Distinct().ToArray(), list.Where((string x) => x.Contains("2")).Distinct().ToArray() }; DBG.blogDebugExtra("Major modsMatrix[0]=" + string.Join(",", array3[0])); DBG.blogDebugExtra("Minor modsMatrix[1]=" + string.Join(",", array3[1])); DBG.blogDebugExtra("Boss modsMatrix[2]=" + string.Join(",", array3[2])); List newMods = new List(); int num = ((array[2] <= 0) ? 1 : 2); int num2 = Random.Range(0, num - 1); bool flag = global::CreatureGenetics.CreatureGenetics.allowEffectsMutation.Value && (float)Random.Range(0, 100) < global::CreatureGenetics.CreatureGenetics.MutationChanceEffects.Value; if (flag) { ModifierType modifierType = (ModifierType)num2; DBG.blogDebug("Has add mutation of type=" + modifierType); array2[num2] = array[num2]; } for (int num3 = 0; num3 < 3; num3++) { ModifierType modifierType; if (array[num3] == 0) { modifierType = (ModifierType)num3; DBG.blogDebugExtra("none of type=" + modifierType); continue; } count = array3[num3].Length; if (count > array2[num3]) { modifierType = (ModifierType)num3; DBG.blogDebugExtra("shuffle list of type=" + modifierType); for (int num4 = 0; num4 < count; num4++) { int num5 = Random.Range(num4, count); ref string reference = ref array3[num3][num4]; ref string reference2 = ref array3[num3][num5]; string text2 = array3[num3][num5]; string text3 = array3[num3][num4]; reference = text2; reference2 = text3; } DBG.blogDebugExtra("shuffled list is=" + string.Join(",", array3[num3])); } else { modifierType = (ModifierType)num3; DBG.blogDebugExtra("did not shuffle list of type=" + modifierType); } count = array[num3]; modifierType = (ModifierType)num3; DBG.blogDebugExtra("count of " + modifierType.ToString() + "=" + count); for (int num6 = 0; num6 < count; num6++) { if (num6 < array2[num3]) { DBG.blogDebugExtra("Adding 100%: " + array3[num3][num6]); newMods.Add(array3[num3][num6]); } else if (Random.Range(0, 100) < 100 - 25 / (array[num3] - num6)) { DBG.blogDebugExtra("Adding chance: " + array3[num3][num6]); newMods.Add(array3[num3][num6]); } else { DBG.blogDebugExtra("Failed chance: " + array3[num3][num6]); } } } if (newMods.Count > 0 && global::CreatureGenetics.CreatureGenetics.allowEffectsMutation.Value && (float)Random.Range(0, 100) < global::CreatureGenetics.CreatureGenetics.MutationChanceEffects.Value) { int num7 = 0; DBG.blogDebug("Has change mutation"); if (newMods.Count > 1) { num7 = Random.Range(0, newMods.Count - 1); } DBG.blogDebugExtra("Changing: " + newMods[num7]); mutateSLS(ref newMods, num7, ref text); DBG.blogDebugExtra("Updated Modifier List:" + text); } if (flag) { ModifierType modifierType = (ModifierType)num2; DBG.blogDebug("Adding mutation of type: " + modifierType); addNewSLS(ref newMods, num2, text); } ShuffleClass.Shuffle((IList)newMods, false); return string.Join(",", newMods.ToArray()); } private static void mutateSLS(ref List newMods, int mutateNum, ref string combinedList) { char c = newMods[mutateNum].Trim(',', ' ').Last(); int num = 1; switch (c) { case '0': num = 0; break; case '2': num = 2; break; } List possibleModifiers = API.GetPossibleModifiers(num); ShuffleClass.Shuffle((IList)possibleModifiers, false); foreach (string item in possibleModifiers) { DBG.blogDebugExtra("Attempting to change effect:" + item); if (!combinedList.Contains(item)) { DBG.blogDebug("Changed effect from:" + newMods[mutateNum] + " to :" + item); newMods[mutateNum] = item + ":" + num; combinedList = combinedList + "," + item + ":" + num; break; } } } private static void addNewSLS(ref List newMods, int mutateType, string combinedList) { List possibleModifiers = API.GetPossibleModifiers(mutateType); ShuffleClass.Shuffle((IList)possibleModifiers, false); foreach (string item in possibleModifiers) { DBG.blogDebugExtra("Attempting to add effect:" + item); if (!combinedList.Contains(item)) { DBG.blogDebug("Added effect:" + item); newMods.Add(item + ":" + mutateType); break; } } } public static void copyColorEggCache(Character childChar, Character adultChar) { try { CharacterCacheEntry andSetLocalCache = CompositeLazyCache.GetAndSetLocalCache(childChar, 0, (Dictionary)null, (List)null, false); ColorDef colorization = Colorization.DetermineCharacterColorization(adultChar, childChar.m_level - 1); andSetLocalCache.Colorization = colorization; ColorDef colorization2 = andSetLocalCache.Colorization; DBG.blogDebugExtra("EggGrow Child Character color set to:" + colorization2.Hue + "," + colorization2.Saturation + "," + colorization2.Value + "," + colorization2.IsEmissive); } catch { DBG.blogDebugExtra("EggGrow Child Character color FAILED"); } } public static int inheritValue(int mom_val, int dad_val) { if (mom_val != 0 || dad_val != 0) { int num = Random.Range(0, 100); if (num > 60) { DBG.blogDebugExtra("IsDadVal"); return dad_val; } if (num > 20) { DBG.blogDebugExtra("IsMomVal"); return mom_val; } DBG.blogDebugExtra("IsNoVal"); } return 0; } [HarmonyPostfix] [HarmonyPatch(typeof(HealthModifications), "ApplyHealthModifications")] private static void Postfix_ApplyHealthModifications(Character chara) { try { Genetics genetics = default(Genetics); if (global::CreatureGenetics.CreatureGenetics.useDNATraits.Value && Object.op_Implicit((Object)(object)chara) && ((Component)chara).gameObject.TryGetComponent(ref genetics)) { float num = chara.GetHealth() / chara.GetMaxHealth(); float maxHealth = chara.GetMaxHealth(); float num2 = Math.Max((float)genetics.Health / 128f, 0.1f); DBG.blogDebug("SLS: CurrentHealth:" + chara.GetHealth() + ", MaxHealth: " + maxHealth + ",DNA Multi: " + num2); float num3 = maxHealth * num2; chara.SetMaxHealth(num3); DBG.blogDebug("SLS: NewMaxHealth:" + chara.GetMaxHealth()); if (num < 1f) { chara.SetHealth(num3 * num); } else { chara.Heal(num3, true); } } } catch { } } [HarmonyPrefix] [HarmonyPatch(typeof(SetChildLevel), "SetupChildCharacter")] private static void Prefix_SetupChildCharacter(Character chara, ref Procreation proc) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown CharacterCacheEntry andSetLocalCache = CompositeLazyCache.GetAndSetLocalCache(chara, 0, (Dictionary)null, (List)null, false); CharacterCacheEntry cacheEntry = CompositeLazyCache.GetCacheEntry(proc.m_character); andSetLocalCache.Colorization = cacheEntry.Colorization; ColorDef colorization = andSetLocalCache.Colorization; DBG.blogDebugExtra("Child Character color set to:" + colorization.Hue + "," + colorization.Saturation + "," + colorization.Value + "," + colorization.IsEmissive); proc = new Procreation(); proc.m_character = chara; } [HarmonyPostfix] [HarmonyPatch(typeof(Colorization), "ApplyLevelVisual")] private static void Postfix_ApplyLevelVisual(Character charc) { try { Genetics genetics = default(Genetics); if (global::CreatureGenetics.CreatureGenetics.useDNAColor.Value && Object.op_Implicit((Object)(object)charc) && ((Component)charc).gameObject.TryGetComponent(ref genetics)) { DBG.blogDebugExtra("Set SLS Level Render"); genetics.postLevelEffect = true; genetics.setCompleteColor(postLevel: true); } } catch { } } [HarmonyPrefix] [HarmonyPatch(typeof(SizeModifications), "SetSizeModification")] private static bool Prefix_ApplySizeNew(GameObject obj, ZNetView zview, CharacterCacheEntry characterCache, bool update = false, float bonus = 0f) { //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_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_0027: Unknown result type (might be due to invalid IL or missing references) Vector3 vec = zview.m_zdo.GetVec3(DataObjects.SLS_SIZE, Vector3.zero); DBG.blogDebugExtra("SLS PreSize=" + obj.transform.localScale.x + ", zdo=" + vec.x); return true; } [HarmonyPatch(typeof(SizeModifications), "SetSizeModification")] [HarmonyPostfix] private unsafe static void Postfix_ApplySizeNew(GameObject obj, ZNetView zview, CharacterCacheEntry characterCache) { //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_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_0027: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: 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_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) Vector3 vec = zview.m_zdo.GetVec3(DataObjects.SLS_SIZE, Vector3.zero); DBG.blogDebugExtra("SLS PostSize=" + obj.transform.localScale.x + ", zdo=" + vec.x); Genetics genetics = default(Genetics); if (!obj.TryGetComponent(ref genetics) || genetics.lateSetInit) { return; } DBG.blogDebugExtra("Genetics Size=" + genetics.Size); bool flag = characterCache.CreatureModifiers.ContainsKey("Big"); if (flag) { DBG.blogDebugExtra("Has Big=" + obj.transform.localScale.x); } else { DBG.blogDebugExtra("No Big=" + obj.transform.localScale.x); } if (genetics.sls_sizes.Count > 0) { int num = 0; foreach (float[] sls_size in genetics.sls_sizes) { num++; } float[] array = genetics.sls_sizes[genetics.sls_sizes.Count - 1]; float num2 = array[0]; bool flag2 = array[1] != 0f; DBG.blogDebugExtra("last size=" + num2); if (flag || !flag2) { DBG.blogDebugExtra("Should Update size"); genetics.sls_sizes.Add(new float[2] { vec.x, flag ? 1 : 0 }); genetics.sls_size = vec.x; } else { DBG.blogDebugExtra("Should not update size"); ((Vector3)(ref vec))..ctor(num2, num2, num2); } foreach (float[] sls_size2 in genetics.sls_sizes) { DBG.blogDebugExtra("post-size " + num + ": " + sls_size2[0] + sls_size2[1]); num++; } } else { genetics.sls_sizes.Add(new float[2] { vec.x, flag ? 1 : 0 }); genetics.sls_size = vec.x; } int num3 = (int)Mathf.Clamp((float)genetics.Size, (float)global::CreatureGenetics.CreatureGenetics.sizeMin256, (float)global::CreatureGenetics.CreatureGenetics.sizeMax256); DBG.blogDebugExtra("clampsize=" + num3); Vector3 val = vec * ((float)(num3 * num3) / 130000f + (float)num3 / 200f + 0.25f); Vector3 val2 = val; DBG.blogDebug("NewSize Post SLS=" + ((object)(*(Vector3*)(&val2))/*cast due to .constrained prefix*/).ToString()); obj.transform.localScale = val; } } } namespace CreatureGenetics { internal class GeneticsPatches { [HarmonyPatch(typeof(Procreation), "Procreate")] public static class InterceptProcreationFindMates { private static int CheckMates(int result, Procreation _proc) { DBG.blogDebug($"in CheckMates for:{((Object)_proc).name} with existing mate {result}"); string key = ((Object)_proc).name.Replace("(Clone)", ""); if (!CreatureGenetics.customGeneticsList.TryGetValue(key, out var value)) { return result; } return GetGeneticInst(result, _proc, value, procOnly: true); } private static int AddMates(int result, Procreation _proc) { DBG.blogDebug($"in AddMates for:{((Object)_proc).name} with existing mate {result}"); GameObject myPrefab = _proc.m_myPrefab; bool num = myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab); myPrefab = _proc.m_offspringPrefab; if (num | (myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab))) { DBG.blogDebug("Init Proc Prefabs"); InitProcPrefabs(_proc); } CreatureGenetics.GeneticsConfig geneticsConfig = SetUpProcPrefabs(_proc); if (geneticsConfig == null) { return result; } return GetGeneticInst(result, _proc, geneticsConfig); } private static GameObject OnCreateChild(GameObject child, Procreation _proc) { DBG.blogDebug("in create child"); Character component = child.GetComponent(); Character component2 = ((Component)_proc).gameObject.GetComponent(); EggGrow component3 = child.GetComponent(); if (!Object.op_Implicit((Object)(object)component) && !Object.op_Implicit((Object)(object)component3)) { DBG.blogWarning("Procreation, No Child"); return child; } if (!Object.op_Implicit((Object)(object)component2)) { DBG.blogWarning("No Parent, setting tame and level manually"); if (Object.op_Implicit((Object)(object)component)) { component.SetTamed(true); component.SetLevel(1); } if (Object.op_Implicit((Object)(object)component3)) { child.GetComponent().SetQuality(0); } return child; } Genetics genetics = default(Genetics); if (!child.gameObject.TryGetComponent(ref genetics)) { DBG.blogDebug("Adding Genes"); genetics = child.gameObject.AddComponent(); } DBG.blogDebug("Attempting Custom Procreation"); genetics.SetCreature(component2); DBG.blogDebug("Finsihed Custom Procreation"); return child; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo procreationHook = AccessTools.DeclaredMethod(typeof(InterceptProcreationFindMates), "OnCreateChild", (Type[])null, (Type[])null); MethodInfo addMatesHook = AccessTools.DeclaredMethod(typeof(InterceptProcreationFindMates), "AddMates", (Type[])null, (Type[])null); MethodInfo checkMatesHook = AccessTools.DeclaredMethod(typeof(InterceptProcreationFindMates), "CheckMates", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First((MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); MethodInfo getNrOfInstances = typeof(SpawnSystem).GetMethods().First((MethodInfo m) => m.Name == "GetNrOfInstances" && m.GetParameters().Length == 5); List codes = new List(instructions); bool setCheckMates = false; bool setAddMates = true; bool setProcHook = true; for (int i = 0; i < codes.Count; i++) { if (CodeInstructionExtensions.Calls(codes[i], getNrOfInstances)) { if (setAddMates && i + 1 < codes.Count && codes[i + 1].opcode.Name.StartsWith("ldarg")) { CodeInstruction stloc = codes[i + 1]; yield return codes[i]; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)addMatesHook); yield return stloc; setCheckMates = true; setAddMates = false; i++; continue; } if (setCheckMates && i + 2 < codes.Count && codes[i + 1].opcode.Name.StartsWith("stloc") && codes[i + 2].opcode.Name.StartsWith("ldarg")) { CodeInstruction stloc2 = codes[i + 1]; yield return codes[i]; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)checkMatesHook); yield return stloc2; setCheckMates = false; i++; continue; } } else if (setProcHook && codes[i].opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(codes[i], (MemberInfo)instantiator)) { yield return codes[i]; yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)procreationHook); i++; setProcHook = false; } yield return codes[i]; } } } [HarmonyPatch(typeof(EggGrow), "GrowUpdate")] public static class InterceptEggGrowup { private static GameObject OnEggGrowup(GameObject adult, EggGrow growup) { DBG.blogDebug("inEggGrowup"); try { DBG.blogDebug("EggGrow adult=" + ((Object)adult).name); Character component = adult.GetComponent(); ItemDrop component2 = ((Component)growup).GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { DBG.blogWarning("Growup, No Adult"); return adult; } component.SetTamed(growup.m_tamed); if (CreatureGenetics.useSLS) { DBG.blogDebug("Has SLS, Reducing Quality"); ItemData itemData = component2.m_itemData; itemData.m_quality--; } component.SetLevel(component2.m_itemData.m_quality + 1); DBG.blogDebug("set lvl=" + component.m_level + ", egg+1=" + (component2.m_itemData.m_quality + 1)); DBG.blogDebug("Attempting custom Growup"); Genetics genetics = default(Genetics); if (!((Component)growup).gameObject.TryGetComponent(ref genetics)) { DBG.blogDebug("Adding Genetics to Growup"); genetics = ((Component)growup).gameObject.AddComponent(); } Growup val = default(Growup); if (CreatureGenetics.useSLS && ((Component)component).TryGetComponent(ref val)) { Character component3 = val.m_grownPrefab.GetComponent(); if ((Object)(object)component3 != (Object)null) { DBG.blogDebug("Attempting to grab data from full adult:" + ((Object)component3).name); SLS_CG.copyColorEggCache(component, component3); } } genetics.SetGrow(component); } catch (Exception o) { adult.GetComponent().SetTamed(true); DBG.blogWarning(o); } return adult; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo growupHook = AccessTools.DeclaredMethod(typeof(InterceptEggGrowup), "OnEggGrowup", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First((MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); foreach (CodeInstruction instruction in instructions) { yield return instruction; if (instruction.opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)instantiator)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)growupHook); } } } } [HarmonyPatch(typeof(Growup), "GrowUpdate")] public static class InterceptGrowup { private static GameObject OnGrowup(GameObject adult, Growup growup) { //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebug("inOnGrowup"); try { DBG.blogDebug("adult=" + ((Object)adult).name); Character component = adult.GetComponent(); Character component2 = ((Component)growup).gameObject.GetComponent(); if (!Object.op_Implicit((Object)(object)component)) { DBG.blogWarning("Growup, No Adult"); return adult; } if (!Object.op_Implicit((Object)(object)component2)) { DBG.blogWarning("No Growup, setting tame and level manually"); component.SetTamed(true); component.SetLevel(1); return adult; } component.SetTamed(component2.IsTamed()); component.SetLevel(component2.GetLevel()); DBG.blogDebug("Attempting custom Growup"); Genetics genetics = default(Genetics); if (!((Component)component2).gameObject.TryGetComponent(ref genetics)) { genetics = ((Component)component2).gameObject.AddComponent(); } if (CreatureGenetics.hasYBR) { BetterRiding.InheritOwnership(component2, component); } genetics.SetGrow(component); DBG.blogDebug("current size4=" + ((Component)component).transform.localScale.x); } catch (Exception o) { adult.GetComponent().SetTamed(true); DBG.blogWarning(o); } return adult; } private static IEnumerable Transpiler(IEnumerable instructions) { MethodInfo growupHook = AccessTools.DeclaredMethod(typeof(InterceptGrowup), "OnGrowup", (Type[])null, (Type[])null); MethodInfo instantiator = typeof(Object).GetMethods().First((MethodInfo m) => m.Name == "Instantiate" && m.GetParameters().Length == 3 && m.GetParameters()[1].ParameterType == typeof(Vector3) && m.GetParameters()[2].ParameterType == typeof(Quaternion) && m.ContainsGenericParameters).MakeGenericMethod(typeof(GameObject)); foreach (CodeInstruction instruction in instructions) { yield return instruction; if (instruction.opcode == OpCodes.Call && CodeInstructionExtensions.OperandIs(instruction, (MemberInfo)instantiator)) { yield return new CodeInstruction(OpCodes.Ldarg_0, (object)null); yield return new CodeInstruction(OpCodes.Call, (object)growupHook); } } } } private static float[,] InfluenceMatrix; private void Awake() { InitInfluenceMatrix(); } public static void InitInfluenceMatrix() { InfluenceMatrix = new float[6, 6] { { 0f, 0f, -0.15f, 0.15f, -0.05f, 0.35f }, { 0f, 0f, -0.05f, -0.25f, 0.2f, 0.05f }, { -0.15f, -0.05f, 0f, 0f, 0.05f, 0.2f }, { 0.15f, -0.25f, 0f, 0f, 0.35f, -0.1f }, { -0.05f, 0.2f, 0.05f, 0.35f, 0f, 0f }, { 0.35f, 0.05f, 0.2f, -0.05f, 0f, 0f } }; } public static float[,] getInfluenceMatrix() { if (InfluenceMatrix == null) { InitInfluenceMatrix(); } return InfluenceMatrix; } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "Awake")] private static void PostfixCharacterAwake(Character __instance) { try { Genetics genetics = default(Genetics); if (!((Component)__instance).gameObject.TryGetComponent(ref genetics) && ((object)__instance).GetType() != typeof(Player)) { genetics = ((Component)__instance).gameObject.AddComponent(); } genetics.modifySpeed(); } catch { } } [HarmonyPrefix] [HarmonyPatch(typeof(Character), "SetLevel")] private static void Prefix(Character __instance, ref int level) { if (Object.op_Implicit((Object)(object)((Component)__instance).gameObject.GetComponent())) { level = ((Component)__instance).gameObject.GetComponent().GetLevel(level); DBG.blogDebug("genetics level is " + level); } } public static GameObject addProcPrefToList(CreatureGenetics.GeneticsConfig genCfg, string PrefName, bool mate = true, string startPref = "", int depth = 0) { DBG.blogDebugExtra("LOOP:" + PrefName + "," + startPref + ",depth=" + depth); if (depth > 5) { DBG.blogDebug("Max depth reached with: " + PrefName); return null; } if (startPref != "") { if (PrefName == startPref) { DBG.blogDebugExtra("Finished loop starting at: " + PrefName); return null; } } else { startPref = PrefName; } string text = PrefName; if (!text.Contains("(Clone)")) { text += "(Clone)"; } if (mate) { if (!genCfg.mateNames.Contains(text)) { genCfg.mateNames.Add(text); } if (!genCfg.allProcPrefabs.Contains(text)) { genCfg.allProcPrefabs.Add(text); } return null; } GameObject prefab = ZNetScene.instance.GetPrefab(PrefName); if (!Object.op_Implicit((Object)(object)prefab)) { DBG.blogWarning("Could not find Prefab: " + text); return null; } List allProcPrefabs = genCfg.allProcPrefabs; if (Object.op_Implicit((Object)(object)prefab.GetComponent())) { if (!allProcPrefabs.Contains(text)) { DBG.blogDebug("parent added " + text + " to alloffspring of " + genCfg.PrefabName); allProcPrefabs.Add(text); } } else if (!genCfg.ProcEggPrefabs.Contains(text)) { DBG.blogDebug("base added egg " + text + " to alloffspring of " + genCfg.PrefabName); genCfg.ProcEggPrefabs.Add(text); } Procreation component = prefab.GetComponent(); GameObject val = null; bool flag = false; bool flag2 = true; if (Object.op_Implicit((Object)(object)component)) { flag = true; string text2 = ""; if (Object.op_Implicit((Object)(object)component.m_offspringPrefab)) { text2 = ((Object)component.m_offspringPrefab).name; flag2 = Object.op_Implicit((Object)(object)component.m_offspringPrefab.GetComponent()); val = component.m_offspringPrefab; } else if (Object.op_Implicit((Object)(object)component.m_offspring)) { text2 = ((Object)component.m_offspring).name; flag2 = Object.op_Implicit((Object)(object)component.m_offspring.GetComponent()); val = component.m_offspring; } else { DBG.blogDebug("did not find offspring adding Mini" + ((Object)prefab).name); text2 = "Mini" + ((Object)prefab).name; } GameObject val2 = addProcPrefToList(genCfg, text2, mate: false, startPref, depth + 1); if ((Object)(object)val == (Object)null && (Object)(object)val2 != (Object)null) { val = val2; } } Growup component2 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component2)) { flag = true; if (Object.op_Implicit((Object)(object)component2.m_grownPrefab)) { addProcPrefToList(genCfg, ((Object)component2.m_grownPrefab).name, mate: false, startPref, depth + 1); } else { DBG.blogDebug("did not find growup"); } } EggGrow component3 = prefab.GetComponent(); if (Object.op_Implicit((Object)(object)component3)) { flag = true; if (Object.op_Implicit((Object)(object)component3.m_grownPrefab)) { addProcPrefToList(genCfg, ((Object)component3.m_grownPrefab).name, mate: false, startPref, depth + 1); } else { DBG.blogDebug("did not find eggGrowup"); } } if (flag && (Object)(object)val == (Object)null) { val = prefab; } if (startPref == "" && !flag) { if (Object.op_Implicit((Object)(object)ZNetScene.instance.GetPrefab(PrefName + "Egg_LMTY"))) { addProcPrefToList(genCfg, PrefName + "Egg_LMTY", mate: false, startPref, depth + 1); } DBG.blogDebug("did not find Offspring/GrowUp/EggGrow, adding Mini" + ((Object)prefab).name); string text3 = "Mini" + ((Object)prefab).name + "(Clone)"; GameObject val3 = addProcPrefToList(genCfg, "Mini" + ((Object)prefab).name, mate: false, startPref, depth + 1); if ((Object)(object)val == (Object)null && (Object)(object)val3 != (Object)null) { val = val3; } } return val; } public static CreatureGenetics.GeneticsConfig SetUpProcPrefabs(Procreation _proc) { string text = ((Object)_proc).name.Replace("(Clone)", ""); if (!CreatureGenetics.customGeneticsList.TryGetValue(text, out var value)) { return null; } string text2 = ""; bool flag = false; if (Object.op_Implicit((Object)(object)_proc.m_offspringPrefab)) { text2 = ((Object)_proc.m_offspringPrefab).name; flag = (Object)(object)_proc.m_offspringPrefab.GetComponent() == (Object)null; } else if (Object.op_Implicit((Object)(object)_proc.m_offspring)) { text2 = ((Object)_proc.m_offspring).name; flag = (Object)(object)_proc.m_offspring.GetComponent() == (Object)null; } else { DBG.blogDebug("did not find offspring"); } text2 += "(Clone)"; DBG.blogDebug("set up offspring name=" + text2); if (flag) { DBG.blogDebug("isEgg=" + text2); if (!value.ProcEggPrefabs.Contains(text2)) { value.ProcEggPrefabs.Add(text2); } } else if (!value.allProcPrefabs.Contains(text2)) { DBG.blogDebug("notEgg=" + text2); value.allProcPrefabs.Add(text2); } if (value.allProcPrefabs.Count + value.ProcEggPrefabs.Count > 1) { DBG.blogDebug("ProcPrefabs already init for: " + text); return value; } DBG.blogDebug("Pre allProcPref for: " + text + ": " + string.Join(",", value.allProcPrefabs)); DBG.blogDebug("Pre ProcEggPrefabs for: " + text + ": " + string.Join(",", value.ProcEggPrefabs)); if (value.ListofRandomOffspring.Count() != 0) { foreach (CreatureGenetics.specificMates item in value.ListofRandomOffspring) { addProcPrefToList(value, item.prefabName); foreach (CreatureGenetics.chanceOffspring item2 in item.possibleOffspring) { GameObject val = addProcPrefToList(value, item2.prefabName, mate: false); if ((Object)(object)val != (Object)null) { DBG.blogDebug("chanceOff.offspring: " + item.prefabName + ": " + ((Object)val).name + ", " + item2.prefabName); item2.offspring = val; } } } DBG.blogDebug("SetUp allProcPref for: " + text + ": " + string.Join(",", value.allProcPrefabs)); DBG.blogDebug("SetUp mateNames for: " + text + ": " + string.Join(",", value.mateNames)); DBG.blogDebug("SetUp eggs for: " + text + ": " + string.Join(",", value.ProcEggPrefabs)); } return value; } public static void InitProcPrefabs(Procreation _proc) { string text = (((Object)(object)_proc.m_offspring != (Object)null) ? ((Object)_proc.m_offspring).name : ""); _proc.m_offspringPrefab = ZNetScene.instance.GetPrefab(text); int prefab = _proc.m_nview.GetZDO().GetPrefab(); _proc.m_myPrefab = ZNetScene.instance.GetPrefab(prefab); GameObject myPrefab = _proc.m_myPrefab; if (myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab)) { DBG.blogDebug("m_myPrefab is still Null, trying again for " + ((Object)_proc).name); string text2 = ((Object)_proc).name.Replace("(Clone)", ""); DBG.blogDebug("proc_name=" + text2); if ((Object)(object)ZNetScene.instance.GetPrefab(text2) == (Object)null) { DBG.blogDebug("proc_name failed"); } else { _proc.m_myPrefab = ZNetScene.instance.GetPrefab(text2); } myPrefab = _proc.m_myPrefab; if (myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab)) { DBG.blogDebug("m_myPrefab backup failed"); } else { DBG.blogDebug("m_myPrefab backup success"); } } myPrefab = _proc.m_offspringPrefab; if (myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab)) { DBG.blogDebug("Failed m_offspringPrefab=" + text); _proc.m_offspringPrefab = _proc.m_offspring; myPrefab = _proc.m_offspringPrefab; if (myPrefab == null || !Object.op_Implicit((Object)(object)myPrefab)) { DBG.blogDebug("m_offspringPrefab backup failed :" + ((Object)(object)_proc.m_offspringPrefab == (Object)null)); } else { DBG.blogDebug("m_offspringPrefab backup success"); } } } [HarmonyPatch(typeof(Procreation), "ResetPregnancy")] [HarmonyPostfix] private static void PostfixResetPregnancy(Procreation __instance) { Genetics genetics = default(Genetics); if (((Component)__instance).TryGetComponent(ref genetics)) { genetics.CheckOffspringReady(); } } [HarmonyPatch(typeof(Procreation), "MakePregnant")] [HarmonyPostfix] private static void PostfixMakePregnant(Procreation __instance) { Genetics genetics = default(Genetics); if (((Component)__instance).TryGetComponent(ref genetics)) { initRandomOffspring(__instance); genetics.ResetOffspring(); } } private static void initRandomOffspring(Procreation _proc) { string key = ((Object)_proc).name.Replace("(Clone)", ""); if (CreatureGenetics.customGeneticsList.TryGetValue(key, out var value) && value.allProcPrefabs.Count == 0 && value.ProcEggPrefabs.Count == 0 && value.ListofRandomOffspring.Count != 0) { SetUpProcPrefabs(_proc); } } private static int GetGeneticInst(int result, Procreation _proc, CreatureGenetics.GeneticsConfig genCfg, bool procOnly = false) { //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) if (genCfg == null) { return result; } DBG.blogDebug($"Starting Genetic find for {((Object)_proc).name}, starting number {result}"); string text = ""; if (!procOnly) { if (Object.op_Implicit((Object)(object)_proc.m_offspringPrefab)) { text = ((Object)_proc.m_offspringPrefab).name; } else if (Object.op_Implicit((Object)(object)_proc.m_offspring)) { text = ((Object)_proc.m_offspring).name; } } else if (!genCfg.canMateWithSelf) { DBG.blogDebug("Cannot Mate with same prefab, " + result + " removed from total nearby"); result = 1; } ZNetScene instance = ZNetScene.instance; Vector3 position = ((Component)_proc).transform.position; float totalCheckRange = _proc.m_totalCheckRange; if (procOnly) { result += MassGetNrOfCreatures(genCfg.mateNames, position, totalCheckRange, procreationOnly: true); } else { result += MassGetNrOfCreatures(genCfg.allProcPrefabs, position, totalCheckRange); result += MassGetNrOfItems(genCfg.ProcEggPrefabs, position, totalCheckRange); } DBG.blogDebug($"Final Result for {((Object)_proc).name} is {result}"); return result; } public static int MassGetNrOfCreatures(List prefNames, Vector3 center, float maxRange, bool procreationOnly = false) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) List allInstances = BaseAI.GetAllInstances(); int num = 0; foreach (BaseAI item in allInstances) { try { if (prefNames.Contains(((Object)((Component)item).gameObject).name) && (!(maxRange > 0f) || !(Vector3.Distance(center, ((Component)item).transform.position) > maxRange))) { if (!procreationOnly) { goto IL_008e; } Procreation component = ((Component)item).GetComponent(); if (!Object.op_Implicit((Object)(object)component) || component.ReadyForProcreation()) { goto IL_008e; } } goto end_IL_001f; IL_008e: num++; DBG.blogDebug("Added 1 of " + ((Object)((Component)item).gameObject).name + "to instnum"); end_IL_001f:; } catch { DBG.blogDebug("Failed to find mate of " + ((Object)((Component)item).gameObject).name + " to instnum"); } } return num; } public static int MassGetNrOfItems(List prefNames, Vector3 center, float maxRange) { //IL_0037: 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) GameObject[] array = GameObject.FindGameObjectsWithTag("spawned"); int num = 0; GameObject[] array2 = array; foreach (GameObject val in array2) { if (prefNames.Contains(((Object)val.gameObject).name) && (!(maxRange > 0f) || !(Vector3.Distance(center, val.transform.position) > maxRange))) { DBG.blogDebug("Added 1 of " + ((Object)val.gameObject).name + "to instnum"); num++; } } return num; } [HarmonyPostfix] [HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")] private static void PostfixGenerateDroplist(CharacterDrop __instance, ref List> __result) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Invalid comparison between Unknown and I4 try { Genetics genetics = default(Genetics); if (!((Component)__instance).gameObject.TryGetComponent(ref genetics)) { return; } float num = 0.6f + (float)genetics.Drops * CreatureGenetics.DropMultiplier; DBG.blogDebug("Pre drop multi" + num); ItemDrop val = default(ItemDrop); for (int i = 0; i < __result.Count; i++) { DBG.blogDebug("Pre drop" + ((Object)__result[i].Key).name + ", amt:" + __result[i].Value); if (!__result[i].Key.TryGetComponent(ref val) || (int)val.m_itemData.m_shared.m_itemType != 13) { float num2 = (float)__result[i].Value * num; int value = Mathf.FloorToInt(num2) + ((Random.value <= num2 % 1f) ? 1 : 0); DBG.blogDebug("amtFlt:" + num2 + ", newAmt:" + value); __result[i] = new KeyValuePair(__result[i].Key, value); } } for (int j = 0; j < __result.Count; j++) { DBG.blogDebug("drop Post" + ((Object)__result[j].Key).name + ", amt:" + __result[j].Value); } } catch { } } [HarmonyPostfix] [HarmonyPatch(typeof(Character), "SetupMaxHealth")] private static void PostfixCharacterSetupMaxHealth(Character __instance) { try { Genetics genetics = default(Genetics); if (!CreatureGenetics.useSLS && ((Component)__instance).gameObject.TryGetComponent(ref genetics)) { genetics.OGMaxHealth = Math.Max(__instance.GetMaxHealth(), genetics.OGMaxHealth); DBG.blogDebug("thisGenetics.OGMaxHealth: " + genetics.OGMaxHealth); __instance.SetMaxHealth(__instance.GetMaxHealth() * Math.Max((float)genetics.Health / 128f, 0.1f)); DBG.blogDebug("__instance.GetMaxHealth(): " + __instance.GetMaxHealth()); } } catch { } } [HarmonyPrefix] [HarmonyPatch(typeof(Character), "Damage")] private static void PrefixChracterDamage(Character __instance, ref HitData hit) { try { Genetics genetics = default(Genetics); if (((Component)__instance).gameObject.TryGetComponent(ref genetics)) { hit.ApplyModifier(387f / ((float)genetics.Armor + 64f) - 1.01f); } } catch { } } private static void ChangeEquipmentColor(Humanoid chr) { try { Genetics genetics = default(Genetics); if (CreatureGenetics.useDNAColor.Value && ((Component)chr).gameObject.TryGetComponent(ref genetics) && !genetics.hasSetupEquipment && !genetics.lateSetInit) { genetics.hasSetupEquipment = genetics.setCompleteColor(); DBG.blogDebug("SetupEquipment=" + genetics.hasSetupEquipment); } } catch { } } [HarmonyPostfix] [HarmonyPatch(typeof(Humanoid), "SetupVisEquipment")] private static void PostfixHumanoidSetupVisEquipment(Humanoid __instance) { ChangeEquipmentColor(__instance); } [HarmonyPostfix] [HarmonyPatch(typeof(Humanoid), "SetupEquipment")] private static void PostfixHumanoidSetupEquipment(Humanoid __instance) { ChangeEquipmentColor(__instance); } [HarmonyPostfix] [HarmonyPatch(typeof(LevelEffects), "SetupLevelVisualization")] private static void Postfix_SetupLevelVisualization(LevelEffects __instance, int level) { if (CreatureGenetics.useSLS) { DBG.blogDebug("Skipping Level Render as SLS"); return; } try { Genetics genetics = default(Genetics); if (CreatureGenetics.useDNAColor.Value && Object.op_Implicit((Object)(object)__instance.m_character) && ((Component)__instance.m_character).gameObject.TryGetComponent(ref genetics)) { DBG.blogDebug("Set Level Render"); Renderer mainRender = __instance.m_mainRender; genetics.postLevelEffect = true; genetics.setCompleteColor(postLevel: true, mainRender); genetics.levelRender = __instance.m_mainRender; } } catch { } } } internal class DNAPatches { } public class Genetics : MonoBehaviour { [Serializable] public class OriginalData : ICloneable { public float acceleration { get; set; } = 1f; public float swimAcceleration { get; set; } = 1f; public float runSpeed { get; set; } = 1f; public float runTurnSpeed { get; set; } = 1f; public float flyFastSpeed { get; set; } = 1f; public float flyTurnSpeed { get; set; } = 1f; public float swimSpeed { get; set; } = 1f; public float swimTurnSpeed { get; set; } = 1f; public float prefSize { get; set; } = 1f; public bool filled { get; set; } = false; public object Clone() { return MemberwiseClone(); } } [Serializable] public class TraitPkg : ICloneable { public long Speed { get; set; } = 128L; public long Health { get; set; } = 128L; public long Armor { get; set; } = 128L; public long Size { get; set; } = 128L; public object Clone() { return MemberwiseClone(); } } [Serializable] public class GeneticPkg : ICloneable { public int id { get; set; } = 0; public string prefabName { get; set; } = ""; public int lvl { get; set; } = 1; public CLLC.Effect_CLLC effect { get; set; } = CLLC.Effect_CLLC.None; public CLLC.Infusion_CLLC infusion { get; set; } = CLLC.Infusion_CLLC.None; public string MonMod { get; set; } = ""; public string SLS { get; set; } = ""; public byte[] DNA { get; set; } = new byte[10]; public object Clone() { return MemberwiseClone(); } } private const string ZDOkey = "CG_DNA"; private const int NumDNAFactors = 10; private int traitOffset = 4; private static byte[] baseDNA; private static float initDelay; private ZNetView m_nview; public Character chr; public long R = 128L; public long G = 128L; public long B = 128L; public float OGMaxHealth = -1f; public long Health = 128L; public long Speed = 128L; public long Armor = 128L; public long Size = 128L; public long Productivity = 0L; public long Drops = 0L; public bool isWild = true; public byte[] DNA_Strand = null; public bool lateSetInit = false; public string HoverText = ""; private OriginalData ogData = new OriginalData(); private bool modifiedSpeed = false; public Renderer[] Renderers = (Renderer[])(object)new Renderer[0]; private Dictionary baseColorTbl = new Dictionary(); private Color baseColor = Color.white; private bool firstColor = true; private Color colorMulti = Color.white; public Renderer levelRender; public bool hasSetupEquipment = false; public bool postLevelEffect = false; public bool hueShifted = false; public GeneticPkg thisPkg; public GeneticPkg partnerPkg; public GeneticPkg offspringPkg; private int level = 1; private bool newLevel = false; public string savedOffspring = ""; private int dad_lvl = 0; public string dad_info = ""; public float sls_size = 0f; public List sls_sizes = new List(); public bool delay_Size = false; private void Awake() { m_nview = ((Component)this).gameObject.GetComponent(); if (!m_nview.IsValid()) { return; } chr = ((Component)this).gameObject.GetComponent(); getOGData(); SetDNA(); if (Object.op_Implicit((Object)(object)((Component)this).GetComponentInParent())) { ItemDrop component = ((Component)this).gameObject.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { ItemData itemData = component.m_itemData; if (!itemData.m_customData.TryGetValue("Infusion", out var value)) { value = "None"; } if (!itemData.m_customData.TryGetValue("ExtraEffect", out var value2)) { value2 = "None"; } if (value != "None" || value2 != "None") { itemData.m_shared.m_maxStackSize = 1; } int quality = GetLevel(component.m_itemData.m_quality); DBG.blogDebug("Setting Quality to " + quality); component.SetQuality(quality); } } if (CreatureGenetics.useSLS) { lateSetInit = true; ((MonoBehaviour)this).Invoke("lateSLSInit", 0.2f); } } public int GetLevel(int oldLevel) { if (newLevel) { return level; } return oldLevel; } public void checkInit() { DBG.blogDebug("Late Checking Init for " + ((Object)((Component)this).gameObject).name); if (!lateSetInit) { DBG.blogDebug("Already Solved, skipping"); return; } lateSetInit = false; if (DNA_Strand == null) { DNA_Strand = m_nview.GetZDO().GetByteArray("CG_DNA", (byte[])null); if (DNA_Strand == null && (Object)(object)chr != (Object)null) { DBG.blogDebug("Performing Backup Init, with random dna"); SetRandomDNA(); } else { DBG.blogDebug("Performing Backup Init, dna=" + string.Join(",", DNA_Strand)); ParseMSG(); } } setAttributes(); SetZDO(); } public void finalSizeDelay() { DBG.blogDebug("Delay size=" + delay_Size); if (delay_Size) { delay_Size = false; setTraits(onlysize: true); } } public void lateSLSInit() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebug("In SLS Late Init for " + ((Object)((Component)this).gameObject).name); float x = ((Component)this).transform.localScale.x; DBG.blogDebugExtra("Starting Size=" + x); ZDO zDO = m_nview.GetZDO(); Vector3 vec = zDO.GetVec3("SLS_SIZE", Vector3.zero); checkInit(); int num = (int)Mathf.Clamp((float)Size, (float)CreatureGenetics.sizeMin256, (float)CreatureGenetics.sizeMax256); Transform transform = ((Component)this).transform; transform.localScale *= (float)(num * num) / 130000f + (float)num / 200f + 0.25f; DBG.blogDebugExtra("New size=" + ((object)((Component)this).transform.localScale/*cast due to .constrained prefix*/).ToString()); } public void SetGrow(Character adultchar) { //IL_01a5: 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_00f8: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebug("inSetGrow"); bool flag = (Object)(object)chr == (Object)null; ItemDrop component = ((Component)this).gameObject.GetComponent(); string text = (flag ? Utils.iDropGetCustData(component, "CG_DNA") : ""); if (CreatureGenetics.useCLLC) { CLLC.Effect_CLLC infusion; CLLC.Infusion_CLLC infusion2; if (flag) { DBG.blogDebug("No Char"); infusion = CLLC.iDropGetEff(component); infusion2 = CLLC.iDropGetInf(component); } else { DBG.blogDebug("Has Char"); infusion2 = CLLC.GetInfusionCreature(chr); infusion = CLLC.GetExtraEffectCreature(chr); } CLLC.SetInfusionCreature(adultchar, infusion2); CLLC.SetExtraEffectCreature(adultchar, infusion); } if (CreatureGenetics.useSLS) { string sLS_Str; if (flag) { DBG.blogDebug("No Char"); sLS_Str = Utils.iDropGetCustData(component, "CG_SLS"); } else { sLS_Str = SLS_CG.getModifiers(chr); } SLS_CG.SetModifiers(adultchar, sLS_Str); float x = ((Component)adultchar).transform.localScale.x; DBG.blogDebugExtra("Default Size1=" + x); ZDO zDO = adultchar.m_nview.GetZDO(); DBG.blogDebugExtra("sls_size11: " + zDO.GetFloat("SLS_SIZE", 0f)); } if (CreatureGenetics.useMonMod) { string monMod; if (flag) { DBG.blogDebug("No Char"); monMod = Utils.iDropGetCustData(component, "CG_MonMod"); } else { monMod = MonMod_CG.getModifiers(chr); } MonMod_CG.SetModifiers(adultchar, monMod); } DBG.blogDebugExtra("current size2=" + ((Component)adultchar).transform.localScale.x); if (!CreatureGenetics.useDNA) { return; } Genetics genetics = default(Genetics); if (!((Component)adultchar).gameObject.TryGetComponent(ref genetics)) { DBG.blogDebugExtra("Adding adult Genes"); genetics = ((Component)adultchar).gameObject.AddComponent(); } byte[] array = null; if (text != "") { array = Convert.FromBase64String(text); DBG.blogDebug("Setting DNA from iDrop"); DNA_Strand = array; } else { DNA_Strand = m_nview.GetZDO().GetByteArray("CG_DNA", (byte[])null); if (DNA_Strand == null) { SetRandomDNA(); SetZDO(); } } genetics.DNA_Strand = DNA_Strand; genetics.restoreColor(); genetics.ParseMSG(); genetics.setAttributes(); genetics.SetZDO(); } public static string iDropGetDNA(ItemDrop iDrop) { string result = ""; if (Object.op_Implicit((Object)(object)iDrop) && CreatureGenetics.useDNA && iDrop.m_itemData.m_customData.TryGetValue("CG_DNA", out var value)) { result = value; DBG.blogDebug("got DNA from iDrop"); } return result; } public void SetDNA() { if (!CreatureGenetics.useDNA) { return; } if (DNA_Strand == null) { DNA_Strand = m_nview.GetZDO().GetByteArray("CG_DNA", (byte[])null); if (DNA_Strand != null) { DBG.blogDebugExtra("grabbed dna hash: " + string.Join(",", DNA_Strand)); } else { DBG.blogDebug("DNA strand is null"); if (Object.op_Implicit((Object)(object)((Component)this).gameObject.GetComponent())) { DBG.blogDebug("is child, skipping init"); if (!lateSetInit) { lateSetInit = true; ((MonoBehaviour)this).Invoke("checkInit", initDelay); } return; } if (Object.op_Implicit((Object)(object)((Component)this).gameObject.GetComponent())) { DBG.blogDebug("is egg, skipping init"); return; } DBG.blogDebug("is adult, making random DNA"); } } else { DBG.blogDebug("has DNA: " + string.Join(",", DNA_Strand)); } ParseMSG(); if (CreatureGenetics.useSLS) { DBG.blogDebug("is SLS, skipping init"); if (!lateSetInit && (Object)(object)chr != (Object)null) { lateSetInit = true; ((MonoBehaviour)this).Invoke("checkInit", initDelay); } } else { setAttributes(); SetZDO(); } } public void SetZDO() { if (DNA_Strand == null) { DNA_Strand = new byte[10]; } DNA_Strand[0] = (byte)Math.Min(R, 255L); DNA_Strand[1] = (byte)Math.Min(G, 255L); DNA_Strand[2] = (byte)Math.Min(B, 255L); DNA_Strand[3] = Convert.ToByte(isWild); DNA_Strand[4] = (byte)Health; DNA_Strand[5] = (byte)Speed; DNA_Strand[6] = (byte)Armor; DNA_Strand[7] = (byte)Size; DNA_Strand[8] = (byte)Productivity; DNA_Strand[9] = (byte)Math.Max(0L, Drops); m_nview.GetZDO().Set("CG_DNA", DNA_Strand); } public void ParseMSG() { if (DNA_Strand == null) { Character val = default(Character); if (((Component)this).gameObject.TryGetComponent(ref val)) { if (!val.m_tamed) { DBG.blogDebug("is not tamed"); OGMaxHealth = val.GetMaxHealth(); SetRandomDNA(); } else if (!lateSetInit) { DBG.blogDebug("is tamed but no DNA"); lateSetInit = true; ((MonoBehaviour)this).Invoke("checkInit", initDelay); } } } else if (DNA_Strand.Length > 10) { DNA_Strand = new byte[10]; SetRandomDNA(); } else { DBG.blogDebug(((Object)((Component)this).gameObject).name + " DNA_Strand=" + string.Join(",", DNA_Strand)); R = DNA_Strand[0]; G = DNA_Strand[1]; B = DNA_Strand[2]; isWild = DNA_Strand[3] == 1; Health = DNA_Strand[4]; Speed = DNA_Strand[5]; Armor = DNA_Strand[6]; Size = DNA_Strand[7]; Productivity = DNA_Strand[8]; Drops = DNA_Strand[9]; } } private void SetRandomDNA() { GaussianGenerator gaussianGenerator = new GaussianGenerator(); float dNAVarianceMod = CreatureGenetics.DNAVarianceMod; R = (long)gaussianGenerator.NextDouble(128.0, 13f * dNAVarianceMod); G = (long)gaussianGenerator.NextDouble(128.0, 13f * dNAVarianceMod); B = (long)gaussianGenerator.NextDouble(128.0, 13f * dNAVarianceMod); float[] array = new float[4] { 6f * dNAVarianceMod, 2f * dNAVarianceMod, -2f * dNAVarianceMod, -6f * dNAVarianceMod }; ShuffleClass.Shuffle((IList)array, false); Health = (long)gaussianGenerator.NextDouble(128f + array[0], 13f * dNAVarianceMod); Speed = (long)gaussianGenerator.NextDouble(128f + array[1], 13f * dNAVarianceMod); Armor = (long)gaussianGenerator.NextDouble(128f + array[2], 13f * dNAVarianceMod); Size = (long)gaussianGenerator.NextDouble(128f + array[3], 13f * dNAVarianceMod); Productivity = Math.Max((long)gaussianGenerator.NextDouble(CreatureGenetics.centerProd, 13f * dNAVarianceMod), 0L); Drops = Math.Max((long)gaussianGenerator.NextDouble(CreatureGenetics.centerDrop, 13f * dNAVarianceMod), 0L); } public void setAttributes() { DBG.blogDebug("setting attributes"); if (!Object.op_Implicit((Object)(object)chr)) { SetZDO(); return; } HoverText = ""; if (CreatureGenetics.useDNAColor.Value) { Transform val = ((Component)this).transform.Find("Visual"); if (Object.op_Implicit((Object)(object)val) && (postLevelEffect || (!Object.op_Implicit((Object)(object)((Component)val).GetComponent()) && !CreatureGenetics.useSLS))) { DBG.blogDebug("Setting Color: " + (lateSetInit ? "Late" : "On Time")); setCompleteColor(postLevel: true); } } if (CreatureGenetics.useDNATraits.Value) { setTraits(); } } public bool setCompleteColor(bool postLevel = false, Renderer overwriteRender = null) { if (lateSetInit) { DBG.blogDebugExtra("too early to init"); return false; } DBG.blogDebug("Colors=" + R + "," + G + "," + B); Transform val = ((Component)this).transform.Find("Visual"); if (!Object.op_Implicit((Object)(object)val)) { return false; } bool value = CreatureGenetics.onlyDNABrightness.Value; Renderer[] renderers = Renderers; foreach (Renderer val2 in renderers) { int count = Regex.Matches(((Object)val2.material).name, "Instance").Count; if (count > 1) { setSingleColor(val2.material, postLevel, value); } } IEnumerable enumerable = ((Component)val).GetComponentsInChildren().Except(Renderers); if (Object.op_Implicit((Object)(object)overwriteRender) & !enumerable.Contains(overwriteRender)) { enumerable.Append(overwriteRender); } foreach (Renderer item in enumerable) { setSingleColor(item.material, postLevel, value); } Renderers = Renderers.Concat(enumerable).ToArray(); return true; } public void setSingleColor(Material mat, bool postLevel = false, bool onlyBright = false) { //IL_0183: 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_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) if (!mat.HasProperty("_Color")) { return; } if (firstColor) { firstColor = false; if (onlyBright) { colorMulti = new Color((float)(R * R) / 63773f + (float)R / 172f, (float)(R * R) / 63773f + (float)R / 172f, (float)(R * R) / 63773f + (float)R / 172f); } else { colorMulti = new Color((float)(R * R) / 63773f + (float)R / 172f, (float)(G * G) / 63773f + (float)G / 172f, (float)(B * B) / 63773f + (float)B / 172f); } } string text = ((Object)mat).name.Replace(" (Instance)", "").Replace("(Clone)", ""); Color val; if (baseColorTbl.TryGetValue(text, out var value)) { if (checkSimilarity(mat.color, value)) { return; } val = value; } else { baseColorTbl.Add(text, mat.color); val = mat.color; DBG.blogDebug("New Color for " + text + ":" + ((object)Unsafe.As(ref colorMulti)/*cast due to .constrained prefix*/).ToString()); } if (!hueShifted && mat.HasProperty("_Hue")) { float num = mat.GetFloat("_Hue"); if (num != 0f) { colorMulti = Utils.ShiftHue(colorMulti, 0f - mat.GetFloat("_Hue")); hueShifted = true; } } Color color = val * colorMulti; mat.color = color; } public bool checkSimilarity(Color thisColor, Color baseColor) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) Color val = baseColor * colorMulti; if (object.Equals(thisColor, val)) { return true; } return false; } public void restoreColor() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) if (CreatureGenetics.useDNAColor.Value) { Renderer[] renderers = Renderers; Color color = default(Color); foreach (Renderer val in renderers) { Material material = val.material; ((Color)(ref color))..ctor(baseColor.r, baseColor.g, baseColor.b, material.color.a); material.color = color; } Renderers = (Renderer[])(object)new Renderer[0]; } } public void setTraits(bool onlysize = false) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebug("setting traits for " + ((Object)((Component)this).gameObject).name); int num = (int)Mathf.Clamp((float)Size, (float)CreatureGenetics.sizeMin256, (float)CreatureGenetics.sizeMax256); Transform transform = ((Component)chr).transform; transform.localScale *= (float)(num * num) / 130000f + (float)num / 200f + 0.25f; if (onlysize) { return; } Transform val = ((Component)this).transform.Find("Visual"); if (Object.op_Implicit((Object)(object)val)) { LODGroup component = ((Component)val).GetComponent(); if (Object.op_Implicit((Object)(object)component)) { component.size *= Mathf.Max((float)(num * num / 17150 - num / 52) + 2.5f, 1f); } } if (!getOGData()) { DBG.blogWarning("Could not get OG Data"); return; } chr.SetupMaxHealth(); modifySpeed(); setProcreationTime(); } public void setProcreationTime() { Procreation component = ((Component)this).gameObject.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { float num = (component.m_updateInterval /= 0.6f + (float)Productivity * CreatureGenetics.ProdMultiplier); ((MonoBehaviour)this).InvokeRepeating("Procreate", Random.Range(num, num * 1.5f), num); DBG.blogDebug("New Procreation Time=" + num); } } public bool getOGData() { //IL_00fa: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)chr)) { return false; } if (!ogData.filled) { ogData.acceleration = chr.m_acceleration; ogData.flyFastSpeed = chr.m_flyFastSpeed; ogData.flyTurnSpeed = chr.m_flyTurnSpeed; ogData.runSpeed = chr.m_runSpeed; ogData.runTurnSpeed = chr.m_runTurnSpeed; ogData.swimAcceleration = chr.m_swimAcceleration; ogData.swimSpeed = chr.m_swimSpeed; ogData.swimTurnSpeed = chr.m_swimTurnSpeed; ogData.prefSize = ((Component)chr).transform.localScale.x; ogData.filled = true; } return true; } public void modifySpeed() { if (!modifiedSpeed || !Object.op_Implicit((Object)(object)chr)) { modifiedSpeed = true; float num = (float)Speed / 128f; if (num < 0.01f) { num = 0.01f; } DBG.blogDebug("Speed=" + Speed + ", speedMulti=" + num); Character obj = chr; obj.m_acceleration *= num; Character obj2 = chr; obj2.m_flyFastSpeed *= num; Character obj3 = chr; obj3.m_flyTurnSpeed *= num; Character obj4 = chr; obj4.m_runSpeed *= num; Character obj5 = chr; obj5.m_runTurnSpeed *= num; Character obj6 = chr; obj6.m_swimAcceleration *= num; Character obj7 = chr; obj7.m_swimSpeed *= num; Character obj8 = chr; obj8.m_swimTurnSpeed *= num; } } public void forceSetDNA() { DNA_Strand = m_nview.GetZDO().GetByteArray("CG_DNA", (byte[])null); if (DNA_Strand == null || DNA_Strand[4] == 1) { DBG.blogDebugExtra("Set Random DNA"); SetRandomDNA(); SetZDO(); } } public GeneticPkg getGeneticPkg() { if (thisPkg != null) { DBG.blogDebugExtra("already has pkg=" + thisPkg.prefabName); return thisPkg; } DBG.blogDebugExtra("making new pkg for=" + ((Object)((Component)this).gameObject).name); thisPkg = new GeneticPkg(); thisPkg.id = ((Object)m_nview).GetInstanceID(); thisPkg.DNA = DNA_Strand; Character component = ((Component)this).gameObject.GetComponent(); thisPkg.prefabName = ((Object)component).name.Replace("(Clone)", ""); thisPkg.lvl = component.GetLevel(); if (CreatureGenetics.useCLLC) { thisPkg.effect = CLLC.GetExtraEffectCreature(component); thisPkg.infusion = CLLC.GetInfusionCreature(component); } if (CreatureGenetics.useSLS) { thisPkg.SLS = SLS_CG.getModifiers(component); } if (CreatureGenetics.useMonMod) { thisPkg.MonMod = MonMod_CG.getModifiers(component); } return thisPkg; } public void CheckOffspringReady() { DBG.blogDebug("checking offspring ready"); if (partnerPkg == null) { SetOffspring(); return; } if (savedOffspring == "") { savedOffspring = m_nview.GetZDO().GetString("OffspringName", ""); if (savedOffspring == "") { SetOffspring(); return; } DBG.blogDebug("Grabbed savedOffspring from zdo: " + savedOffspring); } Procreation component = ((Component)this).gameObject.GetComponent(); if ((Object)(object)component == (Object)null) { DBG.blogWarning("Does not have procreation"); return; } GameObject offspringPrefab = component.m_offspringPrefab; if (((offspringPrefab != null) ? ((Object)offspringPrefab).name : null) != savedOffspring) { DBG.blogDebug("savedOffspring=" + savedOffspring + ", offspringpref=" + ((offspringPrefab != null) ? ((Object)offspringPrefab).name : null)); GameObject prefab = ZNetScene.instance.GetPrefab(savedOffspring); if ((Object)(object)prefab == (Object)null) { ResetOffspring(); } else { component.m_offspringPrefab = prefab; } } } public void ResetOffspring() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) m_nview.GetZDO().Set("CG_Partner", ZDOID.None); partnerPkg = null; SetOffspring(); } public void SetOffspring() { GetPartners(); string prefabName = Utils.GetPrefabName(((Object)((Component)this).gameObject).name); if (!CreatureGenetics.customGeneticsList.TryGetValue(prefabName, out var value) || partnerPkg == null) { return; } DBG.blogDebugExtra("partnerPkg.prefabName=" + partnerPkg.prefabName); foreach (CreatureGenetics.specificMates item in value.ListofRandomOffspring) { DBG.blogDebugExtra("specmates.prefabName=" + item.prefabName); } CreatureGenetics.specificMates specificMates = value.ListofRandomOffspring.Find((CreatureGenetics.specificMates x) => x.prefabName == partnerPkg.prefabName); if (specificMates == null) { DBG.blogDebug("Could not find specmate=" + partnerPkg.prefabName); } else { Procreation val = default(Procreation); if (!((Component)this).gameObject.TryGetComponent(ref val)) { return; } float num = Random.Range(0f, 100f); if (specificMates.possibleOffspring.Count == 0) { Procreation val2 = null; if (num > 50f) { DBG.blogDebugExtra("Getting PrefabProc from " + partnerPkg.prefabName); val2 = ZNetScene.instance.GetPrefab(partnerPkg.prefabName).GetComponent(); DBG.blogDebugExtra("Getting PrefabProc from " + prefabName); } else { if ((Object)(object)value.baseOffspring != (Object)null) { DBG.blogDebugExtra("customGenes.baseOffspring " + ((Object)value.baseOffspring).name); val.m_offspring = value.baseOffspring; val.m_offspringPrefab = value.baseOffspring; DBG.blogDebugExtra("exiting prefab " + ((Object)val.m_offspring).name); val.m_nview.GetZDO().Set("OffspringName", ((Object)val.m_offspring).name); savedOffspring = ((Object)val.m_offspring).name; return; } val2 = ZNetScene.instance.GetPrefab(prefabName).GetComponent(); } if ((Object)(object)val2 == (Object)null) { DBG.blogDebug("PrefabProc is null"); } if ((Object)(object)val2.m_offspring != (Object)null) { val.m_offspring = val2.m_offspring; val.m_offspringPrefab = val2.m_offspring; } else if ((Object)(object)val2.m_offspringPrefab != (Object)null) { val.m_offspring = val2.m_offspringPrefab; val.m_offspringPrefab = val2.m_offspringPrefab; } if (num < 50f) { DBG.blogDebugExtra("Setting baseOffspring=" + (object)val.m_offspring); value.baseOffspring = val.m_offspring; } DBG.blogDebugExtra("exiting prefab " + ((Object)val.m_offspring).name); val.m_nview.GetZDO().Set("OffspringName", ((Object)val.m_offspring).name); savedOffspring = ((Object)val.m_offspring).name; return; } float num2 = 0f; DBG.blogDebugExtra("Determining chance for offspring of " + specificMates.prefabName); foreach (CreatureGenetics.chanceOffspring item2 in specificMates.possibleOffspring) { num2 += item2.chance; DBG.blogDebugExtra("currentchance=" + num2 + ", rndm=" + num); if (!(num2 >= num)) { continue; } DBG.blogDebugExtra("finalchance=" + num2 + ", rndm=" + num); if ((Object)(object)item2.offspring == (Object)null) { DBG.blogDebugExtra("grabbing new prefab=" + item2.prefabName); item2.offspring = ZNetScene.instance.GetPrefab(item2.prefabName); if ((Object)(object)item2.offspring == (Object)null) { DBG.blogWarning("could not find prefab with name=" + item2.prefabName); } } val.m_offspring = item2.offspring; val.m_offspringPrefab = item2.offspring; DBG.blogDebug("proc.m_offspring=" + ((Object)val.m_offspring).name); val.m_nview.GetZDO().Set("OffspringName", ((Object)val.m_offspring).name); savedOffspring = ((Object)val.m_offspring).name; return; } DBG.blogDebug("Did not get chance offspring of " + specificMates.prefabName); if ((Object)(object)value.baseOffspring != (Object)null) { DBG.blogDebugExtra("customGenes.baseOffspring " + ((Object)value.baseOffspring).name); val.m_offspring = value.baseOffspring; val.m_offspringPrefab = value.baseOffspring; DBG.blogDebugExtra("exiting prefab " + ((Object)val.m_offspring).name); val.m_nview.GetZDO().Set("OffspringName", ((Object)val.m_offspring).name); savedOffspring = ((Object)val.m_offspring).name; return; } Procreation component = ZNetScene.instance.GetPrefab(prefabName).GetComponent(); if ((Object)(object)component == (Object)null) { DBG.blogDebug("baseProc is null"); } if ((Object)(object)component.m_offspring != (Object)null) { val.m_offspring = component.m_offspring; val.m_offspringPrefab = component.m_offspring; } else if ((Object)(object)component.m_offspringPrefab != (Object)null) { val.m_offspring = component.m_offspringPrefab; val.m_offspringPrefab = component.m_offspringPrefab; } value.baseOffspring = val.m_offspring; val.m_nview.GetZDO().Set("OffspringName", ((Object)val.m_offspring).name); savedOffspring = ((Object)val.m_offspring).name; DBG.blogDebug("exiting baseProc " + ((Object)val.m_offspring).name); } } public unsafe void GetPartners() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) if (partnerPkg != null) { return; } ZDOID zDOID = m_nview.GetZDO().GetZDOID("CG_Partner"); if (zDOID != ZDOID.None) { ZDOID val = zDOID; DBG.blogDebugExtra("Found partner zdoid=" + ((object)(*(ZDOID*)(&val))/*cast due to .constrained prefix*/).ToString()); GameObject val2 = ZNetScene.instance.FindInstance(zDOID); Genetics genetics = default(Genetics); if ((Object)(object)val2 != (Object)null && val2.TryGetComponent(ref genetics)) { string name = ((Object)val2).name; val = zDOID; DBG.blogDebug("Found partner instance=" + name + ":" + ((object)(*(ZDOID*)(&val))/*cast due to .constrained prefix*/).ToString()); DBG.blogDebugExtra("partnerGenes=" + genetics.savedOffspring); partnerPkg = genetics.getGeneticPkg(); return; } } else { DBG.blogDebugExtra("No partner ZDOID found for=" + ((Object)m_nview).name); } string prefabName = Utils.GetPrefabName(((Object)((Component)this).gameObject).name); List list = new List(); if (CreatureGenetics.customGeneticsList.TryGetValue(prefabName, out var value)) { if (value.mateNames.Count == 0 && value.canMateWithSelf) { value.mateNames.Add(((Object)((Component)this).gameObject).name); } list = value.mateNames; } else { list.Add(((Object)((Component)this).gameObject).name); } Character val3 = null; float num = 999999f; List allCharacters = Character.GetAllCharacters(); GameObject gameObject = ((Component)this).gameObject; DBG.blogDebug("Finding closest mate"); bool flag = false; Tameable val4 = default(Tameable); foreach (Character item in allCharacters) { bool flag2 = false; if ((Object)(object)((Component)item).gameObject == (Object)(object)gameObject || !((Component)item).GetComponent().IsValid() || !list.Contains(((Object)item).name) || !((Component)item).TryGetComponent(ref val4)) { continue; } if (val4.IsHungry()) { flag2 = true; } DBG.blogDebugExtra("Not skipping " + ((Object)item).name); float num2 = Vector3.Distance(((Component)item).transform.position, ((Component)this).transform.position); if ((flag && !flag2) || num2 < num) { DBG.blogDebugExtra("character with name go:" + ((Object)((Component)item).gameObject).name + " is " + Vector3.Distance(((Component)item).transform.position, ((Component)this).transform.position) + "m away"); val3 = item; num = num2; flag = flag2; if (flag2) { DBG.blogDebugExtra(((Object)item).name + "is nearest mate even though hungry"); } } } if ((Object)(object)val3 != (Object)null) { DBG.blogDebug("Partner with name go:" + ((Object)((Component)val3).gameObject).name + " is " + Vector3.Distance(((Component)val3).transform.position, ((Component)this).transform.position) + "m away"); partnerPkg = ((Component)val3).GetComponent().getGeneticPkg(); m_nview.GetZDO().Set("CG_Partner", val3.m_nview.GetZDO().m_uid); } else { DBG.blogDebug("Could not find partner"); partnerPkg = new GeneticPkg(); partnerPkg.DNA = baseDNA.ToArray(); partnerPkg.lvl = ((Component)this).gameObject.GetComponent().GetLevel(); } } public static int GetNewLvl(int lvl, int lvl2) { if (CreatureGenetics.allowLvlMutation.Value && Random.Range(0f, 100f) < CreatureGenetics.MutationChanceLvl.Value) { DBG.blogDebug("Has Mutation in Level"); int num = Mathf.Max(Mathf.Min(lvl, lvl2) - 1, 1); int num2 = Mathf.Max(lvl, lvl2) + 1; DBG.blogDebugExtra("min=" + num + ", max=" + num2); int num3 = Mathf.Min(100, Random.Range(0, 100) + 10); DBG.blogDebugExtra("level_min=" + num + ", rndm=" + num3 + ", float=" + ((float)num + (float)num3 * ((float)num2 - (float)num) / 100f)); lvl = num + Mathf.RoundToInt((float)(num3 * (num2 - num)) / 100f); if (CreatureGenetics.MaxMutationLvl.Value > 0 && lvl > CreatureGenetics.MaxMutationLvl.Value) { lvl = CreatureGenetics.MaxMutationLvl.Value; } } else if (Random.Range(0, 100) > 50) { DBG.blogDebugExtra("IsDadLvl"); lvl = lvl2; } return lvl; } public byte[][] makeMinMaxDNA() { byte[][] array = new byte[10][]; byte[] dNA = partnerPkg.DNA; DBG.blogDebugExtra("DNA_Strand.lrngth=" + DNA_Strand.Length); DBG.blogDebugExtra("minmaxDNA.lrngth=" + array.Length); for (int i = 0; i < array.Length; i++) { if (DNA_Strand[i] < dNA[i]) { array[i] = new byte[2] { DNA_Strand[i], dNA[i] }; } else { array[i] = new byte[2] { dNA[i], DNA_Strand[i] }; } DBG.blogDebugExtra("minmaxDNA[" + i + "]=" + string.Join(",", array[i])); } DBG.blogDebugExtra("minmaxDNA.completed"); return array; } public float[] calcPropMultiplier(int traitNum, ref byte[] newDNA, byte[][] MinMaxDNA) { float[,] influenceMatrix = GeneticsPatches.getInfluenceMatrix(); float num = 1f; float num2 = 1f; float num3 = 127.5f; for (int i = 0; i < 10 - traitOffset; i++) { num3 = i switch { 4 => CreatureGenetics.centerProd, 5 => CreatureGenetics.centerDrop, _ => 127.5f, }; num *= influenceMatrix[traitNum, i] / 127.5f * ((float)(int)MinMaxDNA[i + traitOffset][0] - num3) + 1f; DBG.blogDebugExtra("minMulti " + i + "=" + num + ",minTrait=" + MinMaxDNA[i + traitOffset][0] + ",center=" + num3); num2 *= influenceMatrix[traitNum, i] / 127.5f * ((float)(int)MinMaxDNA[i + traitOffset][1] - num3) + 1f; DBG.blogDebugExtra("maxMulti " + i + "=" + num2 + ",maxTrait=" + MinMaxDNA[i + traitOffset][1]); } return new float[2] { num, num2 }; } public byte getRandomInRange(byte[] MinMax, float varianceLower, float varianceHigher, float center = 127.5f) { float num = (int)MinMax[0]; float num2 = (int)MinMax[1]; float num3 = varianceHigher * (127f + 86f * ((num2 > center) ? ((num2 - center) / (center - 255f)) : ((num2 - center) / center))); float num4 = varianceLower * (127f + 86f * ((num > center) ? ((num - center) / (center - 255f)) : ((num - center) / center))); if (num3 < 0.55f) { num3 = 0.55f; } if (num4 < 0.55f) { num4 = 0.55f; } DBG.blogDebugExtra("maxval:" + num2 + ",var:" + num3 + ",minval:" + num + ",var:" + num4); return Convert.ToByte(Math.Min(Math.Max(Random.Range(num - num4, num2 + num3), 0f), 255f)); } public byte[] getDNAOffspring() { byte[] newDNA = new byte[10]; float num = (float)CreatureGenetics.breedingDNAVariance.Value / 100f; byte[][] array = makeMinMaxDNA(); newDNA[0] = getRandomInRange(array[0], num, num); newDNA[1] = getRandomInRange(array[1], num, num); newDNA[2] = getRandomInRange(array[2], num, num); newDNA[3] = 0; int[] array2 = new int[6] { 0, 1, 2, 3, 4, 5 }; ShuffleClass.Shuffle((IList)array2, false); int[] array3 = array2; for (int i = 0; i < array3.Length; i++) { int num2 = array3[i]; float[] array4 = calcPropMultiplier(num2, ref newDNA, array); DBG.blogDebugExtra("traitnum=" + num2 + ",multi=" + string.Join(",", array4)); newDNA[num2 + traitOffset] = getRandomInRange(array[num2 + traitOffset], num * array4[0], num * array4[1], num2 switch { 5 => CreatureGenetics.centerDrop, 4 => CreatureGenetics.centerProd, _ => 127.5f, }); DBG.blogDebugExtra("NewDNAtrait:" + (num2 + traitOffset) + "," + newDNA[num2 + traitOffset]); } return newDNA; } public void SetUpChildDNA(Genetics momGenes) { DBG.blogDebug("Attempting Child DNA"); byte[] dNAOffspring = momGenes.getDNAOffspring(); restoreColor(); DNA_Strand = dNAOffspring; ParseMSG(); isWild = false; setAttributes(); SetZDO(); } public void SetCreature(Character mother) { try { Genetics genetics = default(Genetics); if (!((Component)mother).gameObject.TryGetComponent(ref genetics)) { DBG.blogDebugExtra("Adding Genes to mother"); genetics = ((Component)mother).gameObject.AddComponent(); } genetics.GetPartners(); GeneticPkg geneticPkg = genetics.partnerPkg; level = mother.GetLevel(); dad_lvl = geneticPkg.lvl; level = GetNewLvl(level, dad_lvl); newLevel = true; string text = ""; string text2 = ""; bool flag = Object.op_Implicit((Object)(object)((Component)this).gameObject.GetComponent()); bool flag2 = false; if (CreatureGenetics.useMonMod) { try { DBG.blogDebug("MonMod is egg=" + flag + ",lvl=" + level); string modifiers = MonMod_CG.getModifiers(mother); text = MonMod_CG.CreateChildModifiers(modifiers, geneticPkg.MonMod, level); DBG.blogDebug("MonModStr=" + text); } catch { DBG.blogWarning("Failed MonsterModifiers Compat"); } } if (CreatureGenetics.useSLS) { try { DBG.blogDebug("SLS is egg=" + flag + ",lvl=" + level); string modifiers2 = SLS_CG.getModifiers(mother); text2 = SLS_CG.CreateChildModifiers(modifiers2, geneticPkg.SLS, level); DBG.blogDebug("SLS: Child Modifiers=" + text2); } catch { DBG.blogWarning("Failed SLS Compat"); } } if (CreatureGenetics.useCLLC) { try { flag2 = CLLC.SetInfusionExtraEffect(((Component)this).gameObject, genetics, flag); } catch { DBG.blogWarning("Failed CLLC Compat"); } } if (CreatureGenetics.useDNA) { try { SetUpChildDNA(genetics); } catch { DBG.blogWarning("Failed DNA Compat"); } } Character component = ((Component)this).gameObject.GetComponent(); DBG.blogDebug("isEgg=" + flag); if ((Object)(object)component != (Object)null) { DBG.blogDebug("Setting level to" + level); component.SetLevel(level); component.SetTamed(true); } else { DBG.blogDebug("ThisChar null"); } ItemDrop val = null; if (flag) { val = ((Component)this).gameObject.GetComponent(); val.SetQuality(level); DBG.blogDebug("setting egg quality to =" + level); if (CreatureGenetics.useMonMod) { Utils.addOrUpdateCustomData(val.m_itemData.m_customData, "CG_MonMod", text); if (text.Length > 0) { flag2 = true; } } if (CreatureGenetics.useSLS) { Utils.addOrUpdateCustomData(val.m_itemData.m_customData, "CG_SLS", text2); if (text2.Length > 0) { flag2 = true; } } if (CreatureGenetics.useDNA) { string newValue = Convert.ToBase64String(DNA_Strand); Utils.addOrUpdateCustomData(val.m_itemData.m_customData, "CG_DNA", newValue); } if (flag2) { DBG.blogDebug("Is Special"); val.m_itemData.m_shared.m_maxStackSize = val.m_itemData.m_stack; } else { DBG.blogDebug("Not Special"); val.m_itemData.m_shared.m_maxStackSize = Math.Max(val.m_itemData.m_stack, 20); } val.Save(); } else { if (CreatureGenetics.useMonMod) { try { MonMod_CG.SetModifiers(component, text); } catch { DBG.blogWarning("Failed MonsterModifiers SetModifiers"); } } if (CreatureGenetics.useSLS) { try { DBG.blogDebugExtra("current Modifiers=" + SLS_CG.getModifiers(component)); SLS_CG.SetModifiers(component, text2); DBG.blogDebugExtra("Cached modifiers:"); } catch { DBG.blogWarning("Failed SLS SetModifiers"); } } } } catch { try { DBG.blogWarning("Major failure of procreation"); level = mother.GetLevel(); } catch { DBG.blogWarning("Catastrophic failure of procreation"); level = 0; } } DBG.blogDebug("End of Set Creature"); } static Genetics() { byte[] obj = new byte[10] { 128, 128, 128, 0, 128, 128, 128, 128, 0, 0 }; obj[8] = (byte)CreatureGenetics.centerProd; obj[9] = (byte)CreatureGenetics.centerDrop; baseDNA = obj; initDelay = 0.05f; } } internal static class GeneticsHover { [HarmonyPatch(typeof(ItemDrop), "GetHoverText")] [HarmonyPostfix] private static void ID_GetHoverText(ItemDrop __instance) { EggGrow val = default(EggGrow); if (Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsValid() && ((Component)__instance).gameObject.TryGetComponent(ref val)) { setstack(__instance.m_itemData); } } public static void setstack(ItemData iData) { if (iData.m_quality <= 1) { iData.m_shared.m_maxStackSize = Math.Max(iData.m_stack, 20); return; } bool flag = false; if (CreatureGenetics.useMonMod) { flag = true; } if (CreatureGenetics.useSLS) { flag = true; } if (!flag && CreatureGenetics.useCLLC) { if (!iData.m_customData.TryGetValue("Infusion", out var value)) { value = "None"; } if (!iData.m_customData.TryGetValue("ExtraEffect", out var value2)) { value2 = "None"; } if (value != "None" || value2 != "None") { flag = true; } } if (flag) { iData.m_shared.m_maxStackSize = iData.m_stack; } else { iData.m_shared.m_maxStackSize = Math.Max(iData.m_stack, 20); } } [HarmonyPatch(typeof(Character), "GetHoverText")] [HarmonyPostfix] [HarmonyPriority(390)] public static void Char_GetHoverText(Character __instance, ref string __result) { GetDNAText(__instance, ref __result); } [HarmonyPatch(typeof(Inventory), "Load")] [HarmonyPostfix] private static void Inventory_Load_Postfix(Inventory __instance) { foreach (ItemData item in __instance.m_inventory) { if (((Object)item.m_dropPrefab).name.Contains("Egg")) { setstack(item); } } } public static void GetDNAText(Character character, ref string __result) { Genetics genetics = default(Genetics); if (!CreatureGenetics.useDNA || !((Component)character).TryGetComponent(ref genetics)) { return; } Player localPlayer = Player.m_localPlayer; ItemData helmetItem = ((Humanoid)localPlayer).m_helmetItem; if (helmetItem == null || ((Object)((Humanoid)localPlayer).m_helmetItem.m_dropPrefab).name != "GeneticsHat") { return; } if (genetics.HoverText.Length > 0) { __result += genetics.HoverText; return; } DBG.blogDebug("SettingHoverText"); string text = "\n"; string text2 = "\n"; if (CreatureGenetics.useDNAColor.Value) { if (CreatureGenetics.onlyDNABrightness.Value) { if (CreatureGenetics.useDNATraits.Value) { text2 = ", $cg_trait_brightness:" + Math.Round((float)genetics.R / 1.275f, 1) + "%\n"; } else { text = text + "$cg_trait_brightness:" + Math.Round((float)genetics.R / 1.275f, 1) + "%\n"; } } else { text = text + " R:" + Math.Round((float)genetics.R / 1.275f, 1) + "%, G:" + Math.Round((float)genetics.G / 1.275f, 1) + "%, B:" + Math.Round((float)genetics.B / 1.275f, 1) + "%\n"; } } if (CreatureGenetics.useDNATraits.Value) { text = text + " $cg_trait_speed:" + Math.Round((float)genetics.Speed / 1.275f, 1) + ", $cg_trait_health:" + Math.Round((float)genetics.Health / 1.275f, 1) + ", $cg_trait_armor:" + Math.Round(100f / (387f / ((float)genetics.Armor + 64f) - 1.01f), 1) + "\n $cg_trait_size:" + Math.Round(100f * ((float)(genetics.Size * genetics.Size) / 130000f + (float)genetics.Size / 200f + 0.25f), 1) + ", $cg_trait_productivity:" + Math.Round(60f + 100f * ((float)genetics.Productivity * CreatureGenetics.ProdMultiplier), 0) + "%, $cg_trait_drops:" + Math.Round(60f + 100f * ((float)genetics.Drops * CreatureGenetics.DropMultiplier), 0) + "%" + text2; } genetics.HoverText = Localization.instance.Localize(text); __result += text; } } public class PrefabManager : MonoBehaviour { public GameObject Root; private static AssetBundle Assets; public const string assetBundleName = "cg_assets"; public const string assetPath = "Assets/MeldursonAssets/"; public static GameObject GeneticsHatPrefab; public static Dictionary ShaderDict = new Dictionary(); public static ZNetScene zns; private void Awake() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown Root = new GameObject("PrefabList"); Root.transform.SetParent(CreatureGenetics.Root.transform); Root.SetActive(false); Assets = Utils.LoadAssetBundle("cg_assets", Assembly.GetExecutingAssembly()); GeneticsHatPrefab = Assets.LoadAsset("Assets/MeldursonAssets/TamingHat.prefab"); ((Object)GeneticsHatPrefab).name = "GeneticsHat"; } public static AssetBundle getAssetBundle() { return Assets; } public static void ItemReg() { DBG.blogDebug("ItemReg"); if (CreatureGenetics.useDNA) { addItem(GeneticsHatPrefab, CreatureGenetics.GeneticsHat_Recipe.Value, CreatureGenetics.GeneticsHat_Station.Value); } else { removeItem("GeneticsHat"); } } private static void removeItem(string prefabName) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(prefabName); if (!Object.op_Implicit((Object)(object)itemPrefab)) { DBG.blogWarning("cannot remove: " + prefabName + " as not in OBjectDB"); } else { ObjectDB.instance.m_items.Remove(itemPrefab); } } public static void addItem(GameObject go, string recipe, string station) { if (Object.op_Implicit((Object)(object)ObjectDB.instance.GetItemPrefab(((Object)go).name))) { DBG.blogDebug("Has Item"); if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { DBG.blogWarning("addItem resetting: " + ((Object)go).name + " recipe"); ResetRecipe(recipe, station, ((Object)go).name); } DBG.blogDebug("already in oDB: " + ((Object)go).name); } else { DBG.blogDebug("addItem adding: " + ((Object)go).name + " to ObjectDB: " + ((Object)ObjectDB.instance).name); Utils.addItemToODB(GeneticsHatPrefab, ObjectDB.instance); if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { ResetRecipe(recipe, station, ((Object)go).name); } } } private static Recipe ResetRecipe(string recipeConfig, string craftingStation, string item) { if (recipeConfig == "" || craftingStation == "") { return null; } GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(item); DBG.blogDebug("resetting: " + item + " recipe"); if ((Object)(object)itemPrefab == (Object)null) { DBG.blogWarning(item + " is null"); return null; } ItemDrop item2 = default(ItemDrop); if (!itemPrefab.TryGetComponent(ref item2)) { DBG.blogWarning(item + " does not have itemDrop"); return null; } Recipe val = ScriptableObject.CreateInstance(); ((Object)val).name = "Recipe_" + item; val.m_item = item2; string[] array = craftingStation.Split(new char[1] { ':' }); GameObject prefab = ZNetScene.instance.GetPrefab(array[0]); CraftingStation val2 = default(CraftingStation); if ((Object)(object)prefab == (Object)null || !prefab.TryGetComponent(ref val2)) { DBG.blogWarning("invalid crafting station: " + array[0]); return null; } val.m_craftingStation = val2; val.m_repairStation = val2; if (array.Length > 1 && int.TryParse(array[1], out var result)) { val.m_minStationLevel = result; } else { val.m_minStationLevel = 5; } string[] array2 = recipeConfig.Split(new char[1] { ',' }); int amt = 1; int upgrade_amt = 1; List list = new List(); for (int i = 0; i < array2.Length; i++) { string[] array3 = array2[i].Split(new char[1] { ':' }); if (array3.Length > 1 && int.TryParse(array3[1], out var result2)) { if (array3.Length > 2 && int.TryParse(array3[2], out var result3)) { amt = result2; upgrade_amt = result3; } else { amt = result2; upgrade_amt = Mathf.RoundToInt((float)result2 * 0.75f); } } Requirement val3 = makeRequirment(array3[0], amt, upgrade_amt); if (val3 == null) { return null; } list.Add(val3); } val.m_resources = list.ToArray(); ObjectDB.instance.m_recipes.Add(val); return val; } private static Requirement makeRequirment(string itemStr, int amt, int upgrade_amt) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown Requirement val = new Requirement(); GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(itemStr); ItemDrop resItem = default(ItemDrop); if (!Object.op_Implicit((Object)(object)itemPrefab) || !itemPrefab.TryGetComponent(ref resItem)) { DBG.blogDebug("Ingredient: " + itemStr + " is not found"); return null; } val.m_amount = amt; val.m_amountPerLevel = upgrade_amt; val.m_resItem = resItem; return val; } public static void FixShaders(GameObject go) { DBG.blogDebug("Start Fixing SHaders for " + ((Object)go).name); Renderer[] componentsInChildren = go.GetComponentsInChildren(); Renderer[] array = componentsInChildren; foreach (Renderer val in array) { Material[] materials = val.materials; foreach (Material val2 in materials) { string name = ((Object)val2.shader).name; DBG.blogDebug("Shader " + name + " is attempting to be switched"); if (name == "Standard") { DBG.blogDebug("Skipping Standard"); continue; } Shader fixedShader = getFixedShader(name); if ((Object)(object)fixedShader != (Object)null) { val2.shader = fixedShader; DBG.blogDebug("Switched Shader for " + ((Object)go).name); } } } } private static GameObject FindShaderObject(string name) { ZNetScene instance = ZNetScene.instance; if ((Object)(object)instance == (Object)null) { instance = zns; } if (instance.m_namedPrefabs.Count > 0) { DBG.blogDebug("znet has init when setting shader: " + name); return instance.GetPrefab(name); } DBG.blogDebug("znet is init when setting shader: " + name); return instance.m_prefabs.Find((GameObject x) => ((Object)x).name.Contains(name)); } private static Shader getFixedShader(string shaderName) { if (ShaderDict.TryGetValue(shaderName, out var value)) { return value; } Shader val = null; try { string text = shaderName; string text2 = text; GameObject val2; if (!(text2 == "Custom/Vegetation")) { if (text2 == "Standard") { return null; } if (ShaderDict.TryGetValue("Standard", out var value2)) { return value2; } val2 = FindShaderObject("AmberPearl"); if ((Object)(object)val2 != (Object)null) { val = val2.GetComponentInChildren().material.shader; shaderName = "Standard"; ShaderDict.Add(shaderName, val); } return val; } val2 = FindShaderObject("AshlandsBranch1"); if ((Object)(object)val2 != (Object)null) { val = ((Component)val2.transform.GetChild(0)).GetComponent().material.shader; } } catch { DBG.blogWarning("Failed shader fix with " + shaderName); if (ShaderDict.TryGetValue("Standard", out var value3)) { return value3; } GameObject val2 = FindShaderObject("AmberPearl"); if ((Object)(object)val2 != (Object)null) { val = val2.GetComponentInChildren().material.shader; shaderName = "Standard"; ShaderDict.Add(shaderName, val); return val; } DBG.blogWarning("Failed secondary fix with " + shaderName); } if (((Object)(object)val != (Object)null) & !ShaderDict.ContainsKey(shaderName)) { ShaderDict.Add(shaderName, val); } return val; } } internal class DBG { private const uint GENERIC_WRITE = 1073741824u; private const uint FILE_SHARE_READ = 1u; private const uint FILE_SHARE_WRITE = 2u; private const uint OPEN_EXISTING = 3u; private const uint STD_OUTPUT_HANDLE = 4294967285u; private const ushort FOREGROUND_BLUE = 1; private const ushort FOREGROUND_GREEN = 2; private const ushort FOREGROUND_RED = 4; private const ushort FOREGROUND_INTENSITY = 8; private static readonly IntPtr consoleHandle = GetStdHandle(4294967285u); [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr GetStdHandle(uint nStdHandle); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetConsoleTextAttribute(IntPtr hConsoleOutput, ushort wAttributes); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool WriteConsole(IntPtr hConsoleOutput, string lpBuffer, uint nNumberOfCharsToWrite, out uint lpNumberOfCharsWritten, IntPtr lpReserved); public static void blogInfo(object o) { CreatureGenetics.logger.LogInfo(o); } public static void blogWarning(object o) { CreatureGenetics.logger.LogWarning(o); } public static void blogDebug(object o) { if (CreatureGenetics.debugout.Value) { CreatureGenetics.logger.LogWarning(o); } } public static void blogDebugExtra(object o) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 if (CreatureGenetics.debugExtra.Value) { if ((int)Application.platform == 2) { SetConsoleTextAttribute(consoleHandle, 10); string text = $"[DNA:CreatureGenetics] {o}\r\n"; WriteConsole(consoleHandle, text, (uint)text.Length, out var _, IntPtr.Zero); SetConsoleTextAttribute(consoleHandle, 15); } else { CreatureGenetics.logger.LogMessage(o); } } } public static void tryblogDebug(object o, object o_backup) { try { if (CreatureGenetics.debugout.Value) { CreatureGenetics.logger.LogWarning(o); } } catch { CreatureGenetics.logger.LogWarning(o_backup); } } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("meldurson.CreatureGenetics", "CreatureGenetics", "0.0.1")] public class CreatureGenetics : BaseUnityPlugin { [Serializable] public class GeneticsConfig : ICloneable { public string PrefabName { get; set; } = ""; public bool canMateWithSelf { get; set; } = true; public List ListofRandomOffspring { get; set; } = new List(); public bool offspringOnly { get; set; } = false; public List allProcPrefabs { get; set; } = new List(); public List ProcEggPrefabs { get; set; } = new List(); public List mateNames { get; set; } = new List(); public GameObject baseOffspring { get; set; } = null; public GeneticsConfig() { } public GeneticsConfig(GeneticsConfig_pkg pkg) { PrefabName = pkg.PrefabName; canMateWithSelf = pkg.canMateWithSelf; offspringOnly = pkg.offspringOnly; foreach (string item in pkg.RandomOffspringString) { if (string.IsNullOrEmpty(item)) { continue; } specificMates specificMates = new specificMates(); string[] array = item.Split(new char[1] { '|' }); specificMates.prefabName = array[0]; if (array.Length < 2) { ListofRandomOffspring.Add(specificMates); continue; } string[] array2 = array[1].Split(new char[1] { ',' }); int num = array2.Length; string[] array3 = array2; foreach (string text in array3) { chanceOffspring chanceOffspring = new chanceOffspring(); string[] array4 = text.Split(new char[1] { ':' }); chanceOffspring.prefabName = array4[0]; if (!string.IsNullOrEmpty(chanceOffspring.prefabName)) { float result; if (array4.Length < 2) { specificMates.possibleOffspring.Add(chanceOffspring); } else if (!float.TryParse(array4[1], out result)) { DBG.blogWarning("Could not parse chance from config: " + text + ", setting to default chance"); specificMates.possibleOffspring.Add(chanceOffspring); } else { chanceOffspring.chance = result; specificMates.possibleOffspring.Add(chanceOffspring); DBG.blogDebug("Successfully added " + text + " as offspring of " + specificMates.prefabName); } } } ListofRandomOffspring.Add(specificMates); DBG.blogDebug("Successfully added config for " + specificMates.prefabName + " to " + PrefabName); } } public object Clone() { return MemberwiseClone(); } } [Serializable] public class GeneticsConfig_pkg : ICloneable { public string PrefabName { get; set; } = ""; public bool canMateWithSelf { get; set; } = true; public List RandomOffspringString { get; set; } = new List(); public bool offspringOnly { get; set; } = false; public GeneticsConfig_pkg(GeneticsConfig config) { PrefabName = config.PrefabName; canMateWithSelf = config.canMateWithSelf; offspringOnly = config.offspringOnly; foreach (specificMates item in config.ListofRandomOffspring) { string text = item.prefabName + "|"; foreach (chanceOffspring item2 in item.possibleOffspring) { text = text + item2.prefabName + ":" + item2.chance + ","; } text.TrimEnd(new char[1] { ',' }); RandomOffspringString.Add(text); } } public object Clone() { return MemberwiseClone(); } } [Serializable] public class specificMates : ICloneable { public string prefabName { get; set; } = ""; public List possibleOffspring { get; set; } = new List(); public object Clone() { return MemberwiseClone(); } } [Serializable] public class chanceOffspring : ICloneable { public string prefabName { get; set; } = ""; public GameObject offspring { get; set; } = null; public float chance { get; set; } = 100f; public object Clone() { return MemberwiseClone(); } } public const string versionNumber = "0.0.1"; public const string versionMinimum = "0.0.1"; public const string modName = "CreatureGenetics"; public const string GUID = "meldurson.CreatureGenetics"; public static ManualLogSource logger; public static Dictionary customGeneticsList = new Dictionary(); public static GameObject Root; public static PrefabManager prefabManager; public static CfgPackage CfgPackage; public static bool ServerConfigReceived = false; public static bool localizeLoaded = false; public static float DNAVarianceMod = 0.1f; public static int sizeMax256 = 255; public static int sizeMin256 = 0; public static bool useDNA = true; public static bool useCLLC = false; public static bool useMonMod = false; public static bool useSLS = false; public static bool hasYBR = false; public static float DropMultiplier = 0.0141f; public static float ProdMultiplier = 0.0141f; public static float centerProd = 24f; public static float centerDrop = 24f; public static Harmony harmony = new Harmony("meldurson.CreatureGenetics"); public static ConfigEntry debugout; public static ConfigEntry debugExtra; public static ConfigEntry useExternalYML; public static ConfigEntry useDNAColor; public static ConfigEntry onlyDNABrightness; public static ConfigEntry useDNATraits; public static ConfigEntry wildDNAVariance; public static ConfigEntry breedingDNAVariance; public static ConfigEntry maxDropMultiDNA; public static ConfigEntry maxProductivityDNA; public static ConfigEntry MaximumSizeDNA; public static ConfigEntry MinimumSizeDNA; public static ConfigEntry allowLvlMutation; public static ConfigEntry MutationChanceLvl; public static ConfigEntry MaxMutationLvl; public static ConfigEntry allowEffectsMutation; public static ConfigEntry MutationChanceEffects; public static ConfigEntry GeneticsHat_Recipe; public static ConfigEntry GeneticsHat_Station; public static ConfigSync configSync = new ConfigSync("meldurson.CreatureGenetics") { DisplayName = "CreatureGenetics", CurrentVersion = "0.0.1", MinimumRequiredVersion = "0.0.1" }; private void Awake() { //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown logger = ((BaseUnityPlugin)this).Logger; debugout = config("1:General", "Debug Output", value: false, "Determines if debug is output to bepinex log", synchronizedSetting: false); debugExtra = config("1:General", "Debug Genetics Calculations", value: false, "Determines if debug for Genetics calculations is output to bepinex log (LOTS of lines of debug!)", synchronizedSetting: false); useExternalYML = config("1:General", "Use External YML", value: false, "Determines if you want to use an external YML for setting your tames or just use the defaults given in the mod", synchronizedSetting: false); useDNAColor = config("3.0:Custom Procreation", "Use Color DNA", value: true, "Determines if you want to use a DNA system for colors"); useDNATraits = config("3.0:Custom Procreation", "Use Trait DNA", value: true, "Determines if you want to use a DNA system for physical traits (Health,Speed,Defense,Size,etc.)"); onlyDNABrightness = config("3.0:Custom Procreation", "Only have Brightness Changes", value: false, "Determines if you want to only have color dna change the brightness and not RGB"); maxDropMultiDNA = config("3.0:Custom Procreation", "Maximum Drop Multiplier for DNA", 3f, "Determines max drop multiplier in DNA"); maxProductivityDNA = config("3.0:Custom Procreation", "Maximum Productivity Speed Multiplier for DNA", 3f, "Determines max productivity chance multiplier in DNA"); wildDNAVariance = config("3.0:Custom Procreation", "Wild DNA Variance", 15, "Determines how random the wild creatures DNA will be or how likely the DNA will be further away from normal (number is in percent, maximum is 50 or 50%)"); breedingDNAVariance = config("3.0:Custom Procreation", "Breeding DNA Variance", 5, "Determines the maximum random change a trait can have when breeding, this decreases as you get close the the maximum or minimum (number is in percent, minimum is 1 or 1%)"); MaximumSizeDNA = config("3.0:Custom Procreation", "Maximum Size for DNA", 2f, "Determines the maximum size that a creature can get with variation to size (useful if needed for compatibility with other mods) The maximum range is 0.25-2"); MinimumSizeDNA = config("3.0:Custom Procreation", "Minimum Size for DNA", 0.25f, "Determines the minimum size that a creature can get with variation to size (useful if needed for compatibility with other mods) The maximum range is 0.25-2"); allowLvlMutation = config("3.1:Mutation", "Allow mutation of Level", value: true, "Determines if you want a chance for the lvl of an offspring to mutate when breeding"); MutationChanceLvl = config("3.1:Mutation", "Level Mutation Chance", 5f, "Determines the chance the level will mutate when breeding (5 is 5%, 100 is 100%)"); MaxMutationLvl = config("3.1:Mutation", "Maximum Mutation Level", -1, "When a creature mutates it has a possibility of the level going up, this is a cap so the level cannot go above this, -1 is no cap"); allowEffectsMutation = config("3.1:Mutation", "Allow mutation of Special Effects", value: true, "Determines if you want a chance for the effects to mutate when breeding (CLLC,MonsterModifiers,SLS)"); MutationChanceEffects = config("3.1:Mutation", "Effects Mutation Chance", 5f, "Determines the chance the special effects will mutate when breeding (5 is 5%, 100 is 100%)"); GeneticsHat_Recipe = config("4: Recipes", "Genetics Hat Recipe", "Iron:6:3,TrophyDraugr:1,Root:10:3,DeerHide:15:5", "What is the recipe for crafting the Genetics Hat, separate initial amount and upgrade amounts with : and different items with ,"); GeneticsHat_Station = config("4: Recipes", "Genetics Hat Station", "piece_workbench:4", "What is the required Crafting Station and Level, separated by a : such as piece_workbench:3 would be lvl 3 Workbench (vanilla stations are: piece_workbench, forge, piece_cauldron, piece_stonecutter, piece_artisanstation, blackforge, piece_magetable, piece_MeadCauldron, piece_preptable"); YAMLReadWrite.UseFileOpenReadTextWithSystemTextYaml(); Root = new GameObject("CreatureGenetics Root"); prefabManager = Root.AddComponent(); Object.DontDestroyOnLoad((Object)(object)Root); useCLLC = Chainloader.PluginInfos.ContainsKey("org.bepinex.plugins.creaturelevelcontrol"); useMonMod = Chainloader.PluginInfos.ContainsKey("warpalicious.MonsterModifiers"); useSLS = Chainloader.PluginInfos.ContainsKey("MidnightsFX.StarLevelSystem"); hasYBR = Chainloader.PluginInfos.ContainsKey("Yggdrah.BetterRiding"); PerformPatches(); PostSyncConfig(); } private ConfigEntry config(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(group, name, value, val); SyncedConfigEntry syncedConfigEntry = configSync.AddConfigEntry(val2); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry config(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } public static void PostSyncConfig() { useDNA = useDNAColor.Value || useDNATraits.Value; if (useDNA) { DBG.blogDebug("Using DNA"); if (wildDNAVariance.Value <= 50) { DNAVarianceMod = (float)wildDNAVariance.Value / 10f; } else { DNAVarianceMod = 5f; } centerProd = 102f / (maxProductivityDNA.Value - 0.6f); centerDrop = 102f / (maxDropMultiDNA.Value - 0.6f); DropMultiplier = (maxDropMultiDNA.Value - 0.6f) / 255f; ProdMultiplier = (maxProductivityDNA.Value - 0.6f) / 255f; sizeMax256 = Mathf.FloorToInt(-325f + (float)Math.Sqrt(73125f + 130000f * Mathf.Clamp(MaximumSizeDNA.Value, 0.25f, 2f))); sizeMin256 = Mathf.FloorToInt(-325f + (float)Math.Sqrt(73125f + 130000f * Mathf.Clamp(MinimumSizeDNA.Value, 0.25f, 2f))); DBG.blogDebug("Size Range is (" + sizeMin256 + "," + sizeMax256 + ")"); } } public void PerformPatches() { harmony.PatchAll(typeof(CreatureGenetics)); harmony.PatchAll(typeof(GeneticsPatches)); harmony.PatchAll(typeof(GeneticsPatches.InterceptProcreationFindMates)); harmony.PatchAll(typeof(GeneticsPatches.InterceptEggGrowup)); harmony.PatchAll(typeof(GeneticsPatches.InterceptGrowup)); harmony.PatchAll(typeof(GeneticsHover)); harmony.PatchAll(typeof(CfgPackage)); harmony.PatchAll(typeof(CfgPackage.GameStartPatch)); if (useSLS) { harmony.PatchAll(typeof(SLS_CG)); } if (hasYBR) { BetterRiding.removeGrowupPatch(); } IEnumerable patchedMethods = harmony.GetPatchedMethods(); DBG.blogDebug("Patched Methods="); foreach (MethodBase item in patchedMethods) { DBG.blogDebug(item.ReflectedType?.ToString() + ":" + item.Name + " is patched"); } } [HarmonyPatch(typeof(ZNetScene), "Shutdown")] [HarmonyPostfix] private static void Postfix() { DBG.blogInfo("Reseting Genetics Lists"); YAMLReadWrite.baseConfig = new GeneticsConfig(); YAMLReadWrite.groupConfigs = new Dictionary(); YAMLReadWrite.UseFileOpenReadTextWithSystemTextYaml(); } [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] [HarmonyPrefix] private static void Prefix_ObjectDB_CopyOther(ObjectDB __instance, ObjectDB other) { if ((Object)(object)other != (Object)null && ((Object)other).name == "_NetScene") { Utils.addItemToODB(PrefabManager.GeneticsHatPrefab, other); } } [HarmonyPostfix] [HarmonyPriority(5)] [HarmonyPatch(typeof(ObjectDB), "Awake")] private static void Postfix_ODB_Awake(ObjectDB __instance) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (!localizeLoaded) { Localizer.Load(); DBG.blogDebug("Loaded Localizations"); localizeLoaded = true; } Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name != "main") { DBG.blogDebug("Not Main Scene"); return; } if (!Object.op_Implicit((Object)(object)ZNet.instance)) { DBG.blogDebug("No instance of ZNet"); return; } if (!ZNet.instance.IsServer()) { DBG.blogDebug("ZNet not server"); return; } if ((Object)(object)PrefabManager.zns == (Object)null) { PrefabManager.zns = ((Component)__instance).gameObject.GetComponent(); } PrefabManager.ItemReg(); } } public static class Utils { public static AssetBundle LoadAssetBundle(string bundleName, Assembly assembly) { string text = null; try { text = assembly.GetManifestResourceNames().Single((string str) => str.EndsWith(bundleName)); } catch { } if (text == null) { DBG.blogWarning("Could not find asset by the name " + bundleName); return null; } Stream manifestResourceStream = assembly.GetManifestResourceStream(text); AssetBundle result; using (manifestResourceStream) { result = AssetBundle.LoadFromStream(manifestResourceStream); } return result; } public static T CopyBroComponent(this Component comp, TU other) where T : Component { Type baseType = ((object)comp).GetType().BaseType; IEnumerable fields = baseType.GetFields(); foreach (FieldInfo item in fields) { object value = item.GetValue(other); try { item.SetValue(comp, value); } catch { DBG.blogDebug("Failed bro copy for: " + item); } } return (T)(object)((comp is T) ? comp : null); } public static string GetPrefabName(string name) { int num = name.IndexOfAny(new char[2] { '(', ' ' }); if (num != -1) { return name.Remove(num); } return name; } public static bool addToZNS(GameObject go) { ZNetScene instance = ZNetScene.instance; if (!Object.op_Implicit((Object)(object)instance)) { return false; } int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)go).name); if (instance.m_namedPrefabs.ContainsKey(stableHashCode)) { DBG.blogDebug("ZNS already has " + ((Object)go).name); return false; } if (Object.op_Implicit((Object)(object)go.GetComponent())) { instance.m_prefabs.Add(go); } else { instance.m_nonNetViewPrefabs.Add(go); } instance.m_namedPrefabs.Add(stableHashCode, go); DBG.blogDebug("Added " + ((Object)go).name + " to zns"); return true; } public static bool addItemToODB(GameObject go, ObjectDB odb) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)go).name); if ((Object)(object)go.GetComponent() == (Object)null) { DBG.blogDebug("Does not have ItemDrop: " + ((Object)go).name); return false; } if (odb.m_itemByHash.ContainsKey(stableHashCode)) { DBG.blogDebug("Already added item " + ((Object)go).name); return false; } addToZNS(go); odb.m_items.Add(go); odb.m_itemByHash.Add(stableHashCode, go); return true; } public static void cloneProperties(TOne copyTo, TTwo CopyFrom) where TOne : Component where TTwo : Component { FieldInfo[] fields = ((object)CopyFrom).GetType().GetFields(); foreach (FieldInfo fieldInfo in fields) { try { if ((fieldInfo.GetValue(copyTo) != null) & (fieldInfo.GetValue(CopyFrom) != fieldInfo.GetValue(copyTo))) { fieldInfo.SetValue(copyTo, fieldInfo.GetValue(CopyFrom)); DBG.blogDebug("From " + ((object)CopyFrom).GetType()?.ToString() + fieldInfo.Name + " set to " + fieldInfo.GetValue(copyTo)); } } catch { DBG.blogDebug(((object)copyTo).GetType()?.ToString() + " does not have " + fieldInfo.Name); } } } public static Color colFromHex(string hexStr) { //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) try { DBG.blogDebug("in colfromhex"); int num = int.Parse(hexStr.Replace("#", ""), NumberStyles.HexNumber); float num2 = num & 0xFF; float num3 = (num >> 8) & 0xFF; float num4 = (num >> 16) & 0xFF; DBG.blogDebug("r,g,b=" + num4 + "," + num3 + "," + num2); Color result = default(Color); ((Color)(ref result))..ctor(num4 / 255f, num3 / 255f, num2 / 255f); return result; } catch { DBG.blogWarning("Not a valid hex color code"); return Color.white; } } public static Texture2D changeEggTex(Texture2D oldTex, Color col, bool invertShadow) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0199: 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_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: 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_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0141: 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_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebug("in change color"); Texture2D val = Object.Instantiate(oldTex); Color[] array = (Color[])(object)new Color[3] { col, col, col }; int num = Mathf.Min(3, ((Texture)val).mipmapCount); Color val3 = default(Color); for (int i = 0; i < num; i++) { Color[] pixels = val.GetPixels(i); DBG.blogDebug("cols.length=" + pixels.Length); for (int j = 0; j < pixels.Length; j++) { Color val2 = pixels[j]; if (invertShadow) { ((Color)(ref val3))..ctor(1f - val2.r, 1f - val2.g, 1f - val2.b); Color val4 = val3 - new Color(Mathf.Min(val3.r, 0.6f), Mathf.Min(val3.g, 0.6f), Mathf.Min(val3.b, 0.6f)); Color val5 = pixels[j] * col; pixels[j] = val5 - val5 * val4 * 1f; pixels[j] = changeHue(val5, 0.5f) * val3 * 1.3f + pixels[j]; } else { Color val6 = Color.grey * val2; val6 -= new Color(Mathf.Min(val6.r, 0.25f), Mathf.Min(val6.g, 0.25f), Mathf.Min(val6.b, 0.25f)); pixels[j] *= col; } pixels[j].a = val2.a; } val.SetPixels(pixels, i); } val.Apply(false); return val; } public static Color changeHue(Color col, float hue) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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_0026: Unknown result type (might be due to invalid IL or missing references) float num2 = default(float); float num3 = default(float); float num = default(float); Color.RGBToHSV(col, ref num, ref num2, ref num3); num = (num + hue) % 1f; return Color.HSVToRGB(num, num2, num3); } public static T GetCopyOf(this Component comp, T other) where T : Component { Type type = ((object)comp).GetType(); if (type != ((object)other).GetType()) { return default(T); } List list = new List(); Type baseType = type.BaseType; while (baseType != null && !(baseType == typeof(MonoBehaviour))) { list.Add(baseType); baseType = baseType.BaseType; } IEnumerable enumerable = type.GetProperties(BindingFlags.Public); foreach (Type item in list) { enumerable = enumerable.Concat(item.GetProperties(BindingFlags.Public)); } enumerable = from property in enumerable where !(type == typeof(Rigidbody)) || !(property.Name == "inertiaTensor") where !property.CustomAttributes.Any((CustomAttributeData attribute) => attribute.AttributeType == typeof(ObsoleteAttribute)) select property; foreach (PropertyInfo pinfo in enumerable) { if (pinfo.CanWrite && !enumerable.Any((PropertyInfo e) => e.Name == $"shared{char.ToUpper(pinfo.Name[0])}{pinfo.Name.Substring(1)}")) { try { pinfo.SetValue(comp, pinfo.GetValue(other, null), null); } catch { } } } IEnumerable enumerable2 = type.GetFields(BindingFlags.Public); foreach (FieldInfo finfo in enumerable2) { foreach (Type item2 in list) { if (!enumerable2.Any((FieldInfo e) => e.Name == $"shared{char.ToUpper(finfo.Name[0])}{finfo.Name.Substring(1)}")) { enumerable2 = enumerable2.Concat(item2.GetFields(BindingFlags.Public)); } } } foreach (FieldInfo item3 in enumerable2) { item3.SetValue(comp, item3.GetValue(other)); } enumerable2 = enumerable2.Where((FieldInfo field) => field.CustomAttributes.Any((CustomAttributeData attribute) => attribute.AttributeType == typeof(ObsoleteAttribute))); foreach (FieldInfo item4 in enumerable2) { item4.SetValue(comp, item4.GetValue(other)); } return (T)(object)((comp is T) ? comp : null); } public static T AddComponent(this GameObject go, T toAdd) where T : Component { return go.AddComponent(((object)toAdd).GetType()).GetCopyOf(toAdd); } public static T CopyIntoParent(T go, T parent) where T : Component { //IL_0055: Unknown result type (might be due to invalid IL or missing references) T val = Object.Instantiate(go); ((Object)(object)val).name = ((Object)(object)go).name; ((Component)val).transform.parent = ((Component)parent).transform; ((Component)val).transform.localPosition = new Vector3(0f, 0f, 0f); return val; } public static void addOrUpdateCustomData(Dictionary dic, string key, string newValue) { if (dic.ContainsKey(key)) { DBG.blogDebug("Already had " + key); dic[key] = newValue; } else { DBG.blogDebug("Added " + key + " to dictionary"); dic.Add(key, newValue); } } public static string iDropGetCustData(ItemDrop iDrop, string key) { string result = ""; if (Object.op_Implicit((Object)(object)iDrop) && iDrop.m_itemData.m_customData.TryGetValue(key, out var value)) { result = value; DBG.blogDebug("got " + key + " from iDrop"); } return result; } public static Color ShiftHue(Color color, float hueShiftDegrees) { //IL_0069: 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_0077: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_02d1: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) DBG.blogDebugExtra("ShiftHue(" + hueShiftDegrees + "), input = " + color.r + ", " + color.g + ", " + color.b); float r = color.r; float g = color.g; float b = color.b; float num = Mathf.Max(new float[3] { r, g, b }); float num2 = Mathf.Min(new float[3] { r, g, b }); float num3 = num - num2; float num4 = ((num3 == 0f) ? 0f : ((num == r) ? (60f * ((g - b) / num3 % 6f)) : ((num != g) ? (60f * ((r - g) / num3 + 4f)) : (60f * ((b - r) / num3 + 2f))))); if (num4 < 0f) { num4 += 360f; } float num5 = ((num == 0f) ? 0f : (num3 / num)); float num6 = num; num4 = (num4 + hueShiftDegrees * 360f) % 360f; if (num4 < 0f) { num4 += 360f; } float num7 = num6 * num5; float num8 = num7 * (1f - Math.Abs(num4 / 60f % 2f - 1f)); float num9 = num6 - num7; float num10; float num11; float num12; if (num4 < 60f) { num10 = 0f; num11 = num8; num12 = num7; } else if (num4 < 120f) { num10 = 0f; num11 = num7; num12 = num8; } else if (num4 < 180f) { num10 = num8; num11 = num7; num12 = 0f; } else if (num4 < 240f) { num10 = num7; num11 = num8; num12 = 0f; } else if (num4 < 300f) { num10 = num7; num11 = 0f; num12 = num8; } else { num10 = num8; num11 = 0f; num12 = num7; } DBG.blogDebug("Hue shifted to=" + (num12 + num9) + "," + (num11 + num9) + "," + (num10 + num9)); return new Color(num12 + num9, num11 + num9, num10 + num9); } public static void RemovePatch(MethodBase method, bool isPrefix, string[] patchNames) { Patches patchInfo = Harmony.GetPatchInfo(method); if (patchInfo == null) { DBG.blogInfo("no patches on " + method.Name); return; } DBG.blogWarning("Attempting to remove Patches from " + method.Name); ReadOnlyCollection readOnlyCollection = ((!isPrefix) ? patchInfo.Postfixes : patchInfo.Prefixes); DBG.blogInfo("Patch owners: " + string.Join(",", patchInfo.Owners)); foreach (Patch item in readOnlyCollection) { DBG.blogInfo("owner: " + item.owner); DBG.blogInfo("patch method Name: " + item.PatchMethod.Name); int priority = item.priority; DBG.blogInfo("priority: " + priority); for (int i = 0; i < patchNames.Length; i++) { string[] array = patchNames[i].Split(new char[1] { '/' }); if (item.owner == array[0] && (array.Length < 2 || item.PatchMethod.Name == array[1])) { CreatureGenetics.harmony.Unpatch(method, item.PatchMethod); DBG.blogWarning("Unpatched method Name: " + item.PatchMethod.Name); } } } } } public class GaussianGenerator { private Random _rng = new Random(); private double? _spareValue = null; public double NextDouble() { if (_spareValue.HasValue) { double value = _spareValue.Value; _spareValue = null; return value; } double num; double num2; double num3; do { num = 2.0 * _rng.NextDouble() - 1.0; num2 = 2.0 * _rng.NextDouble() - 1.0; num3 = num * num + num2 * num2; } while (num3 > 1.0 || num3 == 0.0); double num4 = Math.Sqrt(-2.0 * Math.Log(num3) / num3); _spareValue = num * num4; return num2 * num4; } public double NextDouble(double mu, double sigma) { return mu + NextDouble() * sigma; } } public class YAMLReadWrite { public class GeneticsConfigYML { public List writeValue = new List(); public string PrefabName { get; set; } = null; public bool canMateWithSelf { get; set; } = true; public string specificOffspringString { get; set; } = ""; public List ListofRandomOffspring { get; set; } = new List(); public bool offspringOnly { get; set; } = false; public List allProcPrefabs { get; set; } = new List(); public string mates { get; set; } = ""; } public static Dictionary groupConfigs = new Dictionary(); public static CreatureGenetics.GeneticsConfig baseConfig = new CreatureGenetics.GeneticsConfig(); public static List UseFileOpenReadTextWithSystemTextYaml() { string[] files = Directory.GetFiles(Path.GetDirectoryName(Paths.BepInExConfigPath), "CreatureGenetics_*.yml"); List list = new List(); if (files.Count() > 0) { string[] array = files; foreach (string path in array) { string ymlContents = File.ReadAllText(path); List list2 = ParseTames(ymlContents); if (list2[0].PrefabName == "PrefabName") { list2.RemoveAt(0); } foreach (CreatureGenetics.GeneticsConfig tame in list2) { if (!list.Exists((CreatureGenetics.GeneticsConfig x) => x.PrefabName == tame.PrefabName) && !((tame.PrefabName ?? "") == "")) { list.Add(tame); if (!CreatureGenetics.customGeneticsList.ContainsKey(tame.PrefabName)) { CreatureGenetics.customGeneticsList.Add(tame.PrefabName, tame); } } } } } else { DBG.blogWarning("no config files"); string text = Path.Combine(Path.GetDirectoryName(Paths.BepInExConfigPath), Path.GetFileName("CreatureGenetics_DefaultGeneticsList.yml")); DBG.blogDebug("createfile_path=" + text); DBG.blogDebug("Did not find Setting in config, creating from default"); using StreamWriter streamWriter = File.CreateText(text); streamWriter.Write(loadDefaultConfig()); } return list; } private static string loadDefaultConfig() { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith("DefaultGeneticsList.yml")); string text = ""; using (Stream stream = executingAssembly.GetManifestResourceStream(name)) { using StreamReader streamReader = new StreamReader(stream); text = streamReader.ReadToEnd(); } DBG.blogDebug("result=" + text); return text; } public static List ParseTames(string ymlContents) { Parser Parser = new Parser(new StringReader(ymlContents)); <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer = new DeserializerBuilder().WithNamingConvention(<009e614f-34cc-4966-aebd-f8f248231a77>CamelCaseNamingConvention.Instance).Build(); Parser.Consume<<59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart>(); if (!Parser.TryConsume<DocumentStart>(out var _)) { return new List(); } Parser.Consume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(); List list = new List(); Scalar event2; while (Parser.TryConsume<Scalar>(out event2)) { try { if (Parser.Current.GetType() != typeof(<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart) && (event2.Value ?? "") == "") { continue; } DBG.blogDebug("Parsing=" + event2.Value); CreatureGenetics.GeneticsConfig geneticsConfig = NewStripConfig(<1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer.Deserialize(Parser)); geneticsConfig.PrefabName = event2.Value; string[] array = geneticsConfig.PrefabName.Split(new char[1] { ',' }); if (array.Length == 1) { list.Add(geneticsConfig); continue; } for (int i = 0; i < array.Length; i++) { DBG.blogDebug($"allPrefabs[{i}]=" + array[i]); CreatureGenetics.GeneticsConfig geneticsConfig2 = new CreatureGenetics.GeneticsConfig(); foreach (CreatureGenetics.specificMates item in geneticsConfig.ListofRandomOffspring) { geneticsConfig2.ListofRandomOffspring.Add(item); } geneticsConfig2.PrefabName = array[i]; for (int j = 0; j < array.Length; j++) { if (i != j) { CreatureGenetics.specificMates newMate = new CreatureGenetics.specificMates { prefabName = array[j] }; adjustMates(geneticsConfig2.ListofRandomOffspring, newMate); } } geneticsConfig2.canMateWithSelf = geneticsConfig.canMateWithSelf; list.Add(geneticsConfig2); } } catch { DBG.blogWarning("Failed to parse " + event2.Value + " from yaml, check to make sure this prefab is formated correctly"); } } return list; } public static CreatureGenetics.specificMates grabSpecificMate(string prefabName, object SpecMateDict) { CreatureGenetics.specificMates specificMates = new CreatureGenetics.specificMates(); specificMates.prefabName = prefabName; if (SpecMateDict is Dictionary dictionary) { foreach (KeyValuePair item in dictionary) { string text = item.Key.ToString(); DBG.blogDebug("Offspring=" + text + ":" + item.Value); int num = Convert.ToInt32(item.Value); if (num == 0) { DBG.blogDebug("could not parse as int: " + item.Value); continue; } CreatureGenetics.chanceOffspring chanceOffspring = new CreatureGenetics.chanceOffspring(); chanceOffspring.prefabName = item.Key.ToString(); chanceOffspring.chance = num; specificMates.possibleOffspring.Add(chanceOffspring); } } return specificMates; } public static void adjustMates(List ListofRandomOffspring, CreatureGenetics.specificMates newMate) { foreach (CreatureGenetics.specificMates item in ListofRandomOffspring) { DBG.blogDebug("specMates=" + item.prefabName); foreach (CreatureGenetics.chanceOffspring item2 in item.possibleOffspring) { DBG.blogDebug("chanceOff=" + item2.prefabName + ", chance=" + item2.chance); } } CreatureGenetics.specificMates specificMates = ListofRandomOffspring.Find((CreatureGenetics.specificMates x) => x.prefabName == newMate.prefabName); if (specificMates != null) { foreach (CreatureGenetics.chanceOffspring offspring in newMate.possibleOffspring) { if (specificMates.possibleOffspring.Find((CreatureGenetics.chanceOffspring x) => x.prefabName == offspring.prefabName) == null) { DBG.blogDebug("Added to existing=" + offspring.prefabName); specificMates.possibleOffspring.Add(offspring); } } return; } DBG.blogDebug("Added new mate=" + newMate.prefabName); ListofRandomOffspring.Add(newMate); } public static CreatureGenetics.GeneticsConfig NewStripConfig(object configObj) { CreatureGenetics.GeneticsConfig geneticsConfig = new CreatureGenetics.GeneticsConfig(); if (configObj is Dictionary dictionary) { foreach (KeyValuePair item in dictionary) { string text = item.Key.ToString(); string text2 = text; string text3 = text2; if (text3 == "canMateWithSelf") { DBG.blogDebug("Setting canMateWithSelf=" + item.Value); geneticsConfig.canMateWithSelf = item.Value.ToString() != "false"; } else { DBG.blogDebug("attempt to add a mate " + text); CreatureGenetics.specificMates newMate = grabSpecificMate(text, item.Value); adjustMates(geneticsConfig.ListofRandomOffspring, newMate); } } } return geneticsConfig; } } } namespace CreatureGenetics.RPC { [Serializable] public class CfgPackage { [HarmonyPatch(typeof(Game), "Start")] public static class GameStartPatch { private static void Prefix() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown ZRoutedRpc.instance.Register("CG_RecieveConfigs", (Action)RPC_RecieveConfigs); ZRoutedRpc.instance.Register("CG_Configs", (Action)RPC_CG_Configs); DBG.blogWarning("RPCs Registered"); ZPackage val = new ZPackage(); val.Write("0.0.1"); version = val; } } public class SplitGeneDict { public string[] keys { get; set; } = new string[0]; public CreatureGenetics.GeneticsConfig_pkg[] tmtbl { get; set; } = new CreatureGenetics.GeneticsConfig_pkg[0]; } public string[] split_keys; public CreatureGenetics.GeneticsConfig_pkg[] split_tmtbl; public string[] mate_dict; public string[] trade_dict; public static ZPackage zpack; public static ZPackage version; public static void RPC_RecieveConfigs(long sender, ZPackage pkg) { DBG.blogWarning("Received Configs from Server"); if (sender == ZRoutedRpc.instance.GetServerPeerID() && pkg != null && pkg.Size() > 0) { DBG.blogWarning("Has Valid Server and Package"); Unpack(pkg); DBG.blogWarning("Unpacked"); PrefabManager.ItemReg(); } } public static void RPC_RequestServerAnnouncement_Client(long sender, ZPackage pkg) { } public static void RPC_CG_Configs(long sender, ZPackage pkg) { string text = pkg.ReadString(); DBG.blogInfo("Local version:0.0.1, remote: " + text); ZNetPeer peer = ZNet.instance.GetPeer(sender); if (ZNet.instance.IsServer()) { if (peer == null) { DBG.blogInfo("Peer is Null"); return; } DBG.blogInfo("Peer is not Null"); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "CG_RecieveConfigs", new object[1] { PackGenetics() }); } } public static void RPC_CG_Version(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); DBG.blogInfo("Local version:0.0.1, remote: " + text); if (text != "0.0.1") { DBG.blogWarning("Let Me Tame You Versions do not match"); if (ZNet.instance.IsServer()) { DBG.blogWarning("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting..."); rpc.Invoke("Error", new object[1] { 3 }); } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPostfix] private static void SyncVersionPatch(ZNetPeer peer, ref ZNet __instance) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown DBG.blogDebug("Registering version RPC handler1"); peer.m_rpc.Register("CG_Version", (Action)RPC_CG_Version); DBG.blogDebug("Invoking version check"); if (version == null) { ZPackage val = new ZPackage(); val.Write("0.0.1"); version = val; } peer.m_rpc.Invoke("CG_Version", new object[1] { version }); ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "CG_Version", new object[1] { version }); } [HarmonyPostfix] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private static void SyncConfigsPatch_New(ZRpc rpc, ref ZNet __instance) { DBG.blogDebug("Registering version RPC handler2"); CreatureGenetics.PostSyncConfig(); ZRoutedRpc.instance.InvokeRoutedRPC(__instance.GetPeer(rpc).m_uid, "CG_Configs", new object[1] { version }); } public static ZPackage PackGenetics() { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown if (zpack == null) { if (CreatureGenetics.CfgPackage == null) { CreatureGenetics.CfgPackage = new CfgPackage(); } CreatureGenetics.CfgPackage.Pack(); DBG.blogDebug("Packed List"); } else { DBG.blogDebug("Already Packed List"); } ZPackage val = new ZPackage(); return zpack; } public ZPackage Pack() { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown SplitGeneDict splitGeneDict = createsplitdict(); split_keys = splitGeneDict.keys; split_tmtbl = splitGeneDict.tmtbl; DBG.blogDebug("keysnull=" + (split_keys == null)); DBG.blogDebug("tmblnull=" + (split_tmtbl == null)); DBG.blogDebug("split_keys:" + string.Join(",", split_keys)); string[] array = split_keys; foreach (string text in array) { DBG.blogDebug("key=" + text); } CreatureGenetics.GeneticsConfig_pkg[] array2 = split_tmtbl; foreach (CreatureGenetics.GeneticsConfig_pkg geneticsConfig_pkg in array2) { DBG.blogDebug("consume=" + geneticsConfig_pkg.RandomOffspringString); } ZPackage val = new ZPackage(); DBG.blogDebug("packedpkg"); using MemoryStream memoryStream = new MemoryStream(); using (GZipStream serializationStream = new GZipStream(memoryStream, CompressionLevel.Optimal)) { new BinaryFormatter().Serialize(serializationStream, this); } DBG.blogDebug("pre buffer"); byte[] buffer = memoryStream.GetBuffer(); DBG.blogDebug("pre write"); val.Write(buffer); zpack = val; DBG.blogDebug("return packedpkg"); return val; } public static void Unpack(ZPackage package, bool setValue = true) { byte[] array = package.ReadByteArray(); DBG.blogInfo($"Deserializing {array.Length} bytes of configs"); using MemoryStream stream = new MemoryStream(array); using GZipStream serializationStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true); if (new BinaryFormatter().Deserialize(serializationStream) is CfgPackage cfgPackage) { DBG.blogInfo("Received and deserialized config package"); DBG.blogInfo("Unpackaging configs."); string[] keys = cfgPackage.split_keys; CreatureGenetics.GeneticsConfig[] array2 = new CreatureGenetics.GeneticsConfig[cfgPackage.split_tmtbl.Length]; for (int i = 0; i < cfgPackage.split_tmtbl.Length; i++) { array2[i] = new CreatureGenetics.GeneticsConfig(cfgPackage.split_tmtbl[i]); } Combinesplitdict(keys, array2); DBG.blogInfo("Successfully unpacked configs."); DBG.blogInfo("Unpacked general config"); } else { DBG.blogWarning("Received bad config package. Unable to load."); } } public CreatureGenetics.GeneticsConfig_pkg convertGeneticsCfgToPKG(CreatureGenetics.GeneticsConfig config) { return new CreatureGenetics.GeneticsConfig_pkg(config); } public SplitGeneDict createsplitdict() { DBG.blogWarning("in splitdict"); SplitGeneDict splitGeneDict = new SplitGeneDict(); int count = CreatureGenetics.customGeneticsList.Count; DBG.blogDebug("list size=" + count); splitGeneDict.keys = new string[count]; splitGeneDict.tmtbl = new CreatureGenetics.GeneticsConfig_pkg[count]; int num = 0; foreach (KeyValuePair customGenetics in CreatureGenetics.customGeneticsList) { splitGeneDict.keys[num] = customGenetics.Key; splitGeneDict.tmtbl[num] = new CreatureGenetics.GeneticsConfig_pkg(customGenetics.Value); num++; } return splitGeneDict; } private static void Combinesplitdict(string[] keys, CreatureGenetics.GeneticsConfig[] tmtbl) { int num = keys.Length; CreatureGenetics.customGeneticsList.Clear(); for (int i = 0; i < num; i++) { CreatureGenetics.customGeneticsList.Add(keys[i], tmtbl[i]); DBG.blogDebug("Added to cfglist: " + keys[i]); } } } } namespace Microsoft.CodeAnalysis { [<9d291f63-be5d-4126-90d7-6e6ba262da38>Embedded] [CompilerGenerated] internal sealed class <9d291f63-be5d-4126-90d7-6e6ba262da38>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [<9d291f63-be5d-4126-90d7-6e6ba262da38>Embedded] [CompilerGenerated] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<9d291f63-be5d-4126-90d7-6e6ba262da38>Embedded] internal sealed class <6c93d0e6-93c3-4b47-9f74-486f97e8037c>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <6c93d0e6-93c3-4b47-9f74-486f97e8037c>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <6c93d0e6-93c3-4b47-9f74-486f97e8037c>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<9d291f63-be5d-4126-90d7-6e6ba262da38>Embedded] internal sealed class <7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContextAttribute : Attribute { public readonly byte Flag; public <7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContextAttribute(byte P_0) { Flag = P_0; } } [<9d291f63-be5d-4126-90d7-6e6ba262da38>Embedded] [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace YamlDotNet { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.Name) { this.provider = provider; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public override object GetFormat(Type formatType) { return provider.GetFormat(formatType); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class Polyfills { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool Contains(this string source, char c) { return source.IndexOf(c) != -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EndsWith(this string source, char c) { if (source.Length > 0) { return source[source.Length - 1] == c; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool StartsWith(this string source, char c) { if (source.Length > 0) { return source[0] == c; } return false; } } internal static class PropertyInfoExtensions { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal static class <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions { private static readonly Func IsInstance = (PropertyInfo property) => !(property.GetMethod ?? property.SetMethod).IsStatic; private static readonly Func IsInstancePublic = (PropertyInfo property) => IsInstance(property) && (property.GetMethod ?? property.SetMethod).IsPublic; [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static Type GetImplementationOfOpenGenericInterface(this Type type, Type openGenericType) { if (!openGenericType.IsGenericType || !openGenericType.IsInterface) { throw new ArgumentException("The type must be a generic type definition and an interface", "openGenericType"); } if (IsGenericDefinitionOfType(type, openGenericType)) { return type; } return type.FindInterfaces([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Type t, object context) => IsGenericDefinitionOfType(t, context), openGenericType).FirstOrDefault(); static bool IsGenericDefinitionOfType(Type t, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object context) { if (t.IsGenericType) { return t.GetGenericTypeDefinition() == (Type)context; } return false; } } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsRequired(this MemberInfo member) { return member.GetCustomAttributes(inherit: true).Any([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.RequiredMemberAttribute"); } public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (allowPrivateConstructors) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsValueType) { return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static bool IsAssignableFrom(this Type type, Type source) { return type.IsAssignableFrom(source.GetTypeInfo()); } public static bool IsAssignableFrom(this Type type, TypeInfo source) { return type.GetTypeInfo().IsAssignableFrom(source); } public static TypeCode GetTypeCode(this Type type) { if (IsEnum(type)) { type = Enum.GetUnderlyingType(type); } if (type == typeof(bool)) { return TypeCode.Boolean; } if (type == typeof(char)) { return TypeCode.Char; } if (type == typeof(sbyte)) { return TypeCode.SByte; } if (type == typeof(byte)) { return TypeCode.Byte; } if (type == typeof(short)) { return TypeCode.Int16; } if (type == typeof(ushort)) { return TypeCode.UInt16; } if (type == typeof(int)) { return TypeCode.Int32; } if (type == typeof(uint)) { return TypeCode.UInt32; } if (type == typeof(long)) { return TypeCode.Int64; } if (type == typeof(ulong)) { return TypeCode.UInt64; } if (type == typeof(float)) { return TypeCode.Single; } if (type == typeof(double)) { return TypeCode.Double; } if (type == typeof(decimal)) { return TypeCode.Decimal; } if (type == typeof(DateTime)) { return TypeCode.DateTime; } if (type == typeof(string)) { return TypeCode.String; } return TypeCode.Object; } public static bool IsDbNull(this object value) { return value?.GetType()?.FullName == "System.DBNull"; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static PropertyInfo GetPublicProperty(this Type type, string name) { return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).FirstOrDefault([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (PropertyInfo p) => p.Name == name); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static FieldInfo GetPublicStaticField(this Type type, string name) { return type.GetRuntimeField(name); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { Func predicate = (includeNonPublic ? IsInstance : IsInstancePublic); if (!IsInterface(type)) { return type.GetRuntimeProperties().Where(predicate); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Type i) => i.GetRuntimeProperties().Where(predicate)); } public static IEnumerable GetPublicProperties(this Type type) { return GetProperties(type, 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([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (MethodInfo m) => !m.IsPublic && m.IsStatic && m.Name.Equals(name)) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static MethodInfo GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetRuntimeMethods().FirstOrDefault([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (MethodInfo m) => { if (m.IsPublic && m.IsStatic && m.Name.Equals(name)) { ParameterInfo[] parameters = m.GetParameters(); if (parameters.Length == parameterTypes.Length) { return parameters.Zip(parameterTypes, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (ParameterInfo pi, Type pt) => pi.ParameterType == pt).All((bool r) => r); } return false; } return false; }); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static MethodInfo GetPublicInstanceMethod(this Type type, string name) { return type.GetRuntimeMethods().FirstOrDefault([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (MethodInfo m) => m.IsPublic && !m.IsStatic && m.Name.Equals(name)); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static MethodInfo GetGetMethod(this PropertyInfo property, bool nonPublic) { MethodInfo methodInfo = property.GetMethod; if (!nonPublic && !methodInfo.IsPublic) { methodInfo = null; } return methodInfo; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static MethodInfo GetSetMethod(this PropertyInfo property) { return property.SetMethod; } public static IEnumerable GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static bool IsInstanceOf(this Type type, object o) { if (!(o.GetType() == type)) { return o.GetType().GetTypeInfo().IsSubclassOf(type); } return true; } public static Attribute[] GetAllCustomAttributes<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TAttribute>(this PropertyInfo member) { return Attribute.GetCustomAttributes(member, typeof(TAttribute), inherit: true); } public static bool AcceptsNull(this MemberInfo member) { object[] customAttributes = member.DeclaringType.GetCustomAttributes(inherit: true); object obj = customAttributes.FirstOrDefault([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableContextAttribute"); int num = 0; if (obj != null) { Type type = obj.GetType(); PropertyInfo property = type.GetProperty("Flag"); num = (byte)property.GetValue(obj); } object[] customAttributes2 = member.GetCustomAttributes(inherit: true); object obj2 = customAttributes2.FirstOrDefault([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (object x) => x.GetType().FullName == "System.Runtime.CompilerServices.NullableAttribute"); PropertyInfo propertyInfo = (obj2?.GetType())?.GetProperty("NullableFlags"); byte[] source = (byte[])propertyInfo.GetValue(obj2); return source.Any((byte x) => x == 2) || num == 2; } } internal static class <8b954eb7-eb7d-4a17-98c6-8793b5a2e86e>StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class BuilderSkeleton<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TBuilder> where TBuilder : BuilderSkeleton { internal <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention = <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention.Instance; internal <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention = <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention.Instance; internal <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; internal readonly <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides overrides; internal readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverterFactories; internal readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal BuilderSkeleton(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) { overrides = new <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides(); typeConverterFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> { { typeof(GuidConverter), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new GuidConverter(jsonCompatible: false) }, { typeof(<8397bddf-2f11-40f5-a93f-524634501e3b>SystemTypeConverter), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <8397bddf-2f11-40f5-a93f-524634501e3b>SystemTypeConverter() } }; typeInspectorFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(<22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(<22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention; return Self; } public TBuilder WithTypeResolver(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, Type type); public TBuilder WithAttributeOverride<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter typeConverter, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TYamlTypeConverter>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>> where) where TYamlTypeConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter wrapped, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : <87461092-0374-4a6c-919c-f5a28d630352>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent <4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent <23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TArgument, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponentBase, TComponent>(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class Deserializer : <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer { private readonly <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(<7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(<7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(TextReader input) { return Deserialize(new Parser(input)); } public T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) { return (T)Deserialize(parser, typeof(T)); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(string input) { return Deserialize(input); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(TextReader input) { return Deserialize(input); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) { return Deserialize(parser); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart @event; bool flag = parser.TryConsume<<59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart>(out @event); DocumentStart event2; bool flag2 = parser.TryConsume<DocumentStart>(out event2); object result = null; if (!parser.Accept<DocumentEnd>(out var _) && !parser.Accept<<751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd>(out var _)) { using SerializerState SerializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, SerializerState, valueDeserializer); SerializerState.OnDeserialization(); } if (flag2) { parser.Consume<DocumentEnd>(); } if (flag) { parser.Consume<<751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd>(); } return result; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class DeserializerBuilder : BuilderSkeleton<DeserializerBuilder> { private Lazy<<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory> objectFactory; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> 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((<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver)new <02b646dc-a617-49e0-ad41-cc8199cb7e26>StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy<<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory>(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> { { <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema.Tags.Map, typeof(Dictionary) }, { <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema.Tags.Str, typeof(string) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Bool, typeof(bool) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Float, typeof(double) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(<595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector), (ITypeInspector inner) => new <595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(<2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention)) ? new <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>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 <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeDeserializer> { { typeof(YamlConvertibleNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(<556e34b0-5b06-48b9-b357-3906846f0467>ArrayNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <556e34b0-5b06-48b9-b357-3906846f0467>ArrayNodeDeserializer(enumNamingConvention, BuildTypeInspector()) }, { typeof(DictionaryNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(<8397dec6-ad4e-45f3-b8d3-220c077b8b45>CollectionNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <8397dec6-ad4e-45f3-b8d3-220c077b8b45>CollectionNodeDeserializer(objectFactory.Value, enumNamingConvention, BuildTypeInspector()) }, { typeof(EnumerableNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties, BuildTypeConverters()) }, { typeof(FsharpListNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new FsharpListNodeDeserializer(BuildTypeInspector(), enumNamingConvention) } }; nodeTypeResolverFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeTypeResolver> { { typeof(<6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>MappingNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlSerializableTypeResolver() }, { typeof(<03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver(tagMappings) }, { typeof(<8f7fb5dc-912b-4219-99f2-8d060b974e6c>PreventUnknownTagsNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <8f7fb5dc-912b-4219-99f2-8d060b974e6c>PreventUnknownTagsNodeTypeResolver() }, { typeof(<40fc379e-fd56-4bf4-954d-70c432fa9170>DefaultContainersNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <40fc379e-fd56-4bf4-954d-70c432fa9170>DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } public ITypeInspector BuildTypeInspector() { ITypeInspector ITypeInspector2 = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { ITypeInspector2 = new <8828f0b0-6ddf-442f-b9b3-76b7b013146e>CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), ITypeInspector2); } return typeInspectorFactories.BuildComponentChain(ITypeInspector2); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy<<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory>(() => 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(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeDeserializer)); return this; } public DeserializerBuilder WithNodeDeserializer<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeDeserializer>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> 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, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer> s) { s.Before<DictionaryNodeDeserializer>(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeTypeResolver)); return this; } public DeserializerBuilder WithNodeTypeResolver<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeTypeResolver>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> 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, <49312740-032e-4572-9d35-26e78ef84ddb>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TInterface, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (!DictionaryExtensions.TryAdd(typeMappings, typeFromHandle, typeFromHandle2)) { typeMappings[typeFromHandle] = typeFromHandle2; } return this; } public DeserializerBuilder WithoutTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>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 <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer BuildValueDeserializer() { return new <2455161e-0206-4b0b-b695-d2c6f8479005>AliasValueDeserializer(new <7cdb4fb4-9916-4c7d-9e42-51cb69791690>NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseVisitors; public IObjectGraphVisitor<IEmitter> InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> TypeConverters { get; private set; } public <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor<IEmitter> innerVisitor, IEventEmitter eventEmitter, IEnumerable<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseVisitors, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>() where T : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return preProcessingPhaseVisitors.OfType().Single(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo { public IObjectDescriptor Source { get; } protected <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo : <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Alias { get; } public bool NeedsExpansion { get; set; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo(IObjectDescriptor source, <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class <1e3efad0-1dd4-4910-a072-9bbea5951f51>ObjectEventInfo : <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Anchor { get; set; } public <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Tag { get; set; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] protected <1e3efad0-1dd4-4910-a072-9bbea5951f51>ObjectEventInfo(IObjectDescriptor source) : base(source) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class ScalarEventInfo : <1e3efad0-1dd4-4910-a072-9bbea5951f51>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 <517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo : <1e3efad0-1dd4-4910-a072-9bbea5951f51>ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class <83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo : <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : <1e3efad0-1dd4-4910-a072-9bbea5951f51>ObjectEventInfo { public bool IsImplicit { get; set; } public <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle Style { get; set; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class <380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo : <8789f1a5-bfdc-4b08-9844-6b3fad73aa3b>EventInfo { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IAliasProvider { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName GetAlias(object target); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer { T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(string input); T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(TextReader input); T Deserialize<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(string input); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(TextReader input); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(string input, Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(TextReader input, Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IEventEmitter { void Emit(<8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(<517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(<83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(<380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo eventInfo, IEmitter emitter); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { string Apply(string value); string Reverse(string value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface INodeDeserializer { bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser reader, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface INodeTypeResolver { bool Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IObjectAccessor { void Set(string name, object target, object value); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Read(string name, object target); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IObjectDescriptor { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object Value { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory { object Create(Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out IDictionary dictionary, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments); Type GetValueType(Type type); void ExecuteOnDeserializing(object value); void ExecuteOnDeserialized(object value); void ExecuteOnSerializing(object value); void ExecuteOnSerialized(object value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy { void Traverse<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext> { bool Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context, ObjectSerializer serializer); void VisitScalar(IObjectDescriptor scalar, TContext context, ObjectSerializer serializer); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context, ObjectSerializer serializer); void VisitMappingEnd(IObjectDescriptor mapping, TContext context, ObjectSerializer serializer); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context, ObjectSerializer serializer); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context, ObjectSerializer serializer); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IPropertyDescriptor { string Name { get; } bool AllowNulls { get; } bool CanWrite { get; } Type Type { get; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } bool Required { get; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T GetCustomAttribute() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value); } internal interface <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TBaseRegistrationType> { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <2b22572e-c285-4969-a597-d61d5bde806c>ISerializer { string Serialize([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph); string Serialize([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type); void Serialize(TextWriter writer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph); void Serialize(TextWriter writer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type); void Serialize(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph); void Serialize(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface ITypeInspector { IEnumerable<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container); IPropertyDescriptor GetProperty(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container, string name, [<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching); string GetEnumName(Type enumType, string name); string GetEnumValue(object enumValue); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver { Type Resolve(Type staticType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object actualValue); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object DeserializeValue(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, SerializerState state, <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 2 })] event Action ValueAvailable; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] internal interface IValueSerializer { void SerializeValue([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] IEmitter emitter, object value, Type type); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible { void Read(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] internal delegate object ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object value, Type type = null); [Obsolete("Please use IYamlConvertible instead")] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable { void ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser); void WriteYaml(IEmitter emitter); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { bool Accepts(Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer); void WriteYaml(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer); } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TArgument, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponent> : IEnumerable>, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private class RegistrationLocationSelector : <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 0 })] private readonly LazyComponentRegistration newRegistration; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public RegistrationLocationSelector(<99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 0 })] LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); registrations.entries[index] = newRegistration; } void <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax.After() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists(); registrations.entries.Insert(num + 1, newRegistration); } void <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax.Before() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists(); registrations.entries.Insert(index, newRegistration); } void <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void <895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 0 })] private readonly TrackingLazyComponentRegistration newRegistration; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public TrackingRegistrationLocationSelector(<99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 0 })] TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); Func innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 0, 0 })] private readonly List entries = new List(); public int Count => entries.Count; public IEnumerable> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList Clone() { <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList2 = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList(); foreach (LazyComponentRegistration entry in entries) { <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList2.entries.Add(entry); } return <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList2; } 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 <895aa723-681e-4b7a-8376-d2512fc57d22>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([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if (registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private int EnsureRegistrationExists() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponent>(this <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TArgument, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponent>(this <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { return registrations.InReverseOrder.Aggregate(innerComponent, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (TComponent inner, Func factory) => factory(argumentBuilder(inner))); } public static List BuildComponentList<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponent>(this <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, TComponent> registrations) { return registrations.Select([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Func<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, TComponent> factory) => factory(default(<49312740-032e-4572-9d35-26e78ef84ddb>Nothing))).ToList(); } public static List BuildComponentList<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TArgument, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TComponent>(this <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList registrations, TArgument argument) { return registrations.Select([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Func factory) => factory(argument)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct <49312740-032e-4572-9d35-26e78ef84ddb>Nothing { } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor : IObjectDescriptor { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Value { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } internal delegate <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy <2e964d83-767e-437f-bbad-a13316da711f>ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, int maximumRecursion); [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <75db3571-f9dc-4003-b7ea-2a9c91be7d67>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; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return baseDescriptor.ConverterType; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { baseDescriptor.Write(target, value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public T GetCustomAttribute() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class Serializer : <2b22572e-c285-4969-a597-d61d5bde806c>ISerializer { private readonly IValueSerializer valueSerializer; private readonly <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings emitterSettings; public Serializer() : this(new <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder().BuildValueSerializer(), <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public string Serialize([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public string Serialize([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph, type); return stringWriter.ToString(); } public void Serialize(TextWriter writer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph) { Serialize(new <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(writer, emitterSettings), graph); } public void Serialize(TextWriter writer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type) { Serialize(new <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private void EmitDocument([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] IEmitter emitter, object graph, Type type) { emitter.Emit(new <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart()); emitter.Emit(new DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new DocumentEnd(isImplicit: true)); emitter.Emit(new <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd()); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] internal sealed class <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder : BuilderSkeleton<<0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder> { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class ValueSerializer : IValueSerializer { private readonly <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(<6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories, <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public void SerializeValue([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] IEmitter emitter, object value, Type type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor graph = new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(value, type2, staticType); List<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new <1310b8df-6e8e-4738-ae0a-e8c79e1c46de>EmittingObjectGraphVisitor(eventEmitter), [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IObjectGraphVisitor<IEmitter> inner) => new <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); foreach (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(<49312740-032e-4572-9d35-26e78ef84ddb>Nothing), NestedObjectSerializer); } traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, v, t); } } } private <2e964d83-767e-437f-bbad-a13316da711f>ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories; private readonly DictionaryTagName> tagMappings = new DictionaryTagName>(); private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; private int maximumRecursion = 50; private <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings emitterSettings = <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private ScalarStyle defaultScalarStyle; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder Self => this; public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder() : base((<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(<595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector), (ITypeInspector inner) => new <595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(<2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention)) ? new <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>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 <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> { { typeof(<2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => new <2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> { { typeof(CustomSerializationObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<<2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner>()) }, { typeof(DefaultValuesObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(<078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new <078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, int maximumRecursion) => new <8d91aaee-3f0b-48a8-abb2-e4653d75cbaa>FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithDefaultScalarStyle(ScalarStyle style) { defaultScalarStyle = style; return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>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 <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter>> 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 <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> 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 <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>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 <0eb70ba6-492c-46c1-997c-d367f2b29466>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 <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector> loc) { loc.OnBottom(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(<2b384c3f-4c6d-4b22-ab94-6e973e754d51>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 <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName().WithUtf16SurrogatePairs(); return WithTypeConverter(new GuidConverter(jsonCompatible: true), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> w) { w.InsteadOf<GuidConverter>(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new <812a1307-50d5-4cad-af94-0a766241641b>JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> w) { w.OnTop(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(FuncIYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> w) { w.OnTop(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> _) => objectGraphVisitor)); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(FuncIYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> wrapped, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> _) => objectGraphVisitorFactory(wrapped))); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactoryIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> wrapped, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithObjectGraphTraversalStrategyFactory(<2e964d83-767e-437f-bbad-a13316da711f>ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(Func<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w) { w.OnTop(); }); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(Func<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public <0eb70ba6-492c-46c1-997c-d367f2b29466>SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public <2b22572e-c285-4969-a597-d61d5bde806c>ISerializer Build() { if (FsharpHelper.Instance == null) { FsharpHelper.Instance = new DefaultFsharpHelper(); } return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new <40dc4525-a553-4415-93ab-24b96dc27d3e>WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } public ITypeInspector BuildTypeInspector() { ITypeInspector ITypeInspector2 = new <630b77bf-9faf-4f86-89b4-56134477718b>ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { ITypeInspector2 = new <8828f0b0-6ddf-442f-b9b3-76b7b013146e>CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), ITypeInspector2); } return typeInspectorFactories.BuildComponentChain(ITypeInspector2); } } internal class Settings { public bool AllowPrivateConstructors { get; set; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class StaticBuilderSkeleton<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TBuilder> where TBuilder : StaticBuilderSkeleton { internal <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention = <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention.Instance; internal <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention = <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention.Instance; internal <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; internal readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverterFactories; internal readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<ITypeInspector, ITypeInspector> typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; internal YamlFormatter yamlFormatter = YamlFormatter.Default; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) { typeConverterFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> { { typeof(GuidConverter), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<ITypeInspector, ITypeInspector>(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(<22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithEnumNamingConvention(<22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention) { this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); return Self; } public TBuilder WithTypeResolver(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, Type type); public TBuilder WithTypeConverter(<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> w) { w.OnTop(); }); } public TBuilder WithTypeConverter(<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter typeConverter, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>> where) { if (typeConverter == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => typeConverter)); return Self; } public TBuilder WithTypeConverter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TYamlTypeConverter>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>> where) where TYamlTypeConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { if (typeConverterFactory == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter wrapped, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => typeConverterFactory(wrapped))); return Self; } public TBuilder WithoutTypeConverter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TYamlTypeConverter>() where TYamlTypeConverter : <87461092-0374-4a6c-919c-f5a28d630352>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector> w) { w.OnTop(); }); } public TBuilder WithTypeInspector<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(Func<ITypeInspector, TTypeInspector> typeInspectorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<ITypeInspector, ITypeInspector, TTypeInspector> typeInspectorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<ITypeInspector>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TTypeInspector>() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } public TBuilder WithYamlFormatter(YamlFormatter formatter) { yamlFormatter = formatter ?? throw new ArgumentNullException("formatter"); return Self; } protected IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class StaticContext { public virtual bool IsKnownType(Type type) { throw new NotImplementedException(); } public virtual <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver GetTypeResolver() { throw new NotImplementedException(); } public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] internal sealed class StaticDeserializerBuilder : StaticBuilderSkeleton { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeDeserializer> nodeDeserializerFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeTypeResolver> nodeTypeResolverFactories; private readonly Dictionary<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> 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<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> { { <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema.Tags.Map, typeof(Dictionary) }, { <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema.Tags.Str, typeof(string) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Bool, typeof(bool) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Float, typeof(double) }, { <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(<595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector), (ITypeInspector inner) => new <595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(<2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention)) ? new <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeDeserializer> { { typeof(YamlConvertibleNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter, BuildTypeInspector(), yamlFormatter, enumNamingConvention) }, { typeof(StaticArrayNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter, enumNamingConvention, enforceNullability, caseInsensitivePropertyMatching, enforceRequiredProperties: false, BuildTypeConverters()) } }; nodeTypeResolverFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing, INodeTypeResolver> { { typeof(<6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>MappingNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new YamlSerializableTypeResolver() }, { typeof(<03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver(tagMappings) }, { typeof(<8f7fb5dc-912b-4219-99f2-8d060b974e6c>PreventUnknownTagsNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <8f7fb5dc-912b-4219-99f2-8d060b974e6c>PreventUnknownTagsNodeTypeResolver() }, { typeof(<40fc379e-fd56-4bf4-954d-70c432fa9170>DefaultContainersNodeTypeResolver), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => new <40fc379e-fd56-4bf4-954d-70c432fa9170>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(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer> w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer>> where) { if (nodeDeserializer == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeDeserializer)); return this; } public StaticDeserializerBuilder WithNodeDeserializer<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeDeserializer>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<INodeDeserializer, TNodeDeserializer> nodeDeserializerFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeDeserializer>> 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, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeDeserializerFactory(wrapped))); return this; } public StaticDeserializerBuilder WithCaseInsensitivePropertyMatching() { caseInsensitivePropertyMatching = true; return this; } public StaticDeserializerBuilder WithEnforceNullability() { enforceNullability = true; return this; } public StaticDeserializerBuilder WithoutNodeDeserializer<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeDeserializer>() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeDeserializer> s) { s.Before<DictionaryNodeDeserializer>(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeTypeResolver> w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<INodeTypeResolver>> where) { if (nodeTypeResolver == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver.GetType(), (<49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeTypeResolver)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeTypeResolver>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<INodeTypeResolver, TNodeTypeResolver> nodeTypeResolverFactory, Action<ITrackingRegistrationLocationSelectionSyntax<INodeTypeResolver>> 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, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing _) => nodeTypeResolverFactory(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TNodeTypeResolver>() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override StaticDeserializerBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out var value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public StaticDeserializerBuilder WithTypeMapping<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TInterface, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TConcrete>() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } typeMappings[typeFromHandle] = typeFromHandle2; return this; } public StaticDeserializerBuilder WithoutTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>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 <1be51ab9-9c6c-4842-9e33-2847a9aac19d>IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer BuildValueDeserializer() { return new <2455161e-0206-4b0b-b695-d2c6f8479005>AliasValueDeserializer(new <7cdb4fb4-9916-4c7d-9e42-51cb69791690>NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter, enumNamingConvention, BuildTypeInspector())); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class ValueSerializer : IValueSerializer { private readonly <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(<6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories, <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public void SerializeValue([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] IEmitter emitter, object value, Type type) { Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor graph = new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(value, type2, staticType); List<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(<49312740-032e-4572-9d35-26e78ef84ddb>Nothing), NestedObjectSerializer); } IObjectGraphVisitor<IEmitter> visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(new <1310b8df-6e8e-4738-ae0a-e8c79e1c46de>EmittingObjectGraphVisitor(eventEmitter), [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IObjectGraphVisitor<IEmitter> inner) => new <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter, NestedObjectSerializer); [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] void NestedObjectSerializer(object v, Type t) { SerializeValue(emitter, v, t); } } } private readonly StaticContext context; private readonly StaticObjectFactory factory; private <2e964d83-767e-437f-bbad-a13316da711f>ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> preProcessingPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories; private readonly <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories; private readonly DictionaryTagName> tagMappings = new DictionaryTagName>(); private int maximumRecursion = 50; private <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings emitterSettings = <46a02486-5476-43e4-a617-652c44dc706f>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((<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver)new DynamicTypeResolver()) { this.context = context; factory = context.GetFactory(); typeInspectorFactories.Add(typeof(<595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector), (ITypeInspector inner) => new <595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(<2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention)) ? new <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); preProcessingPhaseObjectGraphVisitorFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationListIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> { { typeof(<2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => new <2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> { { typeof(CustomSerializationObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<<2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner>()) }, { typeof(DefaultValuesObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory) }, { typeof(<078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => new <078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new <99af7a0c-fb9a-46fc-8c16-eb8a01823dce>LazyComponentRegistrationList<IEventEmitter, IEventEmitter> { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings, defaultScalarStyle, yamlFormatter, enumNamingConvention, BuildTypeInspector()) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, int maximumRecursion) => new <8d91aaee-3f0b-48a8-abb2-e4653d75cbaa>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter>> where) where TEventEmitter : IEventEmitter { return WithEventEmitter((IEventEmitter e, ITypeInspector _) => eventEmitterFactory(e), where); } public StaticSerializerBuilder WithEventEmitter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(Func<IEventEmitter, ITypeInspector, TEventEmitter> eventEmitterFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> 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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TEventEmitter>() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override StaticSerializerBuilder WithTagMapping(<763b3306-75ef-49cf-b5e4-c84545a2932c>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, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> 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(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<ITypeInspector> loc) { loc.OnBottom(); }); } public StaticSerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(<2b384c3f-4c6d-4b22-ab94-6e973e754d51>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 GuidConverter(jsonCompatible: true), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> w) { w.InsteadOf<GuidConverter>(); }).WithTypeConverter(new DateTime8601Converter(ScalarStyle.DoubleQuoted)).WithEventEmitter((IEventEmitter inner) => new <812a1307-50d5-4cad-af94-0a766241641b>JsonEventEmitter(inner, yamlFormatter, enumNamingConvention, BuildTypeInspector()), delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IEventEmitter> loc) { loc.InsteadOf<TypeAssigningEventEmitter>(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(FuncIYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitor == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> _) => objectGraphVisitor)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(FuncIYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory(typeConverters))); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<4bf566c9-f500-475e-ba13-1b5cc50e66d6>WrapperFactory<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> wrapped, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> _) => objectGraphVisitorFactory(wrapped))); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactoryIYamlTypeConverter>, IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> wrapped, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(<2e964d83-767e-437f-bbad-a13316da711f>ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(Func<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(Func<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory, Action<<895aa723-681e-4b7a-8376-d2512fc57d22>IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>(<23dfcca1-b793-4bf4-9550-f7142c836d7c>WrapperFactory<<2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory, Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where) where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor<IEmitter> wrapped, <2397dd0e-9afd-45d5-bc4d-f68ff246d6a9>EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TObjectGraphVisitor>() where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { 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 <2b22572e-c285-4969-a597-d61d5bde806c>ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new <40dc4525-a553-4415-93ab-24b96dc27d3e>WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } public ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <67d6f206-67a7-4b95-9d48-aa03089c0734>StreamFragment : <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible { private readonly List<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> events = new List<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); public IList<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> Events => events; void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Read(<335b54f3-fbf8-46c4-bfc9-8467281b299b>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."); } <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent @event in events) { emitter.Emit(@event); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <9f328cd6-afc6-45ab-bfdb-be8cb31c544e>TagMappings { private readonly Dictionary mappings; public <9f328cd6-afc6-45ab-bfdb-be8cb31c544e>TagMappings() { mappings = new Dictionary(); } public <9f328cd6-afc6-45ab-bfdb-be8cb31c544e>TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] internal Type GetMapping(string tag) { if (!mappings.TryGetValue(tag, out var value)) { return null; } return value; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private readonly struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return <08becf84-efa3-4abf-869e-3e3d06f458f0>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 = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.BaseType(type); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); [return: MaybeNull] public T GetAttribute<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out var value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out var value)) { value = new List(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides Clone() { <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides2 = new <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides(); foreach (KeyValuePair> @override in overrides) { foreach (AttributeMapping item in @override.Value) { <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides2.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides2; } public void Add<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TClass>(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = ExpressionExtensions.AsProperty(propertyAccessor); Add(typeof(TClass), propertyInfo.Name, attribute); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class YamlAttributeOverridesInspector : ReflectionTypeInspector { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly <7cf95dad-737a-45ac-af36-1acd6741b346>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; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return baseDescriptor.TypeOverride; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set { baseDescriptor.TypeOverride = value; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return GetCustomAttribute()?.ConverterType ?? baseDescriptor.ConverterType; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { baseDescriptor.Write(target, value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public T GetCustomAttribute() where T : Attribute { T attribute = overrides.GetAttribute(classType, Name); return attribute ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, <7cf95dad-737a-45ac-af36-1acd6741b346>YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { IEnumerable<IPropertyDescriptor> enumerable = innerTypeDescriptor.GetProperties(type, container); if (overrides != null) { enumerable = enumerable.Select((Func<IPropertyDescriptor, IPropertyDescriptor>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type))); } return enumerable; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class YamlAttributesTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute<<0e9e0092-bb69-4060-8d00-87db15d733ac>YamlIgnoreAttribute>() == null select p).Select((Func<IPropertyDescriptor, IPropertyDescriptor>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IPropertyDescriptor p) => { <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2 = new <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor(p); <9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute customAttribute = p.GetCustomAttribute<<9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute>(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2.TypeOverride = customAttribute.SerializeAs; } <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2.Order = customAttribute.Order; <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2.Name = customAttribute.Alias; } } return <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor2; })) orderby p.Order select p; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class YamlConverterAttribute : Attribute { public Type ConverterType { get; } public YamlConverterAttribute(Type converterType) { ConverterType = converterType; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class YamlFormatter { public static YamlFormatter Default { get; } = new YamlFormatter(); public NumberFormatInfo NumberFormat { get; set; } = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public virtual FuncITypeInspector, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention, string> FormatEnum { get; set; } = delegate(object value, ITypeInspector typeInspector, <22599784-6051-4a47-9318-0a6f38d04add>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 <0e9e0092-bb69-4060-8d00-87db15d733ac>YamlIgnoreAttribute : Attribute { } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class <9320923c-d4aa-4aee-b37d-a26b054c9a8e>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 <9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <9320923c-d4aa-4aee-b37d-a26b054c9a8e>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() { } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public YamlSerializableAttribute(Type serializableType) { } } [AttributeUsage(AttributeTargets.Class)] internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class <2455161e-0206-4b0b-b695-d2c6f8479005>AliasValueDeserializer : <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] private sealed class AliasState : Dictionary<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, ValuePromise>, <0a3fb224-36c2-4897-9463-6ce0bbece3ad>IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { AnchorAlias alias = value.Alias; throw new AnchorNotFoundException(alias.Start, alias.End, $"Anchor '{alias.Value}' not found"); } } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private sealed class ValuePromise : IValuePromise { private object value; public readonly 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; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public ValuePromise(AnchorAlias alias) { Alias = alias; } public ValuePromise(object value) { HasValue = true; this.value = value; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer innerDeserializer; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <2455161e-0206-4b0b-b695-d2c6f8479005>AliasValueDeserializer(<7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object DeserializeValue(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, SerializerState state, <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume<AnchorAlias>(out var @event)) { AliasState aliasState = state.Get(); if (!aliasState.TryGetValue(@event.Value, out var value)) { throw new AnchorNotFoundException(@event.Start, @event.End, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName = <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty; if (parser.Accept<<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent>(out var event2) && !event2.Anchor.IsEmpty) { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName = event2.Anchor; AliasState aliasState2 = state.Get(); if (!aliasState2.ContainsKey(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName)) { aliasState2[<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName] = new ValuePromise(new AnchorAlias(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.IsEmpty) { AliasState aliasState3 = state.Get(); if (!aliasState3.TryGetValue(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, out var value2)) { aliasState3.Add(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState3[<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName] = new ValuePromise(obj); } } return obj; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <7cdb4fb4-9916-4c7d-9e42-51cb69791690>NodeValueDeserializer : <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer { private readonly IList<INodeDeserializer> deserializers; private readonly IList<INodeTypeResolver> typeResolvers; private readonly ITypeConverter typeConverter; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public <7cdb4fb4-9916-4c7d-9e42-51cb69791690>NodeValueDeserializer(IList<INodeDeserializer> deserializers, IList<INodeTypeResolver> typeResolvers, ITypeConverter typeConverter, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.enumNamingConvention = enumNamingConvention ?? throw new ArgumentNullException("enumNamingConvention"); this.typeInspector = typeInspector; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object DeserializeValue(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, SerializerState state, <7b4d2326-64df-4cb2-ab47-91a04720bb94>IValueDeserializer nestedObjectDeserializer) { parser.Accept<<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent>(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); ObjectDeserializer rootDeserializer = [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] (Type x) => DeserializeValue(parser, x, state, nestedObjectDeserializer); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] (<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out var value, rootDeserializer)) { return typeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } } catch (<9f1d586b-d77e-4258-bb38-eb176815536f>YamlException) { throw; } catch (Exception innerException) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(@event?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, @event?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "Exception during deserialization", innerException); } throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(@event?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, @event?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, Type currentType) { foreach (INodeTypeResolver typeResolver in typeResolvers) { if (typeResolver.Resolve(nodeEvent, ref currentType)) { break; } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface <0a3fb224-36c2-4897-9463-6ce0bbece3ad>IPostDeserializationCallback { void OnDeserialization(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface ITypeConverter { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type expectedType, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector); } internal class NullTypeConverter : ITypeConverter { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type expectedType, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return value; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <438c8dcf-ee9b-47ba-b497-88f938ceda08>ObjectAnchorCollection { private readonly Dictionary objectsByAnchor = new Dictionary(); private readonly Dictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out var value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(false)][<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out string anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type expectedType, ITypeInspector typeInspector) { return ChangeType(value, expectedType, <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention.Instance, typeInspector); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type expectedType, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return TypeConverter.ChangeType(value, expectedType, enumNamingConvention, typeInspector); } } internal sealed class SerializerState : IDisposable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly Dictionary items = new Dictionary(); [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out var value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (<0a3fb224-36c2-4897-9463-6ce0bbece3ad>IPostDeserializationCallback item in items.Values.OfType<<0a3fb224-36c2-4897-9463-6ce0bbece3ad>IPostDeserializationCallback>()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType()) { item.Dispose(); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { str = char.ToLower(str[0], CultureInfo.InvariantCulture) + str.Substring(1); str = Regex.Replace(ToCamelCase(str), "(?[A-Z])", [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class TypeConverter { public static T ChangeType<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return (T)ChangeType(value, typeof(T), enumNamingConvention, typeInspector); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type destinationType, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture, enumNamingConvention, typeInspector); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type destinationType, IFormatProvider provider, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider), enumNamingConvention, typeInspector); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object ChangeType([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type destinationType, CultureInfo culture, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { if (value == null || <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsDbNull(value)) { if (!<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsValueType(destinationType)) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsGenericType(destinationType)) { 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 (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsEnum(destinationType)) { 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 <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetPublicStaticMethods(type2)) { 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 = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetPublicStaticMethod(destinationType, "Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetPublicStaticMethod(destinationType, "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); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] public static void RegisterTypeConverter<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TConvertible, TConverter>() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class TypeConverterCache { private readonly <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[] typeConverters; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 0, 2 })] private readonly ConcurrentDictionaryIYamlTypeConverter TypeConverter)> cache = new ConcurrentDictionaryIYamlTypeConverter)>(); public TypeConverterCache([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) : this(typeConverters?.ToArray() ?? Array.Empty<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>()) { } public TypeConverterCache(<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[] typeConverters) { this.typeConverters = typeConverters; } public bool TryGetConverterForType(Type type, [NotNullWhen(true)][<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter typeConverter) { (bool, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter) orAdd = DictionaryExtensions.GetOrAdd(cache, type, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Type t, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[] tc) => LookupTypeConverter(t, tc), typeConverters); typeConverter = orAdd.Item2; return orAdd.Item1; } public <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter GetConverterByType(Type converter) { <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[] array = typeConverters; foreach (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter in array) { if (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter.GetType() == converter) { return <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter; } } throw new ArgumentException("IYamlTypeConverter of type " + converter.FullName + " not found", "converter"); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 2 })] private static (bool HasMatch, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter TypeConverter) LookupTypeConverter(Type type, <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[] typeConverters) { foreach (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter in typeConverters) { if (<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter.Accepts(type)) { return (HasMatch: true, TypeConverter: <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter); } } return (HasMatch: false, TypeConverter: null); } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public Type Resolve(Type staticType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal class <02b646dc-a617-49e0-ad41-cc8199cb7e26>StaticTypeResolver : <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public virtual Type Resolve(Type staticType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object actualValue) { if (actualValue != null) { if (actualValue.GetType().IsEnum) { return staticType; } switch (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetTypeCode(actualValue.GetType())) { 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 { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <595306cb-df69-4188-9612-fb507ea4ad4a>CachedTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionaryIPropertyDescriptor>> cache = new ConcurrentDictionaryIPropertyDescriptor>>(); private readonly ConcurrentDictionary> enumNameCache = new ConcurrentDictionary>(); private readonly ConcurrentDictionary enumValueCache = new ConcurrentDictionary(); public <595306cb-df69-4188-9612-fb507ea4ad4a>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, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (string n, (Type enumType, ITypeInspector innerTypeDescriptor) context) => { var (enumType2, ITypeInspector) = context; return ITypeInspector.GetEnumName(enumType2, n); }, (enumType, innerTypeDescriptor)); } public override string GetEnumValue(object enumValue) { return DictionaryExtensions.GetOrAdd(enumValueCache, enumValue, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (object _, (object enumValue, ITypeInspector innerTypeDescriptor) context) => { var (enumValue2, ITypeInspector) = context; return ITypeInspector.GetEnumValue(enumValue2); }, (enumValue, innerTypeDescriptor)); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return DictionaryExtensions.GetOrAdd(cache, type, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (Type t, (object container, ITypeInspector innerTypeDescriptor) context) => { var (container2, ITypeInspector) = context; return ITypeInspector.GetProperties(t, container2).ToList(); }, (container, innerTypeDescriptor)); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <8828f0b0-6ddf-442f-b9b3-76b7b013146e>CompositeTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>TypeInspectorSkeleton { private readonly IEnumerable<ITypeInspector> typeInspectors; public <8828f0b0-6ddf-442f-b9b3-76b7b013146e>CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable<ITypeInspector>)typeInspectors) { } public <8828f0b0-6ddf-442f-b9b3-76b7b013146e>CompositeTypeInspector(IEnumerable<ITypeInspector> 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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return typeInspectors.SelectMany([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (ITypeInspector i) => i.GetProperties(type, container)); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention; public <2bf2bc77-fd64-4c93-8b73-64f0f48536e9>NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, <22599784-6051-4a47-9318-0a6f38d04add>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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return innerTypeDescriptor.GetProperties(type, container).Select([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IPropertyDescriptor p) => { <9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute customAttribute = p.GetCustomAttribute<<9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute>(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new <75db3571-f9dc-4003-b7ea-2a9c91be7d67>PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class ReadableAndWritablePropertiesTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class ReadableFieldsTypeInspector : ReflectionTypeInspector { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] protected class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; public string Name => fieldInfo.Name; public bool Required => fieldInfo.IsRequired(); public Type Type => fieldInfo.FieldType; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } public bool AllowNulls => fieldInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, <58625951-9f8e-4fa7-b548-7b26a0bec31b>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, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { fieldInfo.SetValue(target, value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public T GetCustomAttribute() where T : Attribute { object[] customAttributes = fieldInfo.GetCustomAttributes(typeof(T), inherit: true); return (T)customAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; public ReadableFieldsTypeInspector(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetPublicFields(type).Select((FuncIPropertyDescriptor>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <630b77bf-9faf-4f86-89b4-56134477718b>ReadablePropertiesTypeInspector : ReflectionTypeInspector { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } public bool AllowNulls => propertyInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, <58625951-9f8e-4fa7-b548-7b26a0bec31b>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, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public T GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetAllCustomAttributes(propertyInfo); return (T)allCustomAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = PropertyInfoExtensions.ReadValue(propertyInfo, target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public <630b77bf-9faf-4f86-89b4-56134477718b>ReadablePropertiesTypeInspector(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public <630b77bf-9faf-4f86-89b4-56134477718b>ReadablePropertiesTypeInspector(<58625951-9f8e-4fa7-b548-7b26a0bec31b>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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetProperties(type, includeNonPublicProperties).Where(IsValidProperty).Select((FuncIPropertyDescriptor>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class ReflectionTypeInspector : <034c234e-680a-42cd-aa29-9e54adec7ee6>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(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class <034c234e-680a-42cd-aa29-9e54adec7ee6>TypeInspectorSkeleton : ITypeInspector { public abstract string GetEnumName(Type enumType, string name); public abstract string GetEnumValue(object enumValue); public abstract IEnumerable<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container); public IPropertyDescriptor GetProperty(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container, string name, [<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(true)] bool ignoreUnmatched, bool caseInsensitivePropertyMatching) { IEnumerable<IPropertyDescriptor> 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<IPropertyDescriptor> 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([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class WritablePropertiesTypeInspector : ReflectionTypeInspector { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] protected class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; public string Name => propertyInfo.Name; public bool Required => propertyInfo.IsRequired(); public Type Type => propertyInfo.PropertyType; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type TypeOverride { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type ConverterType { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } public bool AllowNulls => propertyInfo.AcceptsNull(); public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, <58625951-9f8e-4fa7-b548-7b26a0bec31b>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, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { propertyInfo.SetValue(target, value, null); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public T GetCustomAttribute() where T : Attribute { Attribute[] allCustomAttributes = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetAllCustomAttributes(propertyInfo); return (T)allCustomAttributes.FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = PropertyInfoExtensions.ReadValue(propertyInfo, target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public WritablePropertiesTypeInspector(<58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public WritablePropertiesTypeInspector(<58625951-9f8e-4fa7-b548-7b26a0bec31b>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<IPropertyDescriptor> GetProperties(Type type, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object container) { return <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetProperties(type, includeNonPublicProperties).Where(IsValidProperty).Select((FuncIPropertyDescriptor>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))) .ToArray(); } } } namespace YamlDotNet.Serialization.Schemas { internal sealed class <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema { public static class Tags { public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Map = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:map"); public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Seq = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:seq"); public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Str = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:str"); } } internal sealed class <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema { public static class Tags { public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Null = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:null"); public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Bool = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:bool"); public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Int = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:int"); public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Float = new <763b3306-75ef-49cf-b5e4-c84545a2932c>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 <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Timestamp = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName("tag:yaml.org,2002:timestamp"); } } } namespace YamlDotNet.Serialization.ObjectGraphVisitors { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private class AnchorAssignment { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Anchor; } private readonly Dictionary assignments = new Dictionary(); private uint nextId; public <2b384c3f-4c6d-4b22-ab94-6e973e754d51>AnchorAssigner(IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value, ObjectSerializer serializer) { if (value.Value != null && assignments.TryGetValue(value.Value, out var value2)) { if (value2.Anchor.IsEmpty) { value2.Anchor = new <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>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()); } } <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out var value)) { return value.Anchor; } return <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEventEmitter eventEmitter; private readonly IAliasProvider aliasProvider; private readonly HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName> emittedAliases = new HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName>(); public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) : base(nextVisitor) { this.eventEmitter = eventEmitter; this.aliasProvider = aliasProvider; } public override bool Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (value.Value != null) { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo = new <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo(value, alias); eventEmitter.Emit(<8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo, context); return <8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo.NeedsExpansion; } } return base.Enter(propertyDescriptor, value, context, serializer); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new <517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>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); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { private readonly IObjectGraphVisitor<IEmitter> nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.Enter(propertyDescriptor, value, context, serializer); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return nextVisitor.EnterMapping(key, value, context, serializer); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitScalar(scalar, context, serializer); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context, serializer); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitMappingEnd(mapping, context, serializer); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceStart(sequence, elementType, context, serializer); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { nextVisitor.VisitSequenceEnd(sequence, context, serializer); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public <078d324d-3cdf-4219-8017-0d877039ce06>CommentsObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { <9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute customAttribute = key.GetCustomAttribute<<9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute>(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new <52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context, serializer); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly TypeConverterCache typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { this.typeConverters = new TypeConverterCache(typeConverters); this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { if (propertyDescriptor?.ConverterType != null) { <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter converterByType = typeConverters.GetConverterByType(propertyDescriptor.ConverterType); converterByType.WriteYaml(context, value.Value, value.Type, serializer); return false; } if (typeConverters.TryGetConverterForType(value.Type, out var typeConverter)) { typeConverter.WriteYaml(context, value.Value, value.Type, serializer); return false; } if (value.Value is <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible) { <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value.Value is <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable) { <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable.WriteYaml(context); return false; } return base.Enter(propertyDescriptor, value, context, serializer); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <6a015da4-02d4-4339-8f78-cc5604ad0035>DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public <6a015da4-02d4-4339-8f78-cc5604ad0035>DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor<IEmitter> nextVisitor) : base(nextVisitor) { } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private static object GetDefault(Type type) { if (!<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsValueType(type)) { 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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory factory; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor<IEmitter> nextVisitor, <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory factory) : base(nextVisitor) { this.handling = handling; this.factory = factory; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private object GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { DefaultValuesHandling defaultValuesHandling = handling; <9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute customAttribute = key.GetCustomAttribute<<9320923c-d4aa-4aee-b37d-a26b054c9a8e>YamlMemberAttribute>(); 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); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <1310b8df-6e8e-4738-ae0a-e8c79e1c46de>EmittingObjectGraphVisitor : IObjectGraphVisitor<IEmitter> { private readonly IEventEmitter eventEmitter; public <1310b8df-6e8e-4738-ae0a-e8c79e1c46de>EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor<IEmitter>.Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor<IEmitter>.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } bool IObjectGraphVisitor<IEmitter>.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context, ObjectSerializer serializer) { return true; } void IObjectGraphVisitor<IEmitter>.VisitScalar(IObjectDescriptor scalar, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor<IEmitter>.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new <517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor<IEmitter>.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new <83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor<IEmitter>.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor<IEmitter>.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context, ObjectSerializer serializer) { eventEmitter.Emit(new <380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo(sequence), context); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing> { protected readonly IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters; private readonly TypeConverterCache typeConverterCache; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> typeConverters) { typeConverterCache = new TypeConverterCache((<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter[])(this.typeConverters = typeConverters?.ToArray() ?? Array.Empty<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter>())); } bool IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.Enter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { if (typeConverterCache.TryGetConverterForType(value.Type, out var _)) { return false; } if (value.Value is <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible) { return false; } if (value.Value is <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable) { return false; } return Enter(value, serializer); } bool IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } bool IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { return EnterMapping(key, value, serializer); } void IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.VisitMappingEnd(IObjectDescriptor mapping, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { VisitMappingEnd(mapping, serializer); } void IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { VisitMappingStart(mapping, keyType, valueType, serializer); } void IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.VisitScalar(IObjectDescriptor scalar, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { VisitScalar(scalar, serializer); } void IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.VisitSequenceEnd(IObjectDescriptor sequence, <49312740-032e-4572-9d35-26e78ef84ddb>Nothing context, ObjectSerializer serializer) { VisitSequenceEnd(sequence, serializer); } void IObjectGraphVisitor<<49312740-032e-4572-9d35-26e78ef84ddb>Nothing>.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, <49312740-032e-4572-9d35-26e78ef84ddb>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 { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <8d91aaee-3f0b-48a8-abb2-e4653d75cbaa>FullObjectGraphTraversalStrategy : <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] protected readonly struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention; private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; public <8d91aaee-3f0b-48a8-abb2-e4653d75cbaa>FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, int maxRecursion, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention, <27829ecc-c9ac-43bc-8d81-40fa384ecb07>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 <6acc7745-fe96-445c-8d39-bc3dd198886b>IObjectGraphTraversalStrategy.Traverse<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context, ObjectSerializer serializer) { Traverse(null, "", graph, visitor, context, new Stack(maxRecursion), serializer); } protected virtual void Traverse<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = item.Name?.ToString() ?? string.Empty; num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new <33aa3462-611c-4e66-8e55-df86e8908de6>MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(propertyDescriptor, value, context, serializer)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetTypeCode(value.Type); 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 (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsDbNull(value)) { visitor.VisitScalar(new <47a54840-87b2-45a1-9922-dc49259f24c6>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 <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path, serializer); } else if (type != null && obj != null) { Traverse(propertyDescriptor, "Value", new <47a54840-87b2-45a1-9922-dc49259f24c6>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(propertyDescriptor, value, visitor, typeof(object), typeof(object), context, path, serializer); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(propertyDescriptor, new <47a54840-87b2-45a1-9922-dc49259f24c6>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IPropertyDescriptor propertyDescriptor, IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path, ObjectSerializer serializer) { visitor.VisitMappingStart(dictionary, keyType, valueType, context, serializer); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); <47a54840-87b2-45a1-9922-dc49259f24c6>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>(IPropertyDescriptor propertyDescriptor, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context, serializer); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(propertyDescriptor, num, GetObjectDescriptor(item, valueType), visitor, context, path, serializer); num++; } visitor.VisitSequenceEnd(value, context, serializer); } protected virtual void TraverseProperties<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (context.GetType() != typeof(<49312740-032e-4572-9d35-26e78ef84ddb>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 <47a54840-87b2-45a1-9922-dc49259f24c6>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(<49312740-032e-4572-9d35-26e78ef84ddb>Nothing)) { objectFactory.ExecuteOnSerialized(value.Value); } } private <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor GetObjectDescriptor([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type staticType) { return new <47a54840-87b2-45a1-9922-dc49259f24c6>ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class RoundtripObjectGraphTraversalStrategy : <8d91aaee-3f0b-48a8-abb2-e4653d75cbaa>FullObjectGraphTraversalStrategy { private readonly TypeConverterCache converters; private readonly Settings settings; public RoundtripObjectGraphTraversalStrategy(IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> converters, ITypeInspector typeDescriptor, <58625951-9f8e-4fa7-b548-7b26a0bec31b>ITypeResolver typeResolver, int maxRecursion, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention namingConvention, Settings settings, <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory factory) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention, factory) { this.converters = new TypeConverterCache(converters); this.settings = settings; } protected override void TraverseProperties<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TContext>(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path, ObjectSerializer serializer) { if (!value.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.TryGetConverterForType(value.Type, out var _)) { throw new InvalidOperationException($"Type '{value.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value, visitor, context, path, serializer); } } } namespace YamlDotNet.Serialization.ObjectFactories { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] 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 (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsInterface(type)) { Type value2; if (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsGenericType(type)) { if (defaultGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out var value)) { type = value.MakeGenericType(type.GetGenericArguments()); } } else if (defaultNonGenericInterfaceImplementations.TryGetValue(type, out value2)) { type = value2; } } try { return Activator.CreateInstance(type, settings.AllowPrivateConstructors); } catch (Exception innerException) { string message = "Failed to create an instance of type '" + type.FullName + "'."; throw new InvalidOperationException(message, innerException); } } public override void ExecuteOnDeserialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializedAttribute), value); } public override void ExecuteOnDeserializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnDeserializingAttribute), value); } public override void ExecuteOnSerialized(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializedAttribute), value); } public override void ExecuteOnSerializing(object value) { ExecuteState(typeof(YamlDotNet.Serialization.Callbacks.OnSerializingAttribute), value); } private void ExecuteState(Type attributeType, object value) { if (value != null) { Type type = value.GetType(); MethodInfo[] array = GetStateMethods(attributeType, type); MethodInfo[] array2 = array; foreach (MethodInfo methodInfo in array2) { methodInfo.Invoke(value, null); } } } private MethodInfo[] GetStateMethods(Type attributeType, Type valueType) { ConcurrentDictionary concurrentDictionary = stateMethods[attributeType]; return concurrentDictionary.GetOrAdd(valueType, delegate(Type type) { MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return methods.Where([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (MethodInfo x) => x.GetCustomAttributes(attributeType, inherit: true).Length != 0).ToArray(); }); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] 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); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class ObjectFactoryBase : <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory { public abstract object Create(Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public virtual object CreatePrimitive(Type type) { if (!<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsValueType(type)) { 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, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out IDictionary dictionary, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { Type implementationOfOpenGenericInterface = descriptor.Type.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); if (implementationOfOpenGenericInterface != null) { genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); object obj = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), descriptor.Value); dictionary = obj as IDictionary; return true; } genericArguments = null; dictionary = null; return false; } public virtual Type GetValueType(Type type) { Type implementationOfOpenGenericInterface = type.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); return (implementationOfOpenGenericInterface != null) ? implementationOfOpenGenericInterface.GetGenericArguments()[0] : typeof(object); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class StaticObjectFactory : <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory { public abstract object Create(Type type); public abstract Array CreateArray(Type type, int count); public abstract bool IsDictionary(Type type); public abstract bool IsArray(Type type); public abstract bool IsList(Type type); public abstract Type GetKeyType(Type type); public abstract Type GetValueType(Type type); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public virtual object CreatePrimitive(Type type) { return Type.GetTypeCode(type) switch { TypeCode.Boolean => false, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, TypeCode.Int32 => 0, TypeCode.Int64 => 0L, TypeCode.SByte => (sbyte)0, TypeCode.UInt16 => (ushort)0, TypeCode.UInt32 => 0u, TypeCode.UInt64 => 0uL, TypeCode.Single => 0f, TypeCode.Double => 0.0, TypeCode.Decimal => 0m, TypeCode.Char => '\0', TypeCode.DateTime => default(DateTime), _ => null, }; } public bool GetDictionary(IObjectDescriptor descriptor, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out IDictionary dictionary, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] out Type[] genericArguments) { dictionary = null; genericArguments = null; return false; } public abstract void ExecuteOnDeserializing(object value); public abstract void ExecuteOnDeserialized(object value); public abstract void ExecuteOnSerializing(object value); public abstract void ExecuteOnSerialized(object value); } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class <40fc379e-fd56-4bf4-954d-70c432fa9170>DefaultContainersNodeTypeResolver : INodeTypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] bool INodeTypeResolver.Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { if (currentType == typeof(object)) { if (nodeEvent is <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>MappingNodeTypeResolver : INodeTypeResolver { private readonly IDictionary mappings; public <6469b4ae-5939-4b20-8a65-bfcbcecd0a0f>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([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { if (mappings.TryGetValue(currentType, out var value)) { currentType = value; return true; } return false; } } internal class <8f7fb5dc-912b-4219-99f2-8d060b974e6c>PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] bool INodeTypeResolver.Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(nodeEvent.Start, nodeEvent.End, $"Encountered an unresolved tag '{nodeEvent.Tag}'"); } return false; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> tagMappings; public <03413113-99bb-44b0-b5dc-35f8b7823077>TagNodeTypeResolver(IDictionary<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName, Type> tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out var value)) { currentType = value; return true; } return false; } } [Obsolete("The mechanism that this class uses to specify type names is non-standard. Register the tags explicitly instead of using this convention.")] internal sealed class <9d5ee331-7f56-4074-8ded-59a687eb7a3f>TypeNameInTagNodeTypeResolver : INodeTypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] bool INodeTypeResolver.Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>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 { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public bool Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { return typeof(<1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public bool Resolve([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent, ref Type currentType) { return typeof(<2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <556e34b0-5b06-48b9-b357-3906846f0467>ArrayNodeDeserializer : INodeDeserializer { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 2 })] private object[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] public object SyncRoot { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] get { return data; } } public ArrayList() { Clear(); } public int Add(object value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object value) { throw new NotSupportedException(); } int IList.IndexOf(object value) { throw new NotSupportedException(); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public <556e34b0-5b06-48b9-b357-3906846f0467>ArrayNodeDeserializer(<22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!expectedType.IsArray) { value = false; return false; } Type itemType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); Array array = null; <8397dec6-ad4e-45f3-b8d3-220c077b8b45>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; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] void PromiseResolvedHandler(int index, object value2) { if (array == null) { throw new InvalidOperationException("Destination array is still null"); } array.SetValue(TypeConverter.ChangeType(value2, itemType, enumNamingConvention, typeInspector), index); } } } internal abstract class CollectionDeserializer { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] protected static void DeserializeHelper(Type tItem, <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, IList result, bool canUpdate, <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory) { parser.Consume<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart>(); <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd @event; while (!parser.TryConsume<<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd>(out @event)) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise IValuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, current?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(objectFactory.CreatePrimitive(tItem)); IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <8397dec6-ad4e-45f3-b8d3-220c077b8b45>CollectionNodeDeserializer : INodeDeserializer { private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public <8397dec6-ad4e-45f3-b8d3-220c077b8b45>CollectionNodeDeserializer(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { bool canUpdate = true; Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(ICollection<>)); Type type; IList list; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); type = genericArguments[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { Type implementationOfOpenGenericInterface2 = expectedType.GetImplementationOfOpenGenericInterface(typeof(IList<>)); canUpdate = implementationOfOpenGenericInterface2 != null; list = (IList)Activator.CreateInstance(typeof(<76b22c15-364d-460d-8f55-204a4246f2eb>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, <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, IList result, bool canUpdate, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] Action promiseResolvedHandler = null) { parser.Consume<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart>(); <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd @event; while (!parser.TryConsume<<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd>(out @event)) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise IValuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, current?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsValueType(tItem) ? Activator.CreateInstance(tItem) : null); if (promiseResolvedHandler != null) { IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { promiseResolvedHandler(index, v); }; } else { IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { result[index] = TypeConverter.ChangeType(v, tItem, enumNamingConvention, typeInspector); }; } } else { result.Add(TypeConverter.ChangeType(obj, tItem, enumNamingConvention, typeInspector)); } } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class DictionaryDeserializer { private readonly bool duplicateKeyChecking; public DictionaryDeserializer(bool duplicateKeyChecking) { this.duplicateKeyChecking = duplicateKeyChecking; } private void TryAssign(IDictionary result, object key, object value, <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart propertyName) { if (duplicateKeyChecking && result.Contains(key)) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(propertyName.Start, propertyName.End, $"Encountered duplicate key {key}"); } result[key] = value; } protected virtual void Deserialize(Type tKey, Type tValue, <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, IDictionary result, ObjectDeserializer rootDeserializer) { <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart property = parser.Consume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(); <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd @event; while (!parser.TryConsume<<6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd>(out @event)) { object key = nestedObjectDeserializer(parser, tKey); object value = nestedObjectDeserializer(parser, tValue); IValuePromise IValuePromise = value as IValuePromise; if (key is IValuePromise IValuePromise2) { if (IValuePromise == null) { IValuePromise2.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { result[v] = value; }; continue; } bool hasFirstPart = false; IValuePromise2.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, v, value, property); } else { key = v; hasFirstPart = true; } }; IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { if (hasFirstPart) { TryAssign(result, key, v, property); } else { value = v; hasFirstPart = true; } }; continue; } if (key == null) { throw new ArgumentException("Empty key names are not supported yet.", "tKey"); } if (IValuePromise == null) { TryAssign(result, key, value, property); continue; } IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { result[key] = v; }; } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class DictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; public DictionaryNodeDeserializer(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementationOfOpenGenericInterface != null) { Type[] genericArguments = implementationOfOpenGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } Deserialize(type, type2, parser, nestedObjectDeserializer, dictionary, rootDeserializer); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementationOfOpenGenericInterface = expectedType.GetImplementationOfOpenGenericInterface(typeof(IEnumerable<>)); if (implementationOfOpenGenericInterface != expectedType) { value = null; return false; } type = implementationOfOpenGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class FsharpListNodeDeserializer : INodeDeserializer { private readonly ITypeInspector typeInspector; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; public FsharpListNodeDeserializer(ITypeInspector typeInspector, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention) { this.typeInspector = typeInspector; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!FsharpHelper.IsFsharpListType(expectedType)) { value = false; return false; } Type type = expectedType.GetGenericArguments()[0]; Type t = expectedType.GetGenericTypeDefinition().MakeGenericType(type); ArrayList arrayList = new ArrayList(); <8397dec6-ad4e-45f3-b8d3-220c077b8b45>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 { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { value = null; if (parser.Accept<<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent>(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] private static bool NodeIsNull(<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is Scalar { Style: ScalarStyle.Plain, IsKey: false, Value: var value }) { switch (value) { default: return value == "NULL"; case "": case "~": case "null": case "Null": return true; } } return false; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; private readonly ITypeInspector typeInspector; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly bool enforceNullability; private readonly bool caseInsensitivePropertyMatching; private readonly bool enforceRequiredProperties; private readonly TypeConverterCache typeConverters; public ObjectNodeDeserializer(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory, ITypeInspector typeInspector, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, bool enforceNullability, bool caseInsensitivePropertyMatching, bool enforceRequiredProperties, IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> 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(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(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); <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty; <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd event2; while (!parser.TryConsume<<6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd>(out event2)) { Scalar propertyName = parser.Consume<Scalar>(); if (duplicateKeyChecking && !hashSet.Add(propertyName.Value)) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>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) { <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter converterByType = typeConverters.GetConverterByType(property.ConverterType); obj = converterByType.ReadYaml(parser, property.Type, rootDeserializer); } else { obj = nestedObjectDeserializer(parser, property.Type); } if (obj is IValuePromise IValuePromise) { object valueRef = value; IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { object value3 = typeConverter.ChangeType(v, property.Type, enumNamingConvention, typeInspector); NullCheck(value3, property, propertyName); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type, enumNamingConvention, typeInspector); NullCheck(value2, property, propertyName); property.Write(value, value2); } } catch (SerializationException ex) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(propertyName.Start, propertyName.End, ex.Message); } catch (<9f1d586b-d77e-4258-bb38-eb176815536f>YamlException) { throw; } catch (Exception innerException) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(propertyName.Start, propertyName.End, "Exception during deserialization", innerException); } start = propertyName.End; } if (enforceRequiredProperties) { IEnumerable<IPropertyDescriptor> 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 <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(in start, in start, "Missing properties, '" + text + "' in source yaml."); } } objectFactory.ExecuteOnDeserialized(value); return true; } public void NullCheck(object value, IPropertyDescriptor property, Scalar propertyName) { if (enforceNullability && value == null && !property.AllowNulls) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(propertyName.Start, propertyName.End, "Strict nullability enforcement error.", new NullReferenceException("Yaml value is null when target property requires non null values.")); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; private readonly bool attemptUnknownTypeDeserialization; private readonly ITypeConverter typeConverter; private readonly ITypeInspector typeInspector; private readonly YamlFormatter formatter; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter, ITypeInspector typeInspector, YamlFormatter formatter, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); this.typeInspector = typeInspector; this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!parser.TryConsume<Scalar>(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? FsharpHelper.GetOptionUnderlyingType(expectedType) ?? expectedType; if (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsEnum(type)) { string name = enumNamingConvention.Reverse(@event.Value); name = typeInspector.GetEnumName(type, name); value = Enum.Parse(type, name, ignoreCase: true); return true; } TypeCode typeCode = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetTypeCode(type); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, formatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { if (!@event.IsKey && attemptUnknownTypeDeserialization) { value = AttemptUnknownTypeDeserialization(@event); } else { value = @event.Value; } } else { value = typeConverter.ChangeType(@event.Value, expectedType, enumNamingConvention, typeInspector); } break; } return true; } private static bool DeserializeBooleanHelper(string value) { if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { return true; } if (Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { return false; } throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } private object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; int i = 0; bool flag = false; ulong num = 0uL; if (value[0] == '-') { i++; flag = true; } else if (value[0] == '+') { i++; } if (value[i] == '0') { int num2; if (i == value.Length - 1) { num2 = 10; num = 0uL; } else { i++; if (value[i] == 'b') { num2 = 2; i++; } else if (value[i] == 'x') { num2 = 16; i++; } else { num2 = 8; } } for (; i < value.Length; i++) { if (value[i] != '_') { builder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(builder.ToString(), num2); break; case 16: num = ulong.Parse(builder.ToString(), NumberStyles.HexNumber, formatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", ""), CultureInfo.InvariantCulture); } } if (!flag) { return CastInteger(num, typeCode); } long number = ((num != 9223372036854775808uL) ? checked(-(long)num) : long.MinValue); return CastInteger(number, typeCode); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private static object CastInteger(long number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => (ulong)number, _ => number, }); } private static object CastInteger(ulong number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => (long)number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => number, _ => number, }); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private object AttemptUnknownTypeDeserialization(Scalar value) { if (value.Style == ScalarStyle.SingleQuoted || value.Style == ScalarStyle.DoubleQuoted || value.Style == ScalarStyle.Folded) { return value.Value; } string v = value.Value; switch (v) { case "null": case "Null": case "NULL": case "~": case "": return null; case "true": case "True": case "TRUE": return true; case "False": case "FALSE": case "false": return false; default: if (Regex.IsMatch(v, "^0x[0-9a-fA-F]+$")) { v = v.Substring(2); if (byte.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result)) { return result; } if (short.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result2)) { return result2; } if (int.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result3)) { return result3; } if (long.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result4)) { return result4; } if (ulong.TryParse(v, NumberStyles.AllowHexSpecifier, formatter.NumberFormat, out var result5)) { return result5; } return v; } if (Regex.IsMatch(v, "^0o[0-9a-fA-F]+$")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out var value2) && !TryAndSwallow(() => Convert.ToInt16(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 8), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 8), out value2)) { return v; } return value2; } if (Regex.IsMatch(v, "^[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?$")) { if (byte.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result6)) { return result6; } if (short.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result7)) { return result7; } if (int.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result8)) { return result8; } if (long.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result9)) { return result9; } if (ulong.TryParse(v, NumberStyles.Integer, formatter.NumberFormat, out var result10)) { return result10; } if (float.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result11)) { return result11; } if (double.TryParse(v, NumberStyles.Float, formatter.NumberFormat, out var result12)) { return result12; } return v; } if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (Polyfills.StartsWith(v, '-')) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } } private static bool TryAndSwallow(Func attempt, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value) { try { value = attempt(); return true; } catch { value = null; return false; } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private sealed class ArrayList : IList, ICollection, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 2 })] private object[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] public object SyncRoot { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] get { return data; } } public ArrayList() { Clear(); } public int Add(object value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object value) { throw new NotSupportedException(); } int IList.IndexOf(object value) { throw new NotSupportedException(); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly StaticObjectFactory factory; public StaticArrayNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!factory.IsArray(expectedType)) { value = false; return false; } Type valueType = factory.GetValueType(expectedType); ArrayList arrayList = new ArrayList(); StaticCollectionNodeDeserializer.DeserializeHelper(valueType, parser, nestedObjectDeserializer, arrayList, factory); Array array = factory.CreateArray(expectedType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class StaticCollectionNodeDeserializer : INodeDeserializer { private readonly StaticObjectFactory factory; public StaticCollectionNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!factory.IsList(expectedType)) { value = null; return false; } DeserializeHelper(result: (IList)(value = factory.Create(expectedType) as IList), tItem: factory.GetValueType(expectedType), parser: parser, nestedObjectDeserializer: nestedObjectDeserializer, factory: factory); return true; } internal static void DeserializeHelper(Type tItem, <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, IList result, <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory factory) { parser.Consume<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart>(); <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd @event; while (!parser.TryConsume<<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd>(out @event)) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise IValuePromise) { int index = result.Add(factory.CreatePrimitive(tItem)); IValuePromise.ValueAvailable += [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] (object v) => { result[index] = v; }; } else { result.Add(obj); } } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser reader, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (objectFactory.IsDictionary(expectedType)) { if (!(objectFactory.Create(expectedType) is IDictionary dictionary)) { value = null; return false; } Type keyType = objectFactory.GetKeyType(expectedType); Type valueType = objectFactory.GetValueType(expectedType); value = dictionary; base.Deserialize(keyType, valueType, reader, nestedObjectDeserializer, dictionary, rootDeserializer); return true; } value = null; return false; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly TypeConverterCache converters; public TypeConverterNodeDeserializer(IEnumerable<<87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter> converters) { this.converters = new TypeConverterCache(converters); } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!converters.TryGetConverterForType(expectedType, out var typeConverter)) { value = null; return false; } value = typeConverter.ReadYaml(parser, expectedType, rootDeserializer); return true; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (typeof(<1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible).IsAssignableFrom(expectedType)) { <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible = (<1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible)objectFactory.Create(expectedType); <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Read(parser, expectedType, [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] (Type type) => nestedObjectDeserializer(parser, type)); value = <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible; return true; } value = null; return false; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly <27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(<27829ecc-c9ac-43bc-8d81-40fa384ecb07>IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (typeof(<2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable).IsAssignableFrom(expectedType)) { <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable = (<2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable)objectFactory.Create(expectedType); <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable.ReadYaml(parser); value = <2dea703b-a845-4fd8-817f-9ff9bfab312c>IYamlSerializable; return true; } value = null; return false; } } } namespace YamlDotNet.Serialization.NamingConventions { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <009e614f-34cc-4966-aebd-f8f248231a77>CamelCaseNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <009e614f-34cc-4966-aebd-f8f248231a77>CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public <009e614f-34cc-4966-aebd-f8f248231a77>CamelCaseNamingConvention() { } public string Apply(string value) { return StringExtensions.ToCamelCase(value); } public string Reverse(string value) { return StringExtensions.ToPascalCase(value); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <3e3d20d1-3d13-425c-9160-683e859235af>HyphenatedNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <3e3d20d1-3d13-425c-9160-683e859235af>HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public <3e3d20d1-3d13-425c-9160-683e859235af>HyphenatedNamingConvention() { } public string Apply(string value) { return StringExtensions.FromCamelCase(value, "-"); } public string Reverse(string value) { return StringExtensions.ToPascalCase(value); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <16b42846-714c-4ba8-af0e-d9e44633858a>LowerCaseNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <16b42846-714c-4ba8-af0e-d9e44633858a>LowerCaseNamingConvention(); private <16b42846-714c-4ba8-af0e-d9e44633858a>LowerCaseNamingConvention() { } public string Apply(string value) { return StringExtensions.ToCamelCase(value).ToLower(CultureInfo.InvariantCulture); } public string Reverse(string value) { if (string.IsNullOrEmpty(value)) { return value; } return char.ToUpperInvariant(value[0]) + value.Substring(1); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public <1eeb8daa-cbd3-4e44-befe-3b0cff23d0bd>NullNamingConvention() { } public string Apply(string value) { return value; } public string Reverse(string value) { return value; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <8e10dd72-74a1-4220-9bd0-e5ec404e2cc9>PascalCaseNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <8e10dd72-74a1-4220-9bd0-e5ec404e2cc9>PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public <8e10dd72-74a1-4220-9bd0-e5ec404e2cc9>PascalCaseNamingConvention() { } public string Apply(string value) { return StringExtensions.ToPascalCase(value); } public string Reverse(string value) { return StringExtensions.ToPascalCase(value); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <8a390e0b-785a-4253-9e2d-fc4f1264bfb0>UnderscoredNamingConvention : <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention { public static readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention Instance = new <8a390e0b-785a-4253-9e2d-fc4f1264bfb0>UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public <8a390e0b-785a-4253-9e2d-fc4f1264bfb0>UnderscoredNamingConvention() { } public string Apply(string value) { return StringExtensions.FromCamelCase(value, "_"); } public string Reverse(string value) { return StringExtensions.ToPascalCase(value); } } } namespace YamlDotNet.Serialization.EventEmitters { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class <72886f32-17d8-4d43-afc2-627549f27228>ChainedEventEmitter : IEventEmitter { protected readonly IEventEmitter nextEmitter; protected <72886f32-17d8-4d43-afc2-627549f27228>ChainedEventEmitter(IEventEmitter nextEmitter) { this.nextEmitter = nextEmitter ?? throw new ArgumentNullException("nextEmitter"); } public virtual void Emit(<8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(<517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(<83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(<380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <812a1307-50d5-4cad-af94-0a766241641b>JsonEventEmitter : <72886f32-17d8-4d43-afc2-627549f27228>ChainedEventEmitter { private readonly YamlFormatter formatter; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public <812a1307-50d5-4cad-af94-0a766241641b>JsonEventEmitter(IEventEmitter nextEmitter, YamlFormatter formatter, <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention, ITypeInspector typeInspector) : base(nextEmitter) { this.formatter = formatter; this.enumNamingConvention = enumNamingConvention; this.typeInspector = typeInspector; } public override void Emit(<8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>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 = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetTypeCode(eventInfo.Source.Type); 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 (<1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.IsEnum(eventInfo.Source.Type)) { 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(<517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class TypeAssigningEventEmitter : <72886f32-17d8-4d43-afc2-627549f27228>ChainedEventEmitter { private readonly IDictionaryTagName> tagMappings; private readonly bool quoteNecessaryStrings; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private readonly Regex isSpecialStringValue_Regex; private static readonly string SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\\.inf|\\.Inf|\\.INF)|\\.nan|\\.NaN|\\.NAN|\\s.*)$"; private static readonly string CombinedYaml1_1SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?0b[0-1_]+|[-+]?0o?[0-7_]+|[-+]?(0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(:[0-5]?[0-9])+|[-+]?([0-9][0-9_]*)?\\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(inf|Inf|INF)|\\.(nan|NaN|NAN))$"; private readonly ScalarStyle defaultScalarStyle; private readonly YamlFormatter formatter; private readonly <22599784-6051-4a47-9318-0a6f38d04add>INamingConvention enumNamingConvention; private readonly ITypeInspector typeInspector; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, IDictionaryTagName> tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings, ScalarStyle defaultScalarStyle, YamlFormatter formatter, <22599784-6051-4a47-9318-0a6f38d04add>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 = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetTypeCode(eventInfo.Source.Type); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>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 = <8d895882-c8ed-485d-b56e-0908b5de98e0>FailsafeSchema.Tags.Str; eventInfo.RenderedValue = formatter.FormatEnum(value, typeInspector, enumNamingConvention); style = ((!quoteNecessaryStrings || !IsSpecialStringValue(eventInfo.RenderedValue) || !formatter.PotentiallyQuoteEnums(value)) ? defaultScalarStyle : ScalarStyle.DoubleQuoted); } else { eventInfo.Tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Int; eventInfo.RenderedValue = formatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Float; eventInfo.RenderedValue = formatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = <8d895882-c8ed-485d-b56e-0908b5de98e0>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 = <28c6112a-e6be-4658-97e4-f17b05c4398a>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(<517310a7-92ce-449a-80a4-4e82692734cd>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(<1e3efad0-1dd4-4910-a072-9bbea5951f51>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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <40dc4525-a553-4415-93ab-24b96dc27d3e>WriterEventEmitter : IEventEmitter { void IEventEmitter.Emit(<8ab006ca-e2bb-4f10-a13d-81ee5beb72f0>AliasEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new AnchorAlias(eventInfo.Alias)); } void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); } void IEventEmitter.Emit(<517310a7-92ce-449a-80a4-4e82692734cd>MappingStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(<83be912d-5b4b-447a-8cef-354a7f594549>MappingEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd()); } void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(<380c25df-06bf-478d-a0bc-72bdb1edd81e>SequenceEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd()); } } } namespace YamlDotNet.Serialization.Converters { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class DateTime8601Converter : <87461092-0374-4a6c-919c-f5a28d630352>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(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume<Scalar>().Value; DateTime dateTime = DateTime.ParseExact(value, "O", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); return dateTime; } public void WriteYaml(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer) { string value2 = ((DateTime)value).ToString("O", CultureInfo.InvariantCulture); emitter.Emit(new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, value2, scalarStyle, isPlainImplicit: true, isQuotedImplicit: false)); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class DateTimeConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly bool doubleQuotes; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IFormatProvider provider = null, bool doubleQuotes = false, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.doubleQuotes = doubleQuotes; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume<Scalar>().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, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class DateTimeOffsetConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { private readonly IFormatProvider provider; private readonly ScalarStyle style; private readonly DateTimeStyles dateStyle; private readonly string[] formats; public DateTimeOffsetConverter([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] IFormatProvider provider = null, ScalarStyle style = ScalarStyle.Any, DateTimeStyles dateStyle = DateTimeStyles.None, params string[] formats) { this.provider = provider ?? CultureInfo.InvariantCulture; this.style = style; this.dateStyle = dateStyle; this.formats = formats.DefaultIfEmpty("O").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTimeOffset); } public object ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume<Scalar>().Value; DateTimeOffset dateTimeOffset = DateTimeOffset.ParseExact(value, formats, provider, dateStyle); return dateTimeOffset; } public void WriteYaml(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer) { string value2 = ((DateTimeOffset)value).ToString(formats.First(), provider); emitter.Emit(new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, value2, style, isPlainImplicit: true, isQuotedImplicit: false)); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class GuidConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume<Scalar>().Value; return new Guid(value); } public void WriteYaml(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer) { Guid guid = (Guid)value; emitter.Emit(new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <8397bddf-2f11-40f5-a93f-524634501e3b>SystemTypeConverter : <87461092-0374-4a6c-919c-f5a28d630352>IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type type, ObjectDeserializer rootDeserializer) { string value = parser.Consume<Scalar>().Value; return Type.GetType(value, throwOnError: true); } public void WriteYaml(IEmitter emitter, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value, Type type, ObjectSerializer serializer) { Type type2 = (Type)value; emitter.Emit(new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>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 { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly LinkedList<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> buffer; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] private LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> current; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Current { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return current?.Value; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public ParserBuffer(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parserToBuffer, int maxDepth, int maxLength) { buffer = new LinkedList<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); buffer.AddLast(parserToBuffer.Consume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>()); int num = 0; do { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent = parserToBuffer.Consume<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); num += <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent.NestingIncrease; buffer.AddLast(<905c4171-2b55-4d94-bed7-421e597b1406>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; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class TypeDiscriminatingNodeDeserializer : INodeDeserializer { private readonly IList<INodeDeserializer> innerDeserializers; private readonly IList typeDiscriminators; private readonly int maxDepthToBuffer; private readonly int maxLengthToBuffer; public TypeDiscriminatingNodeDeserializer(IList<INodeDeserializer> innerDeserializers, IList typeDiscriminators, int maxDepthToBuffer, int maxLengthToBuffer) { this.innerDeserializers = innerDeserializers; this.typeDiscriminators = typeDiscriminators; this.maxDepthToBuffer = maxDepthToBuffer; this.maxLengthToBuffer = maxLengthToBuffer; } public bool Deserialize(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser reader, Type expectedType, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 1, 1, 2 })] Func<<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser, Type, object> nestedObjectDeserializer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out object value, ObjectDeserializer rootDeserializer) { if (!reader.Accept<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (ITypeDiscriminator t) => t.BaseType.IsAssignableFrom(expectedType)); if (!enumerable.Any()) { value = null; return false; } <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = reader.Current.Start; Type expectedType2 = expectedType; ParserBuffer parserBuffer; try { parserBuffer = new ParserBuffer(reader, maxDepthToBuffer, maxLengthToBuffer); } catch (Exception innerException) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(in start, reader.Current.End, "Failed to buffer yaml node", innerException); } try { foreach (ITypeDiscriminator item in enumerable) { parserBuffer.Reset(); if (item.TryDiscriminate(parserBuffer, out var suggestedType)) { expectedType2 = suggestedType; break; } } } catch (Exception innerException2) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>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; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser buffer, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out Type suggestedType); } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class KeyValueTypeDiscriminator : ITypeDiscriminator { private readonly string targetKey; private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public KeyValueTypeDiscriminator(Type baseType, string targetKey, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.targetKey = targetKey; this.typeMapping = typeMapping; } public bool TryDiscriminate(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out Type suggestedType) { if (parser.TryFindMappingEntry((Scalar scalar) => targetKey == scalar.Value, out var _, out var value) && value is Scalar Scalar && typeMapping.TryGetValue(Scalar.Value, out var value2)) { suggestedType = value2; return true; } suggestedType = null; return false; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] 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(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] out Type suggestedType) { if (parser.TryFindMappingEntry((Scalar scalar) => typeMapping.ContainsKey(scalar.Value), out var key, out var _)) { suggestedType = typeMapping[key.Value]; return true; } suggestedType = null; return false; } } } namespace YamlDotNet.RepresentationModel { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState { private readonly Dictionary<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> anchors = new Dictionary<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); private readonly List<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> nodesWithUnresolvedAliases = new List<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); public void AddAnchor(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } anchors[node.Anchor] = node; } public <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode GetNode(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) { if (anchors.TryGetValue(anchor, out var value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public bool TryGetNode(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, [NotNullWhen(true)] out <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode node) { return anchors.TryGetValue(anchor, out node); } public void AddNodeWithUnresolvedAliases(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode node) { nodesWithUnresolvedAliases.Add(node); } public void ResolveAliases() { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode nodesWithUnresolvedAlias in nodesWithUnresolvedAliases) { nodesWithUnresolvedAlias.ResolveAliases(this); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState { public HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName> EmittedAnchors { get; } = new HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName>(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor { void Visit(YamlStream stream); void Visit(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document); void Visit(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class LibYamlEventStream { private readonly <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser; public LibYamlEventStream(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser iParser) { parser = iParser ?? throw new ArgumentNullException("iParser"); } public void WriteTo(TextWriter textWriter) { while (parser.MoveNext()) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; if (!(current is AnchorAlias AnchorAlias)) { if (!(current is DocumentEnd DocumentEnd)) { if (!(current is DocumentStart DocumentStart)) { if (!(current is <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd)) { if (!(current is <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart nodeEvent)) { if (!(current is Scalar Scalar)) { if (!(current is <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd)) { if (!(current is <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart nodeEvent2)) { if (!(current is <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd)) { if (current is <59ed284a-0453-414f-99b7-7b2f5da6af66>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, <5b4e1044-096b-4e5c-b704-551fa771adb2>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(">"); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode : <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode { public override YamlNodeType NodeType => YamlNodeType.Alias; internal <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor) { base.Anchor = anchor; } internal override void ResolveAliases(<8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); } internal override void Emit(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); } public override void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode2 && Equals(<97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode2)) { return object.Equals(base.Anchor, <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode2.Anchor); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal override string ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { return "*" + base.Anchor; } internal override IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> SafeAllNodes(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { yield return this; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class AnchorAssigningVisitor : <606e002a-80b6-43cd-96e7-8ae51d3cfe5e>YamlVisitorBase { private readonly HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName> existingAnchors = new HashSet<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName>(); private readonly Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, bool> visitedNodes = new Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, bool>(); public void AssignAnchors(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, bool> visitedNode in visitedNodes) { if (!visitedNode.Value) { continue; } <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName; if (!visitedNode.Key.Anchor.IsEmpty && !existingAnchors.Contains(visitedNode.Key.Anchor)) { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName = visitedNode.Key.Anchor; } else { do { <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName = new <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName(random.Next().ToString(CultureInfo.InvariantCulture)); } while (existingAnchors.Contains(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName)); } existingAnchors.Add(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName); visitedNode.Key.Anchor = <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName; } } private bool VisitNodeAndFindDuplicates(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>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(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar) { VisitNodeAndFindDuplicates(scalar); } public override void Visit(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { if (!VisitNodeAndFindDuplicates(mapping)) { base.Visit(mapping); } } public override void Visit(YamlSequenceNode sequence) { if (!VisitNodeAndFindDuplicates(sequence)) { base.Visit(sequence); } } } public <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode RootNode { get; private set; } public IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> AllNodes => RootNode.AllNodes; public <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode rootNode) { RootNode = rootNode; } public <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument(string rootNode) { RootNode = new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(rootNode); } internal <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) { <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState2 = new <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState(); parser.Consume<DocumentStart>(); DocumentEnd @event; while (!parser.TryConsume<DocumentEnd>(out @event)) { RootNode = <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode.ParseNode(parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState2); if (RootNode is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("A document cannot contain only an alias"); } } <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState2.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 DocumentStart()); RootNode.Save(emitter, new <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState()); emitter.Emit(new DocumentEnd(isImplicit: false)); } public void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { visitor.Visit(this); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode : <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, IEnumerableYamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>>, IEnumerable, <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible { private readonly OrderedDictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> children = new OrderedDictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); public <8708c545-30be-4eab-b3f7-c47674d5a48c>IOrderedDictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Load(parser, state); } private void Load(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart = parser.Consume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(); Load(<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart, state); Style = <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart.Style; bool flag = false; <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd @event; while (!parser.TryConsume<<6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd>(out @event)) { <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 = <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode.ParseNode(parser, state); <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode3 = <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode.ParseNode(parser, state); if (!children.TryAdd(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode3)) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2.Start, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2.End, $"Duplicate key {<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2}"); } flag = flag || <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode || <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode3 is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode() { } public <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] params KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>[] children) : this((IEnumerableYamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>>)children) { } public <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] IEnumerableYamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>> children) { foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { this.children.Add(child); } } public <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode(params <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode[] children) : this((IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>)children) { } public <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode(IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> children) { using IEnumerator<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> enumerator = children.GetEnumerator(); while (enumerator.MoveNext()) { <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>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(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode key, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode value) { children.Add(key, value); } public void Add(string key, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode value) { children.Add(new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(key), value); } public void Add(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode key, string value) { children.Add(key, new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(value)); } public void Add(string key, string value) { children.Add(new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(key), new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(value)); } internal override void ResolveAliases(<8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> dictionary = null; Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> dictionary2 = null; foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { if (child.Key is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode) { if (dictionary == null) { dictionary = new Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); } dictionary.Add(child.Key, state.GetNode(child.Key.Anchor, child.Key.Start, child.Key.End)); } if (child.Value is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode) { if (dictionary2 == null) { dictionary2 = new Dictionary<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); } dictionary2.Add(child.Key, state.GetNode(child.Value.Anchor, child.Value.Start, child.Value.End)); } } if (dictionary2 != null) { foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> item in dictionary2) { children[item.Key] = item.Value; } } if (dictionary == null) { return; } foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> item2 in dictionary) { <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode value = children[item2.Key]; children.Remove(item2.Key); children.Add(item2.Value, value); } } internal override void Emit(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state) { emitter.Emit(new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(base.Anchor, base.Tag, isImplicit: true, Style)); foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { child.Key.Save(emitter, state); child.Value.Save(emitter, state); } emitter.Emit(new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd()); } public override void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { visitor.Visit(this); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (!(obj is <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2) || !object.Equals(base.Tag, <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2.Tag) || children.Count != <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2.children.Count) { return false; } foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { if (!<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2.children.TryGetValue(child.Key, out var value) || !object.Equals(child.Value, value)) { return false; } } return true; } public override int GetHashCode() { int num = base.GetHashCode(); foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { num = <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(num, child.Key); num = (child.Value.Anchor.IsEmpty ? <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(num, child.Value) : <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(num, child.Value.Anchor)); } return num; } internal override IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> SafeAllNodes(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("{ "); foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } builder.Append(" }"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] public IEnumeratorYamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>> GetEnumerator() { return children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Read(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState()); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState()); } public static <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2 = new <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode(); foreach (PropertyInfo publicProperty in <1d7297e8-11e2-4901-9933-27ac004563cd>ReflectionExtensions.GetPublicProperties(mapping.GetType())) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 = value as <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode; if (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 == null) { string text = Convert.ToString(value, CultureInfo.InvariantCulture); <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 = text ?? string.Empty; } <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2.Add(publicProperty.Name, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2); } } return <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode { private const int MaximumRecursionLevel = 1000; internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Anchor { get; set; } public <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Tag { get; set; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Start { get; private set; } = <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty; public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark End { get; private set; } = <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty; public IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> AllNodes { get { <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level = new <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel(1000); return SafeAllNodes(level); } } public abstract YamlNodeType NodeType { get; } public <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode this[int index] { get { if (!(this is YamlSequenceNode YamlSequenceNode2)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {index}. Only Sequences can be indexed by number."); } return YamlSequenceNode2.Children[index]; } } public <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode this[<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode key] { get { if (!(this is <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {key}. Only Mappings can be indexed by key."); } return <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode2.Children[key]; } } internal void Load(<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent yamlEvent, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Tag = yamlEvent.Tag; if (!yamlEvent.Anchor.IsEmpty) { Anchor = yamlEvent.Anchor; state.AddAnchor(this); } Start = yamlEvent.Start; End = yamlEvent.End; } internal static <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode ParseNode(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { if (parser.Accept<Scalar>(out var _)) { return new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(parser, state); } if (parser.Accept<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart>(out var _)) { return new YamlSequenceNode(parser, state); } if (parser.Accept<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(out var _)) { return new <8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode(parser, state); } if (parser.TryConsume<AnchorAlias>(out var event4)) { if (!state.TryGetNode(event4.Value, out var node)) { return new <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode(event4.Value); } return node; } throw new ArgumentException("The current event is of an unsupported type.", "parser"); } internal abstract void ResolveAliases(<8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state); internal void Save(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state) { if (!Anchor.IsEmpty && !state.EmittedAnchors.Add(Anchor)) { emitter.Emit(new AnchorAlias(Anchor)); } else { Emit(emitter, state); } } internal abstract void Emit(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state); public abstract void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor); public override string ToString() { <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel = new <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel(1000); return ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel); } internal abstract string ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level); internal abstract IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> SafeAllNodes(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level); public static implicit operator <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode(string value) { return new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(value); } public static implicit operator <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode(string[] sequence) { return new YamlSequenceNode(((IEnumerable)sequence).Select((FuncYamlNode>)([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (string i) => i))); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static explicit operator string(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode node) { if (!(node is <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode2)) { throw new ArgumentException($"Attempted to convert a '{node.NodeType}' to string. This conversion is valid only for Scalars."); } return <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode2.Value; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <48addd95-89bb-4cd6-b369-81d12da27f82>YamlNodeIdentityEqualityComparer : IEqualityComparer<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> { public bool Equals([<39198dc0-b9c8-4d82-ab34-59face54b949>AllowNull] <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode x, [<39198dc0-b9c8-4d82-ab34-59face54b949>AllowNull] <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode y) { return x == y; } public int GetHashCode(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode obj) { return obj.GetHashCode(); } } internal enum YamlNodeType { Alias, Mapping, Scalar, Sequence } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [DebuggerDisplay("{Value}")] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode : <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible { private bool forceImplicitPlain; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private string value; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public string Value { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return value; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set { if (value == null) { forceImplicitPlain = true; } else { forceImplicitPlain = false; } this.value = value; } } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Load(parser, state); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Load(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Scalar Scalar = parser.Consume<Scalar>(); 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 <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode() { } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(string value) { Value = value; } internal override void ResolveAliases(<8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state) { <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag = base.Tag; bool isPlainImplicit = tag.IsEmpty; if (forceImplicitPlain && Style == ScalarStyle.Plain && (Value == null || Value == "")) { tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Null; isPlainImplicit = true; } else if (tag.IsEmpty && Value == null && (Style == ScalarStyle.Plain || Style == ScalarStyle.Any)) { tag = <28c6112a-e6be-4658-97e4-f17b05c4398a>JsonSchema.Tags.Null; isPlainImplicit = true; } emitter.Emit(new Scalar(base.Anchor, tag, Value ?? string.Empty, Style, isPlainImplicit, isQuotedImplicit: false)); } public override void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { visitor.Visit(this); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode2 && object.Equals(base.Tag, <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode2.Tag)) { return object.Equals(Value, <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode2.Value); } return false; } public override int GetHashCode() { return <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(base.Tag.GetHashCode(), Value); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static explicit operator string(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode value) { return value.Value; } internal override string ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { return Value ?? string.Empty; } internal override IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> SafeAllNodes(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { yield return this; } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Read(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState()); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState()); } } [DebuggerDisplay("Count = {children.Count}")] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class YamlSequenceNode : <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>, IEnumerable, <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible { private readonly List<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> children = new List<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>(); public IList<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> Children => children; public <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { Load(parser, state); } private void Load(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart = parser.Consume<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart>(); Load(<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart, state); Style = <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart.Style; bool flag = false; <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd @event; while (!parser.TryConsume<<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd>(out @event)) { <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 = <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode.ParseNode(parser, state); children.Add(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2); flag = flag || <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode2 is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode[] children) : this((IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode>)children) { } public YamlSequenceNode(IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> children) { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in children) { this.children.Add(child); } } public void Add(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new <58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode(child)); } internal override void ResolveAliases(<8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is <97de943b-e87b-40b2-b936-b53f545a83ab>YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState state) { emitter.Emit(new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd()); } public override void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { visitor.Visit(this); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (!(obj is YamlSequenceNode YamlSequenceNode2) || !object.Equals(base.Tag, YamlSequenceNode2.Tag) || children.Count != YamlSequenceNode2.children.Count) { return false; } for (int i = 0; i < children.Count; i++) { if (!object.Equals(children[i], YamlSequenceNode2.children[i])) { return false; } } return true; } public override int GetHashCode() { int h = 0; foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in children) { h = <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(h, child); } return <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(h, base.Tag); } internal override IEnumerable<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> SafeAllNodes(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { level.Increment(); yield return this; foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in children) { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode item in child.SafeAllNodes(level)) { yield return item; } } level.Decrement(); } internal override string ToString(<4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("[ "); foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>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<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> GetEnumerator() { return Children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Read(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new <8b7cd7cf-b136-4675-a288-603bc67dcd7a>DocumentLoadingState()); } void <1e1b8387-788b-4f53-8d0e-f34a926546be>IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new <969243cc-83b4-49de-b5b3-8c255ecb455d>EmitterState()); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class YamlStream : IEnumerable<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument>, IEnumerable { private readonly List<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument> documents = new List<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument>(); public IList<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument> Documents => documents; public YamlStream() { } public YamlStream(params <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument[] documents) : this((IEnumerable<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument>)documents) { } public YamlStream(IEnumerable<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument> documents) { foreach (<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document in documents) { this.documents.Add(document); } } public void Add(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(<335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) { documents.Clear(); parser.Consume<<59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart>(); <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd @event; while (!parser.TryConsume<<751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd>(out @event)) { <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument item = new <9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart()); foreach (<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd()); } public void Accept(<03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator<<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument> GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [Obsolete("Use YamlVisitorBase")] internal abstract class <1d9e9071-3859-4ee2-8b2c-d78db7f02d6b>YamlVisitor : <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor { protected virtual void Visit(YamlStream stream) { } protected virtual void Visited(YamlStream stream) { } protected virtual void Visit(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { } protected virtual void Visited(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { } protected virtual void Visit(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar) { } protected virtual void Visited(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar) { } protected virtual void Visit(YamlSequenceNode sequence) { } protected virtual void Visited(YamlSequenceNode sequence) { } protected virtual void Visit(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { } protected virtual void Visited(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { } protected virtual void VisitChildren(YamlStream stream) { foreach (<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in mapping.Children) { child.Key.Accept(this); child.Value.Accept(this); } } void <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor.Visit(YamlStream stream) { Visit(stream); VisitChildren(stream); Visited(stream); } void <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor.Visit(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { Visit(document); VisitChildren(document); Visited(document); } void <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor.Visit(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar) { Visit(scalar); Visited(scalar); } void <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor.Visit(YamlSequenceNode sequence) { Visit(sequence); VisitChildren(sequence); Visited(sequence); } void <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor.Visit(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { Visit(mapping); VisitChildren(mapping); Visited(mapping); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal abstract class <606e002a-80b6-43cd-96e7-8ae51d3cfe5e>YamlVisitorBase : <03cfe12e-3907-4986-8943-cd1502c09b5e>IYamlVisitor { public virtual void Visit(YamlStream stream) { VisitChildren(stream); } public virtual void Visit(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { VisitChildren(document); } public virtual void Visit(<58303056-0ce9-417e-a235-05c15262fb8a>YamlScalarNode scalar) { } public virtual void Visit(YamlSequenceNode sequence) { VisitChildren(sequence); } public virtual void Visit(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { VisitChildren(mapping); } protected virtual void VisitPair(<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode key, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode value) { key.Accept(this); value.Accept(this); } protected virtual void VisitChildren(YamlStream stream) { foreach (<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(<9ecacc22-31d4-4595-8e60-6464fc68f569>YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(<8486b05d-81e6-4322-8fc7-7a149af86c64>YamlMappingNode mapping) { foreach (KeyValuePair<<99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode, <99f363be-4aa2-4d0a-a2b2-5bd5487310c6>YamlNode> child in mapping.Children) { VisitPair(child.Key, child.Value); } } } } namespace YamlDotNet.Helpers { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class DefaultFsharpHelper : IFsharpHelper { private static bool IsFsharpCore(Type t) { return t.Namespace == "Microsoft.FSharp.Core"; } public bool IsOptionType(Type t) { if (IsFsharpCore(t)) { return t.Name == "FSharpOption`1"; } return false; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type GetOptionUnderlyingType(Type t) { if (!t.IsGenericType || !IsOptionType(t)) { return null; } return t.GenericTypeArguments[0]; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object GetValue(IObjectDescriptor objectDescriptor) { if (!IsOptionType(objectDescriptor.Type)) { throw new InvalidOperationException("Should not be called on non-Option<> type"); } if (objectDescriptor.Value == null) { return null; } return objectDescriptor.Type.GetProperty("Value").GetValue(objectDescriptor.Value); } public bool IsFsharpListType(Type t) { if (t.Namespace == "Microsoft.FSharp.Collections") { return t.Name == "FSharpList`1"; } return false; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { if (!IsFsharpListType(t)) { return null; } return t.Assembly.GetType("Microsoft.FSharp.Collections.ListModule").GetMethod("OfArray").MakeGenericMethod(itemsType) .Invoke(null, new object[1] { arr }); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal static class DictionaryExtensions { public static bool TryAdd<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] V>(this Dictionary dictionary, T key, V value) { if (dictionary.ContainsKey(key)) { return false; } dictionary.Add(key, value); return true; } public static TValue GetOrAdd<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TKey, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TValue, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] TArg>(this ConcurrentDictionary dictionary, TKey key, Func valueFactory, TArg arg) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } if (key == null) { throw new ArgumentNullException("key"); } if (valueFactory == null) { throw new ArgumentNullException("valueFactory"); } TValue value; do { if (dictionary.TryGetValue(key, out value)) { return value; } value = valueFactory(key, arg); } while (!dictionary.TryAdd(key, value)); return value; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { PropertyInfo propertyInfo = TryGetMemberExpression(propertyAccessor); if (propertyInfo == null) { throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } return propertyInfo; } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TMemberInfo>(LambdaExpression lambdaExpression) where TMemberInfo : MemberInfo { if (lambdaExpression.Parameters.Count != 1) { return null; } Expression expression = lambdaExpression.Body; if (expression is UnaryExpression unaryExpression) { if (unaryExpression.NodeType != ExpressionType.Convert) { return null; } expression = unaryExpression.Operand; } if (expression is MemberExpression memberExpression) { if (memberExpression.Expression != lambdaExpression.Parameters[0]) { return null; } return memberExpression.Member as TMemberInfo; } return null; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class FsharpHelper { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static IFsharpHelper Instance { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] set; } public static bool IsOptionType(Type t) { return Instance?.IsOptionType(t) ?? false; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static Type GetOptionUnderlyingType(Type t) { return Instance?.GetOptionUnderlyingType(t); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object GetValue(IObjectDescriptor objectDescriptor) { return Instance?.GetValue(objectDescriptor); } public static bool IsFsharpListType(Type t) { return Instance?.IsFsharpListType(t) ?? false; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return Instance?.CreateFsharpListFromArray(t, itemsType, arr); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <76b22c15-364d-460d-8f55-204a4246f2eb>GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] private readonly ICollection genericCollection; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public object this[int index] { get { throw new NotSupportedException(); } set { ((IList)genericCollection)[index] = (T)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] public object SyncRoot { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] get { throw new NotSupportedException(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <76b22c15-364d-460d-8f55-204a4246f2eb>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(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public void CopyTo(Array array, int index) { throw new NotSupportedException(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class GenericDictionaryToNonGenericAdapterNullable(2)] TValue> : IDictionary, ICollection, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object Value { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return enumerator.Current.Value; } } public object Current => Entry; public DictionaryEnumerator([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] IEnumerator> enumerator) { this.enumerator = enumerator; } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } private readonly IDictionary genericDictionary; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public ICollection Keys { get { throw new NotSupportedException(); } } public ICollection Values { get { throw new NotSupportedException(); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object this[object key] { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] get { throw new NotSupportedException(); } [param: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] set { genericDictionary[(TKey)key] = (TValue)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericDictionaryToNonGenericAdapter(IDictionary genericDictionary) { this.genericDictionary = genericDictionary ?? throw new ArgumentNullException("genericDictionary"); } public void Add(object key, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object value) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(object key) { throw new NotSupportedException(); } public IDictionaryEnumerator GetEnumerator() { return new DictionaryEnumerator(genericDictionary.GetEnumerator()); } public void Remove(object key) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IFsharpHelper { bool IsOptionType(Type t); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] Type GetOptionUnderlyingType(Type t); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object GetValue(IObjectDescriptor objectDescriptor); bool IsFsharpListType(Type t); [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] object CreateFsharpListFromArray(Type t, Type itemsType, Array arr); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <8708c545-30be-4eab-b3f7-c47674d5a48c>IOrderedDictionaryNullable(2)] TValue> : IDictionary, ICollection>, IEnumerable>, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair this[int index] { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] get; [param: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class NullFsharpHelper : IFsharpHelper { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object CreateFsharpListFromArray(Type t, Type itemsType, Array arr) { return null; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Type GetOptionUnderlyingType(Type t) { return null; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public object GetValue(IObjectDescriptor objectDescriptor) { return null; } public bool IsFsharpListType(Type t) { return false; } public bool IsOptionType(Type t) { return false; } } internal static class <2fe40640-6d5b-4ec9-8a66-6cf8dd9862d3>NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class OrderedDictionaryNullable(2)] TValue> : <8708c545-30be-4eab-b3f7-c47674d5a48c>IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class KeyCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TKey item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TKey item) { return orderedDictionary.dictionary.ContainsKey(item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class ValueCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TValue item) { return orderedDictionary.dictionary.ContainsValue(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); dictionary[key] = value; list[index] = new KeyValuePair(key, value); } else { Add(key, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] public KeyValuePair this[int index] { [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] get { return list[index]; } [param: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] set { list[index] = value; } } public OrderedDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public OrderedDictionary(IEqualityComparer comparer) { list = new List>(); dictionary = new Dictionary(comparer); this.comparer = comparer; } public void Add([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { if (!TryAdd(item)) { ThrowDuplicateKeyException(item.Key); } } public void Add(TKey key, TValue value) { if (!TryAdd(key, value)) { ThrowDuplicateKeyException(key); } } private static void ThrowDuplicateKeyException(TKey key) { throw new ArgumentException($"An item with the same key {key} has already been added."); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd(TKey key, TValue value) { if (DictionaryExtensions.TryAdd(dictionary, key, value)) { list.Add(new KeyValuePair(key, value)); return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryAdd([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { if (DictionaryExtensions.TryAdd(dictionary, item.Key, item.Value)) { list.Add(item); return true; } return false; } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 1, 0, 1, 1 })] public IEnumerator> GetEnumerator() { return list.GetEnumerator(); } public void Insert(int index, TKey key, TValue value) { dictionary.Add(key, value); list.Insert(index, new KeyValuePair(key, value)); } public bool Remove(TKey key) { if (dictionary.ContainsKey(key)) { int index = list.FindIndex(([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair kvp) => comparer.Equals(kvp.Key, key)); list.RemoveAt(index); if (!dictionary.Remove(key)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] KeyValuePair item) { return Remove(item.Key); } public void RemoveAt(int index) { TKey key = list[index].Key; dictionary.Remove(key); list.RemoveAt(index); } public bool TryGetValue(TKey key, [<41214478-6ad4-497d-9169-53b3d6fb78cb>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; } } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal static class <27f168b4-c572-465d-9c17-da9e40317f12>ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T>(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionaryNullable(2)] TValue>(this Dictionary dictionary) { return dictionary; } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } } namespace YamlDotNet.Core { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal readonly struct <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName : IEquatable<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName> { public static readonly <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Empty; private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private readonly string value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of an empty anchor"); public bool IsEmpty => value == null; public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>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(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName other) { return object.Equals(value, other.value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName left, <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName right) { return left.Equals(right); } public static bool operator !=(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName left, <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName right) { return !(left == right); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public static implicit operator <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName(string value) { if (value != null) { return new <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName(value); } return Empty; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class AnchorNotFoundException : <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException { public AnchorNotFoundException(string message) : base(message) { } public AnchorNotFoundException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : base(in start, in end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } [DebuggerStepThrough] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal readonly struct <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] TBuffer> where TBuffer : <9c2ab6dd-fc52-485f-8c49-54673c63a06d>ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public <412d8d1b-3958-4769-8923-70456defbc57>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 <887fda37-bd17-4d99-991f-3fcafc3d70a5>Constants { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] public static readonly <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective[] DefaultTagDirectives = new <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective[2] { new <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective("!", "!"), new <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective("!!", "tag:yaml.org,2002:") }; public const int MajorVersion = 1; public const int MinorVersion = 3; } [DebuggerStepThrough] internal sealed class <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor { public long Index { get; private set; } public long Line { get; private set; } public long LineOffset { get; private set; } public <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor() { Line = 1L; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor(<1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Mark() { return new <31f47b9d-8d18-481e-bdd8-c0be28798592>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; } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter : IEmitter { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private class AnchorData { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Anchor; public bool IsAlias; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class TagData { public string Handle; public string Suffix; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private class ScalarData { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] public string Value = string.Empty; public bool IsMultiline; public bool IsFlowPlainAllowed; public bool IsBlockPlainAllowed; public bool IsSingleQuotedAllowed; public bool IsBlockAllowed; public bool HasSingleQuotes; public ScalarStyle Style; } private static readonly Regex UriReplacer = new Regex("[^0-9A-Za-z_\\-;?@=$~\\\\\\)\\]/:&+,\\.\\*\\(\\[!]", RegexOptions.Compiled | RegexOptions.Singleline); private static readonly string[] NewLineSeparators = new string[3] { "\r\n", "\r", "\n" }; private readonly TextWriter output; private readonly bool outputUsesUnicodeEncoding; private readonly int maxSimpleKeyLength; private readonly bool isCanonical; private readonly bool skipAnchorName; private readonly int bestIndent; private readonly int bestWidth; private EmitterState state; private readonly Stack<EmitterState> states = new Stack<EmitterState>(); private readonly Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> events = new Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); 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 <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(TextWriter output) : this(output, <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings.Default) { } public <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(TextWriter output, int bestIndent) : this(output, bestIndent, int.MaxValue) { } public <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(TextWriter output, int bestIndent, int bestWidth) : this(output, bestIndent, bestWidth, isCanonical: false) { } public <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : this(output, new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(bestIndent, bestWidth, isCanonical, 1024)) { } public <444b1bb2-7c2f-4a15-8430-f4af9fa7ee33>Emitter(TextWriter output, <46a02486-5476-43e4-a617-652c44dc706f>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { <905c4171-2b55-4d94-bed7-421e597b1406>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 (<905c4171-2b55-4d94-bed7-421e597b1406>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { anchorData.Anchor = <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is AnchorAlias AnchorAlias) { AnalyzeAnchor(AnchorAlias.Value, isAlias: true); } else if (evt is <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent) { if (evt is Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent.Anchor, isAlias: false); if (!<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent.Tag.IsEmpty && (isCanonical || <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent.IsCanonical)) { AnalyzeTag(<5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent.Tag); } } } private void AnalyzeAnchor(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(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 { <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<StringLookAheadBuffer> <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2 = new <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<StringLookAheadBuffer>(bufferWrapper.Buffer); bool flag3 = true; bool flag4 = <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.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 (!<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.EndOfInput) { if (flag19) { if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check("#,[]{}&*!|>\"%@`'")) { flag = true; flag2 = true; flag9 = <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check('\''); flag17 |= <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check('\''); } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check(",?[]{}")) { flag = true; } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Check('\''); } if (!flag16 && !<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsPrintable()) { flag16 = true; } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsBreak()) { flag15 = true; } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsSpace()) { if (flag19) { flag5 = true; } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Buffer.Position >= <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsBreak()) { if (flag19) { flag6 = true; } if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Buffer.Position >= <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.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 = <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsWhiteBreakOrZero(); <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.Skip(1); if (!<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.EndOfInput) { flag4 = <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.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(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag) { tagData.Handle = tag.Value; foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { if (evt is <52cdc8a6-b039-4a15-9448-db7acc64bcd3>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 <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(<52cdc8a6-b039-4a15-9448-db7acc64bcd3>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { if (!(evt is <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart)) { throw new ArgumentException("Expected STREAM-START.", "evt"); } indent = -1; column = 0; isWhitespace = true; isIndentation = true; state = EmitterState.FirstDocumentStart; } private void EmitDocumentStart(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt, bool isFirst) { if (evt is DocumentStart DocumentStart) { bool flag = DocumentStart.IsImplicit && isFirst && !isCanonical; TagDirectiveCollection TagDirectiveCollection2 = NonDefaultTagsAmong(DocumentStart.Tags); if (!isFirst && !isDocumentEndWritten && (DocumentStart.Version != null || TagDirectiveCollection2.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 (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item in TagDirectiveCollection2) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective[] defaultTagDirectives = <887fda37-bd17-4d99-991f-3fcafc3d70a5>Constants.DefaultTagDirectives; foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective value in defaultTagDirectives) { AppendTagDirectiveTo(value, allowDuplicates: true, tagDirectives); } if (TagDirectiveCollection2.Count > 0) { flag = false; <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective[] defaultTagDirectives2 = <887fda37-bd17-4d99-991f-3fcafc3d70a5>Constants.DefaultTagDirectives; foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective value2 in defaultTagDirectives2) { AppendTagDirectiveTo(value2, allowDuplicates: true, TagDirectiveCollection2); } foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item2 in TagDirectiveCollection2) { 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 <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd)) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private static TagDirectiveCollection NonDefaultTagsAmong([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] IEnumerable<<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective> tagCollection) { TagDirectiveCollection TagDirectiveCollection2 = new TagDirectiveCollection(); if (tagCollection == null) { return TagDirectiveCollection2; } foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, TagDirectiveCollection2); } <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective[] defaultTagDirectives = <887fda37-bd17-4d99-991f-3fcafc3d70a5>Constants.DefaultTagDirectives; foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item in defaultTagDirectives) { TagDirectiveCollection2.Remove(item); } return TagDirectiveCollection2; } private static void AnalyzeVersionDirective(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(<905c4171-2b55-4d94-bed7-421e597b1406>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 <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { Scalar Scalar = (Scalar)evt; ScalarStyle ScalarStyle2 = Scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !Scalar.IsPlainImplicit && !Scalar.IsQuotedImplicit) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Neither tag nor isImplicit flags are specified."); } if (ScalarStyle2 == ScalarStyle.Any) { ScalarStyle2 = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { ScalarStyle2 = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { ScalarStyle2 = ScalarStyle.DoubleQuoted; } if (ScalarStyle2 == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { ScalarStyle2 = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { ScalarStyle2 = ScalarStyle.SingleQuoted; } if (flag && !Scalar.IsPlainImplicit) { ScalarStyle2 = ScalarStyle.SingleQuoted; } } if (ScalarStyle2 == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { ScalarStyle2 = ScalarStyle.DoubleQuoted; } if ((ScalarStyle2 == ScalarStyle.Literal || ScalarStyle2 == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { ScalarStyle2 = ScalarStyle.DoubleQuoted; } if (ScalarStyle2 == ScalarStyle.ForcePlain) { ScalarStyle2 = ScalarStyle.Plain; } scalarData.Style = ScalarStyle2; } 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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { ProcessAnchor(); ProcessTag(); <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart = (<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart)evt; if (flowLevel != 0 || isCanonical || <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart.Style == <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { ProcessAnchor(); ProcessTag(); <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart = (<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart)evt; if (flowLevel != 0 || isCanonical || <7231b36d-778a-425a-903e-21ac3ab9861d>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt) { if (evt is DocumentEnd DocumentEnd) { WriteIndent(); if (!DocumentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is <4ad8224b-02dd-4665-aacb-4525b1f4b912>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is <6ecca1c5-273b-4e95-842e-8d040b4ffb77>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(<905c4171-2b55-4d94-bed7-421e597b1406>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is <4ad8224b-02dd-4665-aacb-4525b1f4b912>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(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is <6ecca1c5-273b-4e95-842e-8d040b4ffb77>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(<905c4171-2b55-4d94-bed7-421e597b1406>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 (<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent @event in events) { num++; if (num == 2) { if (@event is 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(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private static int SafeStringLength(string value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure<<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart, <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd>(); } private bool CheckEmptyMapping() { return CheckEmptyStructure<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart, <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd>(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] private bool CheckEmptyStructure() where TStart : <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent where TEnd : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { if (events.Count < 2) { return false; } using Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>.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 { <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<StringLookAheadBuffer> <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2 = new <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<StringLookAheadBuffer>(bufferWrapper.Buffer); if (<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsSpace() || <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.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 || !<412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer2.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(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>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, [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] ([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(1)] Match match) => { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { builder.AppendFormat(CultureInfo.InvariantCulture, "%{0:X02}", b); } return builder.ToString(); } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } }); } private void Write(char value) { output.Write(value); column++; } private void Write(string value) { output.Write(value); column += value.Length; } private void WriteBreak(char breakCharacter = '\n') { if (breakCharacter == '\n') { output.WriteLine(); } else { output.Write(breakCharacter); } column = 0; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings { public static readonly <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings Default = new <46a02486-5476-43e4-a617-652c44dc706f>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 <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings() { } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public <46a02486-5476-43e4-a617-652c44dc706f>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 <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithBestIndent(int bestIndent) { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithBestWidth(int bestWidth) { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithNewLine(string newLine) { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings Canonical() { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithoutAnchorName() { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true, IndentSequences, NewLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithIndentedSequences() { return new <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine, UseUtf16SurrogatePairs); } public <46a02486-5476-43e4-a617-652c44dc706f>EmitterSettings WithUtf16SurrogatePairs() { return new <46a02486-5476-43e4-a617-652c44dc706f>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 } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class ForwardAnchorNotSupportedException : <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException { public ForwardAnchorNotSupportedException(string message) : base(message) { } public ForwardAnchorNotSupportedException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : base(in start, in end, message) { } public ForwardAnchorNotSupportedException(string message, Exception inner) : base(message, inner) { } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] internal static class <08becf84-efa3-4abf-869e-3e3d06f458f0>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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IEmitter { void Emit(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent @event); } internal interface <9c2ab6dd-fc52-485f-8c49-54673c63a06d>ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class InsertionQueue<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] T> : IEnumerable, IEnumerable { private const int DefaultInitialCapacity = 128; private T[] items; private int readPtr; private int writePtr; private int mask; private int count; public int Count => count; public int Capacity => items.Length; public InsertionQueue(int initialCapacity = 128) { if (initialCapacity <= 0) { throw new ArgumentOutOfRangeException("initialCapacity", "The initial capacity must be a positive number."); } if (!<2fe40640-6d5b-4ec9-8a66-6cf8dd9862d3>NumberExtensions.IsPowerOfTwo(initialCapacity)) { 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(); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] internal interface <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Current { get; } bool MoveNext(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] internal interface <2068457c-4d1c-473d-b107-dea5af731fe6>IScanner { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark CurrentPosition { get; } Token Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [DebuggerStepThrough] internal sealed class <9824c142-3dd4-46fb-a01c-09a4d772cbaa>LookAheadBuffer : <9c2ab6dd-fc52-485f-8c49-54673c63a06d>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 <9824c142-3dd4-46fb-a01c-09a4d772cbaa>LookAheadBuffer(TextReader input, int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); } if (!<2fe40640-6d5b-4ec9-8a66-6cf8dd9862d3>NumberExtensions.IsPowerOfTwo(capacity)) { 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 <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark : IEquatable<<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark>, IComparable<<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark>, IComparable { public static readonly <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Empty = new <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark(0L, 1L, 1L); public long Index { get; } public long Line { get; } public long Column { get; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>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; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { return Equals((<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark)(obj ?? ((object)Empty))); } public bool Equals(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark other) { if (Index == other.Index && Line == other.Line) { return Column == other.Column; } return false; } public override int GetHashCode() { return <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(Index.GetHashCode(), <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(Line.GetHashCode(), Column.GetHashCode())); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public int CompareTo(object obj) { return CompareTo((<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark)(obj ?? ((object)Empty))); } public int CompareTo(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark other) { int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } public static bool operator ==(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return left.Equals(right); } public static bool operator !=(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return !(left == right); } public static bool operator <(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return left.CompareTo(right) < 0; } public static bool operator <=(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return left.CompareTo(right) <= 0; } public static bool operator >(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return left.CompareTo(right) > 0; } public static bool operator >=(<31f47b9d-8d18-481e-bdd8-c0be28798592>Mark left, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark right) { return left.CompareTo(right) >= 0; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <33aa3462-611c-4e66-8e55-df86e8908de6>MaximumRecursionLevelReachedException : <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException { public <33aa3462-611c-4e66-8e55-df86e8908de6>MaximumRecursionLevelReachedException(string message) : base(message) { } public <33aa3462-611c-4e66-8e55-df86e8908de6>MaximumRecursionLevelReachedException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : base(in start, in end, message) { } public <33aa3462-611c-4e66-8e55-df86e8908de6>MaximumRecursionLevelReachedException(string message, Exception inner) : base(message, inner) { } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class MergingParser : <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private sealed class ParsingEventCollection : IEnumerableParsingEvent>>, IEnumerable { private readonly LinkedList<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> events; private readonly HashSetParsingEvent>> deleted; private readonly Dictionary<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>> references; public ParsingEventCollection() { events = new LinkedList<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); deleted = new HashSetParsingEvent>>(); references = new Dictionary<<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName, LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>>(); } public void AddAfter(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node, IEnumerable<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> items) { foreach (<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent item in items) { node = events.AddAfter(node, item); } } public void Add(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent item) { LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node = events.AddLast(item); AddReference(item, node); } public void MarkDeleted(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { deleted.Add(node); } public bool IsDeleted(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { return deleted.Contains(node); } public void CleanMarked() { foreach (LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> item in deleted) { events.Remove(item); } } public IEnumerableParsingEvent>> FromAnchor(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor) { LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> next = references[anchor].Next; return Enumerate(next); } public IEnumeratorParsingEvent>> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private static IEnumerableParsingEvent>> Enumerate([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { while (node != null) { yield return node; node = node.Next; } } private void AddReference(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent item, LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { if (item is <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart { Anchor: { IsEmpty: false } anchor }) { references[anchor] = node; } } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private sealed class ParsingEventCloner : <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent clonedEvent; public <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Clone(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent e) { e.Accept(this); if (clonedEvent == null) { throw new InvalidOperationException($"Could not clone event of type '{e.Type}'"); } return clonedEvent; } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(AnchorAlias e) { clonedEvent = new AnchorAlias(e.Value, e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart e) { throw new NotSupportedException(); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd e) { throw new NotSupportedException(); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(DocumentStart e) { throw new NotSupportedException(); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(DocumentEnd e) { throw new NotSupportedException(); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(Scalar e) { clonedEvent = new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart e) { clonedEvent = new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd e) { clonedEvent = new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd(e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart e) { clonedEvent = new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd e) { clonedEvent = new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd(e.Start, e.End); } void <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor.Visit(<52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment e) { throw new NotSupportedException(); } } private readonly ParsingEventCollection events; private readonly <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser innerParser; private IEnumeratorParsingEvent>> iterator; private bool merged; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Current { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get { return iterator.Current?.Value; } } public MergingParser(<335b54f3-fbf8-46c4-bfc9-8467281b299b>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<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> @event in events) { if (IsMergeToken(@event)) { events.MarkDeleted(@event); if (!HandleMerge(@event.Next)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(@event.Value.Start, @event.Value.End, "Unrecognized merge key pattern"); } } } } private bool HandleMerge([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { if (node == null) { return false; } if (node.Value is AnchorAlias anchorAlias) { return HandleAnchorAlias(node, node, anchorAlias); } if (node.Value is <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart) { return HandleSequence(node); } return false; } private bool HandleMergeSequence(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> sequenceStart, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { if (node == null) { return false; } if (node.Value is AnchorAlias anchorAlias) { return HandleAnchorAlias(sequenceStart, node, anchorAlias); } if (node.Value is <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart) { return HandleSequence(node); } return false; } private static bool IsMergeToken(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { if (node.Value is Scalar Scalar) { return Scalar.Value == "<<"; } return false; } private bool HandleAnchorAlias(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node, LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> anchorNode, AnchorAlias anchorAlias) { IEnumerable<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> mappingEvents = GetMappingEvents(anchorAlias.Value); events.AddAfter(node, mappingEvents); events.MarkDeleted(anchorNode); return true; } private bool HandleSequence(LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> node) { events.MarkDeleted(node); LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> linkedListNode = node; while (linkedListNode != null) { if (linkedListNode.Value is <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> GetMappingEvents(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor) { ParsingEventCloner parsingEventCloner = new ParsingEventCloner(); int nesting = 0; return (from e in events.FromAnchor(anchor) where !events.IsDeleted(e) select e.Value).TakeWhile([<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(0)] (<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent e) => (nesting += e.NestingIncrease) >= 0).Select(parsingEventCloner.Clone); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class Parser : <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] private class EventQueue { private readonly Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> highPriorityEvents = new Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); private readonly Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent> normalPriorityEvents = new Queue<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); public int Count => highPriorityEvents.Count + normalPriorityEvents.Count; public void Enqueue(<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent @event) { EventType type = @event.Type; if (type == EventType.StreamStart || type == EventType.DocumentStart) { highPriorityEvents.Enqueue(@event); } else { normalPriorityEvents.Enqueue(@event); } } public <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Dequeue() { if (highPriorityEvents.Count <= 0) { return normalPriorityEvents.Dequeue(); } return highPriorityEvents.Dequeue(); } } private readonly Stack<<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState> states = new Stack<<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState>(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState state; private readonly <2068457c-4d1c-473d-b107-dea5af731fe6>IScanner scanner; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private Token currentToken; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective version; private readonly EventQueue pendingEvents = new EventQueue(); [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent Current { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private set; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private Token GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (!(currentToken is Comment Comment)) { break; } pendingEvents.Enqueue(new <52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment(Comment.Value, Comment.IsInline, Comment.Start, Comment.End)); scanner.ConsumeCurrent(); } } return currentToken; } public Parser(TextReader input) : this(new <81d6fcf7-841a-4aed-8411-c66b57343746>Scanner(input)) { } public Parser(<2068457c-4d1c-473d-b107-dea5af731fe6>IScanner scanner) { this.scanner = scanner; } public bool MoveNext() { if (state == <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.StreamEnd) { Current = null; return false; } if (pendingEvents.Count == 0) { pendingEvents.Enqueue(StateMachine()); } Current = pendingEvents.Dequeue(); return true; } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent StateMachine() { return state switch { <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.StreamStart => ParseStreamStart(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.ImplicitDocumentStart => ParseDocumentStart(isImplicit: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentStart => ParseDocumentStart(isImplicit: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentContent => ParseDocumentContent(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentEnd => ParseDocumentEnd(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockNode => ParseNode(isBlock: true, isIndentlessSequence: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockNodeOrIndentlessSequence => ParseNode(isBlock: true, isIndentlessSequence: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowNode => ParseNode(isBlock: false, isIndentlessSequence: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockSequenceFirstEntry => ParseBlockSequenceEntry(isFirst: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockSequenceEntry => ParseBlockSequenceEntry(isFirst: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.IndentlessSequenceEntry => ParseIndentlessSequenceEntry(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingFirstKey => ParseBlockMappingKey(isFirst: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingKey => ParseBlockMappingKey(isFirst: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingValue => ParseBlockMappingValue(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceFirstEntry => ParseFlowSequenceEntry(isFirst: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntry => ParseFlowSequenceEntry(isFirst: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingKey => ParseFlowSequenceEntryMappingKey(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingValue => ParseFlowSequenceEntryMappingValue(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingEnd => ParseFlowSequenceEntryMappingEnd(), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingFirstKey => ParseFlowMappingKey(isFirst: true), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingKey => ParseFlowMappingKey(isFirst: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingValue => ParseFlowMappingValue(isEmpty: false), <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingEmptyValue => ParseFlowMappingValue(isEmpty: true), _ => throw new InvalidOperationException(), }; } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } private <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart ParseStreamStart() { Token Token = GetCurrentToken(); if (!(Token is StreamStart StreamStart)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "Did not find expected ."); } Skip(); state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.ImplicitDocumentStart; return new <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart(StreamStart.Start, StreamStart.End); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token Token = GetCurrentToken(); if (!isImplicit) { while (Token is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd) { Skip(); Token = GetCurrentToken(); } } if (Token == null) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (Token is Scalar && (state == <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.ImplicitDocumentStart || state == <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(Token is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective) && !(Token is <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective) && !(Token is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart) && !(Token is <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd) && !(Token is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd)) || Token is <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentEnd); state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockNode; return new DocumentStart(null, tags, isImplicit: true, Token.Start, Token.End); } if (!(Token is <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd) && !(Token is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd)) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = Token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective = ProcessDirectives(tags2); Token = GetCurrentToken() ?? throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(Token is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token.Start, Token.End, "Did not find expected ."); } states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentEnd); state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentContent; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end = Token.End; Skip(); return new DocumentStart(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective, tags2, isImplicit: false, start, end); } if (Token is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd) { Skip(); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.StreamEnd; Token = GetCurrentToken() ?? throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException("Reached the end of the stream while parsing a document start"); <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd result = new <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd(Token.Start, Token.End); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective result = null; while (true) { if (GetCurrentToken() is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective) { if (version != null) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.Start, <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.End, "Found duplicate %YAML directive."); } if (<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.Version.Major != 1 || <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.Version.Minor > 3) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.Start, <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective.End, "Found incompatible YAML document."); } result = (version = <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective); flag = true; } else { if (!(GetCurrentToken() is <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective)) { break; } if (tags.Contains(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective.Handle)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective.Start, <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective.End, "Found duplicate %TAG directive."); } tags.Add(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective); flag = true; } Skip(); } if (GetCurrentToken() is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart && version == null) { version = new <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, <887fda37-bd17-4d99-991f-3fcafc3d70a5>Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable<<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective> source) { foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective || GetCurrentToken() is <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective || GetCurrentToken() is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart || GetCurrentToken() is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd || GetCurrentToken() is <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static Scalar ProcessEmptyScalar(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark position) { return new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, string.Empty, ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false, position, position); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { if (GetCurrentToken() is <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error { Start: var start } <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in start, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.End, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.Value); } Token Token = GetCurrentToken() ?? throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException("Reached the end of the stream while parsing a node"); if (Token is <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias) { state = states.Pop(); <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent result = new AnchorAlias(<087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.Value, <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.Start, <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.End); Skip(); return result; } <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start2 = Token.Start; <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor = <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty; <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag = <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty; Anchor Anchor = null; <70b1222a-a83c-4054-93f5-5d95220f5164>Tag <70b1222a-a83c-4054-93f5-5d95220f5164>Tag = null; while (true) { if (anchor.IsEmpty && Token is Anchor Anchor2) { Anchor = Anchor2; anchor = Anchor2.Value; Skip(); } else { if (!tag.IsEmpty || !(Token is <70b1222a-a83c-4054-93f5-5d95220f5164>Tag <70b1222a-a83c-4054-93f5-5d95220f5164>Tag2)) { if (Token is Anchor { Start: var start3 } Anchor3) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in start3, Anchor3.End, "While parsing a node, found more than one anchor."); } if (Token is <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias { Start: var start4 } <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias2) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in start4, <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias2.End, "While parsing a node, did not find expected token."); } if (!(Token is <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error2)) { break; } if (<70b1222a-a83c-4054-93f5-5d95220f5164>Tag != null && Anchor != null && !anchor.IsEmpty) { return new Scalar(anchor, default(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName), string.Empty, ScalarStyle.Any, isPlainImplicit: false, isQuotedImplicit: false, Anchor.Start, Anchor.End); } throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error2.Start, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error2.End, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error2.Value); } <70b1222a-a83c-4054-93f5-5d95220f5164>Tag = <70b1222a-a83c-4054-93f5-5d95220f5164>Tag2; if (string.IsNullOrEmpty(<70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Handle)) { tag = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName(<70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Suffix); } else { if (!tagDirectives.Contains(<70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Handle)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Start, <70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.End, "While parsing a node, found undefined tag handle."); } tag = new <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName(tagDirectives[<70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Handle].Prefix + <70b1222a-a83c-4054-93f5-5d95220f5164>Tag2.Suffix); } Skip(); } Token = GetCurrentToken() ?? throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException("Reached the end of the stream while parsing a node"); } bool isEmpty = tag.IsEmpty; if (isIndentlessSequence && GetCurrentToken() is <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.IndentlessSequenceEntry; return new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(anchor, tag, isEmpty, <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle.Block, start2, Token.End); } if (Token is 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(); <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent result2 = new 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 <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error) { <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error3 = currentToken as <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error; throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(<00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error3.Start, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error3.End, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error3.Value); } } if (state == <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingKey && !(scanner.Current is FlowMappingEnd) && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(currentToken.Start, currentToken.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (Token is <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceFirstEntry; return new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(anchor, tag, isEmpty, <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle.Flow, start2, <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart.End); } if (Token is <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingFirstKey; return new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start2, <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart.End); } if (isBlock) { if (Token is <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockSequenceFirstEntry; return new <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(anchor, tag, isEmpty, <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle.Block, start2, <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart.End); } if (Token is <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingFirstKey; return new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start2, <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart.End); } } if (!anchor.IsEmpty || !tag.IsEmpty) { state = states.Pop(); return new Scalar(anchor, tag, string.Empty, ScalarStyle.Plain, isEmpty, isQuotedImplicit: false, start2, Token.End); } throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token.Start, Token.End, "While parsing a node, did not find expected node content."); } private DocumentEnd ParseDocumentEnd() { Token Token = GetCurrentToken() ?? throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = Token.Start; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end = start; if (Token is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd) { end = Token.End; Skip(); isImplicit = false; } else if (!(currentToken is <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd) && !(currentToken is <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart) && !(currentToken is <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd) && !(currentToken is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective) && (!(Current is Scalar) || !(currentToken is <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error))) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in start, in end, "Did not find expected ."); } if (version != null && version.Version.Major == 1 && version.Version.Minor > 1) { version = null; } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.DocumentStart; return new DocumentEnd(isImplicit, start, end); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token Token = GetCurrentToken(); if (Token is <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry { End: var position }) { Skip(); Token = GetCurrentToken(); if (!(Token is <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry) && !(Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockSequenceEntry; return ProcessEmptyScalar(in position); } if (Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd) { state = states.Pop(); <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent result = new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd(<48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd.Start, <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd.End); Skip(); return result; } throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "While parsing a block collection, did not find expected '-' indicator."); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseIndentlessSequenceEntry() { Token Token = GetCurrentToken(); if (Token is <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry { End: var position }) { Skip(); Token = GetCurrentToken(); if (!(Token is <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry) && !(Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key) && !(Token is Value) && !(Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.IndentlessSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(in position); } state = states.Pop(); return new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token Token = GetCurrentToken(); if (Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key { End: var position }) { Skip(); Token = GetCurrentToken(); if (!(Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key) && !(Token is Value) && !(Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingValue); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingValue; return ProcessEmptyScalar(in position); } if (Token is Value Value) { Skip(); return ProcessEmptyScalar(Value.End); } if (Token is <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias) { Skip(); return new AnchorAlias(<087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.Value, <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.Start, <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias.End); } if (Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd) { state = states.Pop(); <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent result = new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd(<48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd.Start, <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd.End); Skip(); return result; } if (GetCurrentToken() is <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error { Start: var start } <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.End, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.Value); } throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "While parsing a block mapping, did not find expected key."); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseBlockMappingValue() { Token Token = GetCurrentToken(); if (Token is Value { End: var position }) { Skip(); Token = GetCurrentToken(); if (!(Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key) && !(Token is Value) && !(Token is <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingKey); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingKey; return ProcessEmptyScalar(in position); } if (Token is <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error { Start: var start } <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in start, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.End, <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error.Value); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.BlockMappingKey; return ProcessEmptyScalar(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token Token = GetCurrentToken(); <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent result; if (!(Token is <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd)) { if (!isFirst) { if (!(Token is FlowEntry)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); Token = GetCurrentToken(); } if (Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key) { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingKey; result = new <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(Token is <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); result = new <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); Skip(); return result; } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseFlowSequenceEntryMappingKey() { Token Token = GetCurrentToken(); if (!(Token is Value) && !(Token is FlowEntry) && !(Token is <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark position = Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty; Skip(); state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(in position); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseFlowSequenceEntryMappingValue() { Token Token = GetCurrentToken(); if (Token is Value) { Skip(); Token = GetCurrentToken(); if (!(Token is FlowEntry) && !(Token is <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } private <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd ParseFlowSequenceEntryMappingEnd() { state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowSequenceEntry; Token Token = GetCurrentToken(); return new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } private <905c4171-2b55-4d94-bed7-421e597b1406>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 Scalar)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (Token is <6c627cc6-567f-4f6f-aa87-38251a178370>Key) { Skip(); Token = GetCurrentToken(); if (!(Token is Value) && !(Token is FlowEntry) && !(Token is FlowMappingEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingValue; return ProcessEmptyScalar(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } if (Token is Scalar) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } if (!(Token is FlowMappingEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingEmptyValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); Skip(); return new <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, Token?.End ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } private <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent ParseFlowMappingValue(bool isEmpty) { Token Token = GetCurrentToken(); if (!isEmpty && Token is Value) { Skip(); Token = GetCurrentToken(); if (!(Token is FlowEntry) && !(Token is FlowMappingEnd)) { states.Push(<034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingKey); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = <034f49ca-f509-4ee2-94dc-652d40013aa9>ParserState.FlowMappingKey; if (!isEmpty && Token is Scalar Scalar) { Skip(); return new Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, Scalar.Value, Scalar.Style, isPlainImplicit: false, isQuotedImplicit: false, Token.Start, Scalar.End); } return ProcessEmptyScalar(Token?.Start ?? <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal static class <537e7b71-d023-43f7-a1d8-e6565f654af6>ParserExtensions { public static T Consume<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(false)] out T @event) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { if (parser.Accept(out @event)) { parser.MoveNext(); return true; } return false; } public static T Require<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { if (!parser.Accept(out var @event)) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; if (current == null) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException("Expected '" + typeof(T).Name + "', got nothing."); } throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(current.Start, current.End, $"Expected '{typeof(T).Name}', got '{current.GetType().Name}' (at {current.Start})."); } return @event; } public static bool Accept<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, [<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(false)] out T @event) where T : <905c4171-2b55-4d94-bed7-421e597b1406>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 <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) { int num = 0; do { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent = parser.Consume<<905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent>(); num += <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent.NestingIncrease; } while (num > 0); } [Obsolete("Please use Consume() instead")] public static T Expect<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: MaybeNull] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static T Allow<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { if (!parser.TryConsume(out var @event)) { return null; } return @event; } [Obsolete("Please use Accept(out var evt) instead")] [return: MaybeNull] [return: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public static T Peek<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>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<[<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] T>(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser) where T : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { T @event; return parser.Accept(out @event); } public static bool TryFindMappingEntry(this <335b54f3-fbf8-46c4-bfc9-8467281b299b>IParser parser, Func<Scalar, bool> selector, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)][<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(false)] out Scalar key, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)][<41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhen(false)] out <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent value) { if (parser.TryConsume<<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart>(out var _)) { while (parser.Current != null) { <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent current = parser.Current; if (!(current is Scalar Scalar)) { if (current is <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart || current is <326fc025-c42e-43e7-a3d6-229d7b950ee5>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 <034f49ca-f509-4ee2-94dc-652d40013aa9>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 <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel { private int current; public int Maximum { get; } public <4a23a725-ca6f-4e37-93f7-f4b2a2c3b2b2>RecursionLevel(int maximum) { Maximum = maximum; } public void Increment() { if (!TryIncrement()) { throw new <33aa3462-611c-4e66-8e55-df86e8908de6>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 } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <81d6fcf7-841a-4aed-8411-c66b57343746>Scanner : <2068457c-4d1c-473d-b107-dea5af731fe6>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<Token> tokens = new InsertionQueue<Token>(); private readonly Stack<<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey> simpleKeys = new Stack<<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey>(); [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] private readonly <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<<9824c142-3dd4-46fb-a01c-09a4d772cbaa>LookAheadBuffer> analyzer; private readonly <1e558c2a-1569-420d-9e91-7e96443fa87b>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; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private Token previous; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private Anchor previousAnchor; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private Scalar lastScalar; private readonly int maxKeySize; private static readonly byte[] EmptyBytes = Array.Empty(); public bool SkipComments { get; private set; } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] [field: <6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] public Token Current { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] get; [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private set; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <81d6fcf7-841a-4aed-8411-c66b57343746>Scanner(TextReader input, bool skipComments = true) : this(input, skipComments, 1024) { } public <81d6fcf7-841a-4aed-8411-c66b57343746>Scanner(TextReader input, bool skipComments, int maxKeySize) { analyzer = new <412d8d1b-3958-4769-8923-70456defbc57>CharacterAnalyzer<<9824c142-3dd4-46fb-a01c-09a4d772cbaa>LookAheadBuffer>(new <9824c142-3dd4-46fb-a01c-09a4d772cbaa>LookAheadBuffer(input, 1024)); cursor = new <1e558c2a-1569-420d-9e91-7e96443fa87b>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 (<6cd809d3-1033-4a2c-aa14-4232b78a09cc>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 (<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + maxKeySize < cursor.Index)) { if (simpleKey.IsRequired) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2 = cursor.Mark(); tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning a simple key, could not find expected ':'.", <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2)); } 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 <00c9ac2e-5a97-4348-b32f-5db18347c3e1>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) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2 = cursor.Mark(); tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning plain scalar, found a comment between adjacent scalars.", <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2)); } 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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (!analyzer.IsWhiteBreakOrZero()) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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; } <31f47b9d-8d18-481e-bdd8-c0be28798592>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 StreamStart); tokens.Enqueue(new Comment(builder.ToString(), isInline, start, cursor.Mark())); } } finally { ((IDisposable)builderWrapper/*cast due to .constrained prefix*/).Dispose(); } } private void FetchStreamStart() { simpleKeys.Push(new <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); tokens.Enqueue(new StreamStart(in start, in start)); } private void UnrollIndent(long column) { if (flowLevel == 0) { while (indent > column) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); tokens.Enqueue(new <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd(in start, in start)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); tokens.Enqueue(new <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1L); RemoveSimpleKey(); simpleKeyAllowed = false; Token Token = ScanDirective(); if (Token != null) { tokens.Enqueue(Token); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] private Token ScanDirective() { <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart) && !(previous is StreamStart) && !(previous is <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd)) { throw new <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { tokens.Enqueue(new <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart(in start, cursor.Mark())); return; } Token Token = null; while (!analyzer.EndOfInput && !analyzer.IsBreak() && !analyzer.Check('#')) { if (!analyzer.IsWhite()) { Token = new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning a document end, found invalid content after '...' marker.", start, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd(in start, in start)); if (Token != null) { tokens.Enqueue(Token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); Token item = ((!isSequenceToken) ? ((Token)new <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart(in start, in start)) : ((Token)new <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart(in start, in start))); tokens.Enqueue(item); startFlowCollectionFetched = true; } private void IncreaseFlowLevel() { simpleKeys.Push(new <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); Token Token = null; Token item; if (isSequenceToken) { if (analyzer.Check('#')) { Token = new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning a flow sequence end, found invalid comment after ']'.", start, start); } item = new <8594577e-2844-4429-bdf4-407d1f4a0799>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; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end = cursor.Mark(); if (analyzer.Check('#')) { tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>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 <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(previousAnchor.Start, previousAnchor.End, "Anchor before sequence entry on same line is not allowed."); } <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2 = cursor.Mark(); tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("Block sequence entries are not allowed in this context.", <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2)); } RollIndent(cursor.LineOffset, -1, isSequence: true, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = true; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry(in start, cursor.Mark())); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start2 = cursor.Mark(); Skip(); tokens.Enqueue(new <6c627cc6-567f-4f6f-aa87-38251a178370>Key(in start2, cursor.Mark())); } private void FetchValue() { <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2 = simpleKeys.Peek(); if (<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsPossible) { tokens.Insert(<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.TokenNumber - tokensParsed, new <6c627cc6-567f-4f6f-aa87-38251a178370>Key(<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark, <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark)); RollIndent(<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.LineOffset, <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.TokenNumber, isSequence: false, <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark); <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2 = cursor.Mark(); tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("Mapping values are not allowed in this context.", <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0L && <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.LineOffset == 0L) { tokens.Insert(tokens.Count, new <6c627cc6-567f-4f6f-aa87-38251a178370>Key(<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark, <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark)); flag = false; } } simpleKeyAllowed = flag; } <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new Value(in start, cursor.Mark())); } private void RollIndent(long column, int number, bool isSequence, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart(in position, in position)) : ((Token)new <80f83767-52a1-4b67-997b-8ba434e4f305>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) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); bool flag = false; if (isAlias) { <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2 = simpleKeys.Peek(); flag = <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsRequired && <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning an anchor or alias, found value containing disallowed: []{},"); } <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value = new <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName(builder.ToString()); if (isAlias) { return new <087597a3-a3ca-4cca-b360-19a36474e009>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 <70b1222a-a83c-4054-93f5-5d95220f5164>Tag ScanTag() { <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, did not find expected whitespace, comma or line break."); } return new <70b1222a-a83c-4054-93f5-5d95220f5164>Tag(text, text2, start, cursor.Mark()); } private void FetchBlockScalar(bool isLiteral) { SaveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private 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; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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; } } <31f47b9d-8d18-481e-bdd8-c0be28798592>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 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 <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>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 <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>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; Scalar item = ScanFlowScalar(isSingleQuoted); tokens.Enqueue(item); lastScalar = item; if (!isSingleQuoted && analyzer.Check('#')) { <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2 = cursor.Mark(); tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark2)); } } private Scalar ScanFlowScalar(bool isSingleQuoted) { <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 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; Scalar item = (lastScalar = ScanPlainScalar(ref isMultiline)); if (isMultiline && analyzer.Check(':') && flowLevel == 0 && indent < cursor.LineOffset) { tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error("While scanning a multiline plain scalar, found invalid mapping.", cursor.Mark(), cursor.Mark())); } tokens.Enqueue(item); } private 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; <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start = cursor.Mark(); <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end = start; <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2 = simpleKeys.Peek(); while (!IsDocumentIndicator()) { if (analyzer.Check('#')) { if (indent < 0 && flowLevel == 0) { plainScalarFollowedByComment = true; } break; } bool flag2 = analyzer.Check('*') && (!<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsPossible || !<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsRequired); while (!analyzer.IsWhiteBreakOrZero()) { if ((analyzer.Check(':') && !flag2 && (analyzer.IsWhiteBreakOrZero(1) || (flowLevel > 0 && analyzer.Check(',', 1)))) || (flowLevel > 0 && analyzer.Check(",[]{}"))) { if (flowLevel == 0 && !<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsPossible) { tokens.Enqueue(new <00c9ac2e-5a97-4348-b32f-5db18347c3e1>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 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() { <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2 = simpleKeys.Peek(); if (<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsPossible && <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.IsRequired) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(<6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark, <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.Mark, "While scanning a simple key, could not find expected ':'."); } <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey2.MarkAsImpossible(); } private string ScanDirectiveName(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, could not find expected directive name."); } if (analyzer.EndOfInput) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a directive, found unexpected end of stream."); } if (!analyzer.IsWhiteBreakOrZero()) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective ScanVersionDirectiveValue(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(in start); if (!analyzer.Check('.')) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective(new Version(major, minor), start, start); } private <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective ScanTagDirectiveValue(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a %TAG directive, did not find expected whitespace or line break."); } return new <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective(handle, prefix, start, start); } private string ScanTagUri([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] string head, <31f47b9d-8d18-481e-bdd8-c0be28798592>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in start, cursor.Mark(), "While scanning a tag, found an incorrect UTF-8 sequence."); } return text; } private string ScanTagHandle(bool isDirective, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { if (!analyzer.Check('!')) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { throw new <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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 <80084179-937e-4fcb-bee2-c5f8fc8e99c3>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) { <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey item = new <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey(isRequired, tokensParsed + tokens.Count, cursor); RemoveSimpleKey(); simpleKeys.Pop(); simpleKeys.Push(item); } } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException : <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException { public <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(string message) : base(message) { } public <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : base(in start, in end, message) { } public <9eb71bf1-1c50-4e6e-9e92-cc08d31074cc>SemanticErrorException(string message, Exception inner) : base(message, inner) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey { private readonly <1e558c2a-1569-420d-9e91-7e96443fa87b>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 <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey() { cursor = new <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor(); } public <6cd809d3-1033-4a2c-aa14-4232b78a09cc>SimpleKey(bool isRequired, int tokenNumber, <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new <1e558c2a-1569-420d-9e91-7e96443fa87b>Cursor(cursor); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class StringLookAheadBuffer : <9c2ab6dd-fc52-485f-8c49-54673c63a06d>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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException : <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException { public <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(string message) : base(message) { } public <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : base(in start, in end, message) { } public <80084179-937e-4fcb-bee2-c5f8fc8e99c3>SyntaxErrorException(string message, Exception inner) : base(message, inner) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1, 1 })] internal sealed class TagDirectiveCollection : KeyedCollectionTagDirective> { public TagDirectiveCollection() { } public TagDirectiveCollection(IEnumerable<<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective> tagDirectives) { foreach (<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective tagDirective in tagDirectives) { Add(tagDirective); } } protected override string GetKeyForItem(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective item) { return item.Handle; } public new bool Contains(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective directive) { return Contains(GetKeyForItem(directive)); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal readonly struct <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName : IEquatable<<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName> { public static readonly <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Empty; [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private readonly string value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of a non-specific tag"); public bool IsEmpty => value == null; public bool IsNonSpecific { get { if (!IsEmpty) { if (!(value == "!")) { return value == "?"; } return true; } return false; } } public bool IsLocal { get { if (!IsEmpty) { return Value[0] == '!'; } return false; } } public bool IsGlobal { get { if (!IsEmpty) { return !IsLocal; } return false; } } public <763b3306-75ef-49cf-b5e4-c84545a2932c>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(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName other) { return object.Equals(value, other.value); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName left, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName right) { return left.Equals(right); } public static bool operator !=(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName left, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName right) { return !(left == right); } public static bool operator ==(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName left, string right) { return object.Equals(left.value, right); } public static bool operator !=(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName left, string right) { return !(left == right); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public static implicit operator <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName(string value) { if (value != null) { return new <763b3306-75ef-49cf-b5e4-c84545a2932c>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; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is Version Version2 && Major == Version2.Major) { return Minor == Version2.Minor; } return false; } public override int GetHashCode() { return <08becf84-efa3-4abf-869e-3e3d06f458f0>HashCode.CombineHashCodes(Major.GetHashCode(), Minor.GetHashCode()); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException : Exception { public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Start { get; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark End { get; } public <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(string message) : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, message) { } public <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message) : this(in start, in end, message, null) { } public <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, string message, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] Exception innerException) : base(message, innerException) { Start = start; End = end; } public <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(string message, Exception inner) : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, message, inner) { } public override string ToString() { return $"({Start}) - ({End}): {Message}"; } } } namespace YamlDotNet.Core.Tokens { internal class Anchor : Token { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Value { get; } public Anchor(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value) : this(value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Anchor(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias : Token { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Value { get; } public <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value) : this(value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <087597a3-a3ca-4cca-b360-19a36474e009>AnchorAlias(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd : Token { public <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <48672323-7f57-4300-a87f-6eb2982530d2>BlockEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry : Token { public <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <10a62872-ccc0-4cc8-a820-73ff24d536ef>BlockEntry(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart : Token { public <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <3336acff-78cf-4279-b602-ab6102d3decf>BlockMappingStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart : Token { public <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <80f83767-52a1-4b67-997b-8ba434e4f305>BlockSequenceStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class Comment : Token { public string Value { get; } public bool IsInline { get; } public Comment(string value, bool isInline) : this(value, isInline, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Comment(string value, bool isInline, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd : Token { public <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <4b9f649c-5db6-4b56-9de9-681725583239>DocumentEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart : Token { public <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <2a3fd450-646b-4a4f-b6d6-058d0608d3f2>DocumentStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error : Token { public string Value { get; } public <00c9ac2e-5a97-4348-b32f-5db18347c3e1>Error(string value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public FlowEntry(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public FlowMappingEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart : Token { public <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <3928fb53-8b2c-4950-a5b7-1e898531f6db>FlowMappingStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd : Token { public <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <8594577e-2844-4429-bdf4-407d1f4a0799>FlowSequenceEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart : Token { public <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <28e9c2f5-e2b2-43d5-85b2-6074b053f7db>FlowSequenceStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class <6c627cc6-567f-4f6f-aa87-38251a178370>Key : Token { public <6c627cc6-567f-4f6f-aa87-38251a178370>Key() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <6c627cc6-567f-4f6f-aa87-38251a178370>Key(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class Scalar : Token { public bool IsKey { get; set; } public string Value { get; } public ScalarStyle Style { get; } public Scalar(string value) : this(value, ScalarStyle.Any) { } public Scalar(string value, ScalarStyle style) : this(value, style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Scalar(string value, ScalarStyle style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd : Token { public <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <2f5ee72c-e274-44da-a467-5924fd9397a4>StreamEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public StreamStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <70b1222a-a83c-4054-93f5-5d95220f5164>Tag : Token { public string Handle { get; } public string Suffix { get; } public <70b1222a-a83c-4054-93f5-5d95220f5164>Tag(string handle, string suffix) : this(handle, suffix, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <70b1222a-a83c-4054-93f5-5d95220f5164>Tag(string handle, string suffix, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Handle = handle ?? throw new ArgumentNullException("handle"); Suffix = suffix ?? throw new ArgumentNullException("suffix"); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal class <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective : Token { private static readonly Regex TagHandlePattern = new Regex("^!([0-9A-Za-z_\\-]*!)?$", RegexOptions.Compiled); public string Handle { get; } public string Prefix { get; } public <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective(string handle, string prefix) : this(handle, prefix, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective(string handle, string prefix, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>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; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective <976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective2 && Handle.Equals(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective2.Handle)) { return Prefix.Equals(<976409c6-5787-4fe8-b4c1-5f2a5c3c621b>TagDirective2.Prefix); } return false; } public override int GetHashCode() { return Handle.GetHashCode() ^ Prefix.GetHashCode(); } public override string ToString() { return Handle + " => " + Prefix; } } internal abstract class Token { public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Start { get; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark End { get; } protected Token(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) { Start = start; End = end; } } internal sealed class Value : Token { public Value() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Value(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective : Token { public Version Version { get; } public <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective(Version version) : this(version, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective(Version version, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Version = version; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] public override bool Equals(object obj) { if (obj is <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective2) { return Version.Equals(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective2.Version); } return false; } public override int GetHashCode() { return Version.GetHashCode(); } } } namespace YamlDotNet.Core.ObjectPool { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 0, 1 })] internal class DefaultObjectPool : ObjectPool where T : class { private readonly Func createFunc; private readonly Func returnFunc; private readonly int maxCapacity; private int numItems; private protected readonly ConcurrentQueue items = new ConcurrentQueue(); [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(2)] private protected T fastItem; public DefaultObjectPool(IPooledObjectPolicy policy) : this(policy, Environment.ProcessorCount * 2) { } public DefaultObjectPool(IPooledObjectPolicy policy, int maximumRetained) { createFunc = policy.Create; returnFunc = policy.Return; maxCapacity = maximumRetained - 1; } public override T Get() { T result = fastItem; if (result == null || Interlocked.CompareExchange(ref fastItem, null, result) != result) { if (items.TryDequeue(out result)) { Interlocked.Decrement(ref numItems); return result; } return createFunc(); } return result; } public override void Return(T obj) { ReturnCore(obj); } private protected bool ReturnCore(T obj) { if (!returnFunc(obj)) { return false; } if (fastItem != null || Interlocked.CompareExchange(ref fastItem, obj, null) != null) { if (Interlocked.Increment(ref numItems) <= maxCapacity) { items.Enqueue(obj); return true; } Interlocked.Decrement(ref numItems); return false; } return true; } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class DefaultPooledObjectPolicy : IPooledObjectPolicy where T : class, new() { public T Create() { return new T(); } public bool Return(T obj) { if (obj is IResettable resettable) { return resettable.TryReset(); } return true; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface IPooledObjectPolicy { T Create(); bool Return(T obj); } internal interface IResettable { bool TryReset(); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal abstract class ObjectPool where T : class { public abstract T Get(); public abstract void Return(T obj); } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class ObjectPool { public static ObjectPool Create([<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] IPooledObjectPolicy policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy()); } public static ObjectPool Create(int maximumRetained, [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(new byte[] { 2, 1 })] IPooledObjectPolicy policy = null) where T : class, new() { return new DefaultObjectPool(policy ?? new DefaultPooledObjectPolicy(), maximumRetained); } } [DebuggerStepThrough] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class StringBuilderPool { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ObjectPool pool; public BuilderWrapper(StringBuilder builder, ObjectPool pool) { Builder = builder; this.pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { pool.Return(Builder); } } private static readonly ObjectPool Pool = ObjectPool.Create(new StringBuilderPooledObjectPolicy { InitialCapacity = 16, MaximumRetainedCapacity = 1024 }); public static BuilderWrapper Rent() { StringBuilder builder = Pool.Get(); return new BuilderWrapper(builder, Pool); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] 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; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal static class StringLookAheadBufferPool { [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal readonly struct BufferWrapper : IDisposable { public readonly StringLookAheadBuffer Buffer; private readonly ObjectPool<StringLookAheadBuffer> pool; public BufferWrapper(StringLookAheadBuffer buffer, ObjectPool<StringLookAheadBuffer> pool) { Buffer = buffer; this.pool = pool; } public override string ToString() { return Buffer.ToString(); } public void Dispose() { pool.Return(Buffer); } } private static readonly ObjectPool<StringLookAheadBuffer> Pool = ObjectPool.Create(new DefaultPooledObjectPolicy<StringLookAheadBuffer>()); public static BufferWrapper Rent(string value) { StringLookAheadBuffer StringLookAheadBuffer = Pool.Get(); StringLookAheadBuffer.Value = value; return new BufferWrapper(StringLookAheadBuffer, Pool); } } } namespace YamlDotNet.Core.Events { [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class AnchorAlias : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { internal override EventType Type => EventType.Alias; public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Value { get; } public AnchorAlias(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new <9f1d586b-d77e-4258-bb38-eb176815536f>YamlException(in start, in end, "Anchor value must not be empty."); } Value = value; } public AnchorAlias(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName value) : this(value, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return $"Alias [value = {Value}]"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public string Value { get; } public bool IsInline { get; } internal override EventType Type => EventType.Comment; public <52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment(string value, bool isInline) : this(value, isInline, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment(string value, bool isInline, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Value = value; IsInline = isInline; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } public override string ToString() { return (IsInline ? "Inline" : "Block") + " Comment [" + Value + "]"; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class DocumentEnd : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.DocumentEnd; public bool IsImplicit { get; } public DocumentEnd(bool isImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { IsImplicit = isImplicit; } public DocumentEnd(bool isImplicit) : this(isImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return $"Document end [isImplicit = {IsImplicit}]"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(2)] internal sealed class DocumentStart : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.DocumentStart; public TagDirectiveCollection Tags { get; } public <33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective Version { get; } public bool IsImplicit { get; } public DocumentStart(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective version, TagDirectiveCollection tags, bool isImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Version = version; Tags = tags; IsImplicit = isImplicit; } public DocumentStart(<33123a34-b3fc-4e8a-a4e2-219844ba375f>VersionDirective version, TagDirectiveCollection tags, bool isImplicit) : this(version, tags, isImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public DocumentStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : this(null, null, isImplicit: true, start, end) { } public DocumentStart() : this(null, null, isImplicit: true, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal interface <7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor { void Visit(AnchorAlias e); void Visit(<59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart e); void Visit(<751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd e); void Visit(DocumentStart e); void Visit(DocumentEnd e); void Visit(Scalar e); void Visit(<326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart e); void Visit(<4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd e); void Visit(<7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart e); void Visit(<6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd e); void Visit(<52cdc8a6-b039-4a15-9448-db7acc64bcd3>Comment e); } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal class <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.MappingEnd; public <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } public <6ecca1c5-273b-4e95-842e-8d040b4ffb77>MappingEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return "Mapping end"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart : <5b4e1044-096b-4e5c-b704-551fa771adb2>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 <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, bool isImplicit, MappingStyle style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, bool isImplicit, MappingStyle style) : this(anchor, tag, isImplicit, style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <7231b36d-778a-425a-903e-21ac3ab9861d>MappingStart() : this(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, isImplicit: true, MappingStyle.Any, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return $"Mapping start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum MappingStyle { Any, Block, Flow } internal abstract class <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public <694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName Anchor { get; } public <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName Tag { get; } public abstract bool IsCanonical { get; } protected <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { Anchor = anchor; Tag = tag; } protected <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag) : this(anchor, tag, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } } internal abstract class <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public virtual int NestingIncrease => 0; internal abstract EventType Type { get; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark Start { get; } public <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark End { get; } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] public abstract void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor); internal <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) { Start = start; End = end; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class Scalar : <5b4e1044-096b-4e5c-b704-551fa771adb2>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(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end, bool isKey = false) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; IsKey = isKey; } public Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Scalar(string value) : this(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName.Empty, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Scalar(<763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, string value) : this(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName.Empty, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public Scalar(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, string value) : this(anchor, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>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(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.SequenceEnd; public <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } public <4ad8224b-02dd-4665-aacb-4525b1f4b912>SequenceEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return "Sequence end"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart : <5b4e1044-096b-4e5c-b704-551fa771adb2>NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.SequenceStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle Style { get; } public <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, bool isImplicit, <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public <326fc025-c42e-43e7-a3d6-229d7b950ee5>SequenceStart(<694b1b2d-d1b1-405c-88e5-82fd0e5d66f6>AnchorName anchor, <763b3306-75ef-49cf-b5e4-c84545a2932c>TagName tag, bool isImplicit, <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle style) : this(anchor, tag, isImplicit, style, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return $"Sequence start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum <63d488d6-ccd0-4427-8357-81f9e0a06979>SequenceStyle { Any, Block, Flow } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.StreamEnd; public <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } public <751b9606-9fca-462a-916f-f35fccdf5cb4>StreamEnd() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public override string ToString() { return "Stream end"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart : <905c4171-2b55-4d94-bed7-421e597b1406>ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.StreamStart; public <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart() : this(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark.Empty) { } public <59ed284a-0453-414f-99b7-7b2f5da6af66>StreamStart(in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark start, in <31f47b9d-8d18-481e-bdd8-c0be28798592>Mark end) : base(in start, in end) { } public override string ToString() { return "Stream start"; } public override void Accept(<7e1cb154-d68a-49b8-9e15-f66c0b593073>IParsingEventVisitor visitor) { visitor.Visit(this); } } } namespace System.Diagnostics.CodeAnalysis { [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class <39198dc0-b9c8-4d82-ab34-59face54b949>AllowNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] internal sealed class <3d5ff3d6-b43f-45b2-a640-80aced72c2a8>DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public <3d5ff3d6-b43f-45b2-a640-80aced72c2a8>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 <41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public <41214478-6ad4-497d-9169-53b3d6fb78cb>MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] 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 <85ed5968-ed8b-4266-87ec-702678c1084e>NotNullAttribute : Attribute { } [<6c93d0e6-93c3-4b47-9f74-486f97e8037c>Nullable(0)] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [<7c34d804-8e9b-4adc-8e44-54bd192f7760>NullableContext(1)] internal sealed class <1b4a5fbd-3c39-4d90-b32b-25be11256d65>NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public <1b4a5fbd-3c39-4d90-b32b-25be11256d65>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; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<6434da27-6349-432f-94a1-5e9576724321>Embedded] internal sealed class <6434da27-6349-432f-94a1-5e9576724321>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<6434da27-6349-432f-94a1-5e9576724321>Embedded] [CompilerGenerated] internal sealed class <9f01c15f-3771-4d65-86cd-6de23f8fb457>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <9f01c15f-3771-4d65-86cd-6de23f8fb457>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <9f01c15f-3771-4d65-86cd-6de23f8fb457>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<6434da27-6349-432f-94a1-5e9576724321>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <4fed08f8-055b-4205-bba5-001f87224508>NullableContextAttribute : Attribute { public readonly byte Flag; public <4fed08f8-055b-4205-bba5-001f87224508>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [<6434da27-6349-432f-94a1-5e9576724321>Embedded] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] [PublicAPI] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] internal abstract class OwnConfigEntryBase { [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] internal class SyncedConfigEntry<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] T>(ConfigEntry sourceConfig) : OwnConfigEntryBase() { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(2)] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(1)] public readonly string Identifier; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(1)] public readonly Type Type; private object boxedValue; protected bool localIsOwner; public readonly int Priority; public object BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action ValueChanged; [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] internal sealed class CustomSyncedValue<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] [PublicAPI] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] internal class ConfigSync { [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public static ZRpc currentRpc; [HarmonyPrefix] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] [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); } } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] private class ParsedConfigs { [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary configValues = new Dictionary(); [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] private class SendConfigsAfterLogin { [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix([<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] private class PackageEntry { public string section = null; public string key = null; public Type type = null; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public object value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] private static class PreventSavingServerInfo { [HarmonyPrefix] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public string DisplayName; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public string CurrentVersion; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public string MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private OwnConfigEntryBase lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 1, 0, 1 })] private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0052: result = 0; goto IL_0053; IL_0053: return (byte)result != 0; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] [method: <4fed08f8-055b-4205-bba5-001f87224508>NullableContext(2)] [field: <9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] public event Action SourceOfTruthChanged; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] [method: <4fed08f8-055b-4205-bba5-001f87224508>NullableContext(2)] [field: <9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private event Action lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] T>(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (object _, EventArgs _) => { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] T>(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (object _, EventArgs _) => { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(([<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 0, 1 })] KeyValuePair kv) => { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; val2.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } [return: <9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private static OwnConfigEntryBase configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } [return: <9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1 })] public static SyncedConfigEntry ConfigData<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] T>(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute<[<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] T>(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage([<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1 })] IEnumerable configs = null, [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1 })] IEnumerable customValues = null, [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1 })] IEnumerable packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] object value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [PublicAPI] [<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(1)] [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(0)] [HarmonyPatch] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private string displayName; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private string currentVersion; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private string minimumRequiredVersion; public bool ModRequired = true; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private string ReceivedCurrentVersion; [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private string ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] private ConfigSync ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool flag = new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."); } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error([<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(2)] ZRpc rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(new byte[] { 2, 1, 1 })] Action original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (ZRpc rpc, [<9f01c15f-3771-4d65-86cd-6de23f8fb457>Nullable(1)] ZPackage pkg) => { CheckVersion(rpc, pkg, action); })); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "Disconnect")] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] 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([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy([<4fed08f8-055b-4205-bba5-001f87224508>NullableContext(0)] (KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace LocalizationManager { [PublicAPI] [NullableContext(1)] [Nullable(0)] internal class Localizer { private static readonly Dictionary>> PlaceholderProcessors; private static readonly Dictionary> loadedTexts; private static readonly ConditionalWeakTable localizationLanguage; private static readonly List> localizationObjects; [Nullable(2)] private static BaseUnityPlugin _plugin; private static readonly List fileExtensions; private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } private static void UpdatePlaceholderText(Localization localization, string key) { localizationLanguage.TryGetValue(localization, out var value); string text = loadedTexts[value][key]; if (PlaceholderProcessors.TryGetValue(key, out var value2)) { text = value2.Aggregate(text, [NullableContext(0)] (string current, KeyValuePair> kv) => current.Replace("{" + kv.Key + "}", kv.Value())); } localization.AddWord(key, text); } public static void AddPlaceholder(string key, string placeholder, ConfigEntry config, [Nullable(new byte[] { 2, 1, 1 })] Func convertConfigValue = null) { if (convertConfigValue == null) { convertConfigValue = [NullableContext(0)] [return: Nullable(1)] (T val) => val.ToString(); } if (!PlaceholderProcessors.ContainsKey(key)) { PlaceholderProcessors[key] = new Dictionary>(); } config.SettingChanged += [NullableContext(0)] (object _, EventArgs _) => { UpdatePlaceholder(); }; if (loadedTexts.ContainsKey(Localization.instance.GetSelectedLanguage())) { UpdatePlaceholder(); } void UpdatePlaceholder() { PlaceholderProcessors[key][placeholder] = () => convertConfigValue(config.Value); UpdatePlaceholderText(Localization.instance, key); } } public static void AddText(string key, string text) { List> list = new List>(); foreach (WeakReference localizationObject in localizationObjects) { if (localizationObject.TryGetTarget(out var target)) { Dictionary dictionary = loadedTexts[localizationLanguage.GetOrCreateValue(target)]; if (!target.m_translations.ContainsKey(key)) { dictionary[key] = text; target.AddWord(key, text); } } else { list.Add(localizationObject); } } foreach (WeakReference item in list) { localizationObjects.Remove(item); } } public static void Load() { LoadLocalization(Localization.instance, Localization.instance.GetSelectedLanguage()); } private static void LoadLocalization(Localization __instance, string language) { if (!localizationLanguage.Remove(__instance)) { localizationObjects.Add(new WeakReference(__instance)); } localizationLanguage.Add(__instance, language); Dictionary dictionary = new Dictionary(); foreach (string item in from f in Directory.GetFiles(Path.GetDirectoryName(Paths.PluginPath), plugin.Info.Metadata.Name + ".*", SearchOption.AllDirectories) where fileExtensions.IndexOf(Path.GetExtension(f)) >= 0 select f) { string text = Path.GetFileNameWithoutExtension(item).Split(new char[1] { '.' })[1]; if (dictionary.ContainsKey(text)) { Debug.LogWarning((object)("Duplicate key " + text + " found for " + plugin.Info.Metadata.Name + ". The duplicate file found at " + item + " will be skipped.")); } else { dictionary[text] = item; } } byte[] array = LoadTranslationFromAssembly("English"); if (array == null) { throw new Exception("Found no English localizations in mod " + plugin.Info.Metadata.Name + ". Expected an embedded resource translations/English.json or translations/English.yml."); } Dictionary dictionary2 = new DeserializerBuilder().IgnoreFields().Build().Deserialize>(Encoding.UTF8.GetString(array)); if (dictionary2 == null) { throw new Exception("Localization for mod " + plugin.Info.Metadata.Name + " failed: Localization file was empty."); } string text2 = null; if (language != "English") { if (dictionary.ContainsKey(language)) { text2 = File.ReadAllText(dictionary[language]); } else { byte[] array2 = LoadTranslationFromAssembly(language); if (array2 != null) { text2 = Encoding.UTF8.GetString(array2); } } } if (text2 == null && dictionary.ContainsKey("English")) { text2 = File.ReadAllText(dictionary["English"]); } if (text2 != null) { foreach (KeyValuePair item2 in new DeserializerBuilder().IgnoreFields().Build().Deserialize>(text2) ?? new Dictionary()) { dictionary2[item2.Key] = item2.Value; } } loadedTexts[language] = dictionary2; foreach (KeyValuePair item3 in dictionary2) { UpdatePlaceholderText(__instance, item3.Key); } } static Localizer() { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown PlaceholderProcessors = new Dictionary>>(); loadedTexts = new Dictionary>(); localizationLanguage = new ConditionalWeakTable(); localizationObjects = new List>(); fileExtensions = new List { ".json", ".yml" }; new Harmony("org.bepinex.helpers.LocalizationManager").Patch((MethodBase)AccessTools.DeclaredMethod(typeof(Localization), "LoadCSV", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(AccessTools.DeclaredMethod(typeof(Localizer), "LoadLocalization", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } [return: Nullable(2)] private static byte[] LoadTranslationFromAssembly(string language) { foreach (string fileExtension in fileExtensions) { byte[] array = ReadEmbeddedFileBytes("translations." + language + fileExtension); if (array != null) { return array; } } return null; } [NullableContext(2)] public static byte[] ReadEmbeddedFileBytes([Nullable(1)] string resourceFileName, Assembly containingAssembly = null) { using MemoryStream memoryStream = new MemoryStream(); if ((object)containingAssembly == null) { containingAssembly = Assembly.GetCallingAssembly(); } string text = containingAssembly.GetManifestResourceNames().FirstOrDefault([NullableContext(0)] (string str) => str.EndsWith(resourceFileName, StringComparison.Ordinal)); if (text != null) { containingAssembly.GetManifestResourceStream(text)?.CopyTo(memoryStream); } return (memoryStream.Length == 0L) ? null : memoryStream.ToArray(); } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class 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; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] 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)] internal sealed class MaybeNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { public static void Deconstruct(this KeyValuePair pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } } namespace YamlDotNet { internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } public override object? GetFormat(Type? formatType) { return provider.GetFormat(formatType); } } internal static class ReflectionExtensions { private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Type? BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type) { if (!type.IsValueType) { return type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo? GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (includeNonPublic) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsInterface) { return type.GetProperties(bindingFlags); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable GetPublicProperties(this Type type) { return GetProperties(type, includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if (RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute)); } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { internal abstract class BuilderSkeleton where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; private bool ignoreFields; private bool includeNonPublicProperties; 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"); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride(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; } 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 object? Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } 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 T Deserialize(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } 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 bool ignoreUnmatched; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy(() => new DefaultObjectFactory(typeMappings), 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() }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched) } }; 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() } }; } 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 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 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 (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList())); } } 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); object? Deserialize(TextReader input); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); T Deserialize(IParser parser); object? Deserialize(IParser parser); 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); } internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value); } internal interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } 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); } internal interface IObjectGraphTraversalStrategy { void Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); } internal interface IObjectGraphVisitor { bool Enter(IObjectDescriptor value, TContext context); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); void VisitScalar(IObjectDescriptor scalar, TContext context); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); void VisitMappingEnd(IObjectDescriptor mapping, TContext context); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); } internal interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } Type? TypeOverride { get; set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } 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 { void Serialize(TextWriter writer, object graph); string Serialize(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); } 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); void WriteYaml(IEmitter emitter, object? value, Type type); } 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 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 string Name { get; set; } public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, 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 void Serialize(TextWriter writer, object graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public string Serialize(object graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } 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); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; 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) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention); } 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, Action> where) where TEventEmitter : IEventEmitter { if (eventEmitterFactory == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory(inner))); return Self; } public SerializerBuilder WithEventEmitter(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); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings), 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(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, 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(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { if (objectGraphVisitorFactory == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() 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() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } } internal 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 IDictionary mappings; public TagMappings() { mappings = new Dictionary(); } public TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } internal Type? GetMapping(string tag) { if (!mappings.TryGetValue(tag, out Type value)) { return null; } return value; } } internal sealed class YamlAttributeOverrides { private 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 = ReflectionExtensions.BaseType(type); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); 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 = ExpressionExtensions.AsProperty(propertyAccessor); Add(typeof(TClass), propertyInfo.Name, attribute); } } internal sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T GetCustomAttribute() where T : Attribute { return overrides.GetAttribute(classType, Name) ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable GetProperties(Type type, 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 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; } } internal static class YamlFormatter { public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public static string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public static string FormatNumber(double number) { return number.ToString("G17", NumberFormat); } public static string FormatNumber(float number) { return number.ToString("G17", NumberFormat); } public static string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public static string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public static string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan/*cast due to .constrained prefix*/).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] 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"); } } } 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)) { if (!state.Get().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 aliasState = state.Get(); if (!aliasState.ContainsKey(anchorName)) { aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState2 = state.Get(); if (!aliasState2.TryGetValue(anchorName, out ValuePromise value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; public NodeValueDeserializer(IList deserializers, IList typeResolvers) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer.DeserializeValue(r, t, state, nestedObjectDeserializer), out object value)) { return YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(value, expectedType); } } } catch (YamlException) { throw; } catch (Exception innerException) { throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "Exception during deserialization", innerException); } throw new YamlException(@event?.Start ?? Mark.Empty, @event?.End ?? Mark.Empty, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType) { using (IEnumerator enumerator = typeResolvers.GetEnumerator()) { while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType)) { } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } internal sealed class ObjectAnchorCollection { private readonly IDictionary objectsByAnchor = new Dictionary(); private readonly IDictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out 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 static class ReflectionUtility { public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (ReflectionExtensions.IsGenericType(implementedInterface) && implementedInterface.GetGenericTypeDefinition() == genericInterfaceType) { return implementedInterface; } } return null; } public static IEnumerable GetImplementedInterfaces(Type type) { if (ReflectionExtensions.IsInterface(type)) { yield return type; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { yield return interfaces[i]; } } } internal sealed class SerializerState : IDisposable { private readonly IDictionary 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]) + str.Substring(1); str = Regex.Replace(ToCamelCase(str), "(?[A-Z])", (Match match) => separator + match.Groups["char"].Value.ToLowerInvariant()); return str; } } internal static class TypeConverter { public static T ChangeType(object? value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType(object? value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType(object? value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } public static object? ChangeType(object? value, Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } public static object? ChangeType(object? value, Type destinationType, CultureInfo culture) { if (value == null || ReflectionExtensions.IsDbNull(value)) { if (!ReflectionExtensions.IsValueType(destinationType)) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (ReflectionExtensions.IsGenericType(destinationType) && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture); return Activator.CreateInstance(destinationType, obj); } if (ReflectionExtensions.IsEnum(destinationType)) { if (!(value is string value2)) { return value; } return Enum.Parse(destinationType, value2, ignoreCase: true); } if (destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; for (int i = 0; i < array.Length; i++) { foreach (MethodInfo publicStaticMethod2 in ReflectionExtensions.GetPublicStaticMethods(array[i])) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.Unwrap(); } } } } if (type == typeof(string)) { try { MethodInfo publicStaticMethod = ReflectionExtensions.GetPublicStaticMethod(destinationType, "Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = ReflectionExtensions.GetPublicStaticMethod(destinationType, "Parse", typeof(string)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] 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))); } } } } 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 sealed class StaticTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { internal sealed class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container).ToList()); } } internal sealed class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable)typeInspectors) { } public CompositeTypeInspector(IEnumerable typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override IEnumerable GetProperties(Type type, object? container) { return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type, container)); } } internal sealed class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override IEnumerable GetProperties(Type type, 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 sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } internal sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { fieldInfo.SetValue(target, value); } public T GetCustomAttribute() where T : Attribute { return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable GetProperties(Type type, object? container) { return ReflectionExtensions.GetPublicFields(type).Select((Func)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } internal sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T GetCustomAttribute() where T : Attribute { return (T)ReflectionExtensions.GetAllCustomAttributes(propertyInfo).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = PropertyInfoExtensions.ReadValue(propertyInfo, 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 ReflectionExtensions.GetProperties(type, includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { public abstract IEnumerable GetProperties(Type type, object? container); public IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched) { IEnumerable enumerable = from p in GetProperties(type, container) where p.Name == name select p; using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } } 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 IDictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value) { if (value.Value != null && assignments.TryGetValue(value.Value, out 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) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value) { return true; } protected override void VisitScalar(IObjectDescriptor scalar) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence) { } private void VisitObject(IObjectDescriptor value) { if (value.Value != null) { assignments.Add(value.Value, new AnchorAssignment()); } } AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out 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(IObjectDescriptor value, IEmitter context) { if (value.Value != null) { AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { AliasEventInfo aliasEventInfo = new AliasEventInfo(value, alias); eventEmitter.Emit(aliasEventInfo, context); return aliasEventInfo.NeedsExpansion; } } return base.Enter(value, context); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter(IObjectDescriptor value, IEmitter context) { return nextVisitor.Enter(value, context); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context) { nextVisitor.VisitScalar(scalar, context); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { nextVisitor.VisitMappingEnd(mapping, context); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { nextVisitor.VisitSequenceStart(sequence, elementType, context); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { nextVisitor.VisitSequenceEnd(sequence, context); } } internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new YamlDotNet.Core.Events.Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context); } } internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEnumerable typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter(IObjectDescriptor value, IEmitter context) { IYamlTypeConverter yamlTypeConverter = typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value.Type)); if (yamlTypeConverter != null) { yamlTypeConverter.WriteYaml(context, value.Value, value.Type); return false; } if (value.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(value, context); } } internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } private static object? GetDefault(Type type) { if (!ReflectionExtensions.IsValueType(type)) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValueAttribute customAttribute = key.GetCustomAttribute(); object objB = ((customAttribute != null) ? customAttribute.Value : GetDefault(key.Type)); if (!object.Equals(value.Value, objB)) { return base.EnterMapping(key, value, context); } return false; } } internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor nextVisitor) : base(nextVisitor) { this.handling = handling; } private static object? GetDefault(Type type) { if (!ReflectionExtensions.IsValueType(type)) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValuesHandling defaultValuesHandling = handling; YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.IsDefaultValuesHandlingSpecified) { defaultValuesHandling = customAttribute.DefaultValuesHandling; } if ((defaultValuesHandling & DefaultValuesHandling.OmitNull) != DefaultValuesHandling.Preserve && value.Value == null) { return false; } if ((defaultValuesHandling & DefaultValuesHandling.OmitEmptyCollections) != DefaultValuesHandling.Preserve && value.Value is IEnumerable enumerable) { IEnumerator enumerator = enumerable.GetEnumerator(); bool flag = enumerator.MoveNext(); if (enumerator is IDisposable disposable) { disposable.Dispose(); } if (!flag) { return false; } } if ((defaultValuesHandling & DefaultValuesHandling.OmitDefaults) != DefaultValuesHandling.Preserve) { object objB = key.GetCustomAttribute()?.Value ?? GetDefault(key.Type); if (object.Equals(value.Value, objB)) { return false; } } return base.EnterMapping(key, value, context); } } internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, Nothing context) { if (typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value.Type)) != null) { return false; } if (value.Value is IYamlConvertible) { return false; } if (value.Value is IYamlSerializable) { return false; } return Enter(value); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context) { VisitMappingEnd(mapping); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context) { VisitMappingStart(mapping, keyType, valueType); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context) { VisitScalar(scalar); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context) { VisitSequenceEnd(sequence); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context) { VisitSequenceStart(sequence, elementType); } protected abstract bool Enter(IObjectDescriptor value); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value); protected abstract void VisitMappingEnd(IObjectDescriptor mapping); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType); protected abstract void VisitScalar(IObjectDescriptor scalar); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { protected struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly ITypeResolver typeResolver; private readonly INamingConvention namingConvention; public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention) { 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"); } void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) { Traverse("", graph, visitor, context, new Stack(maxRecursion)); } protected virtual void Traverse(object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(item.Name); num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(value, context)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = ReflectionExtensions.GetTypeCode(value.Type); switch (typeCode) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: visitor.VisitScalar(value, context); return; case TypeCode.Empty: throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } if (ReflectionExtensions.IsDbNull(value)) { visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); if (underlyingType != null) { Traverse("Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path); } else { TraverseObject(value, visitor, context, path); } } finally { path.Pop(); } } protected virtual void TraverseObject(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(value, visitor, typeof(object), typeof(object), context, path); return; } Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IDictionary<, >)); if (implementedGenericInterface != null) { Type[] genericArguments = implementedGenericInterface.GetGenericArguments(); object value2 = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), value.Value); TraverseDictionary(new ObjectDescriptor(value2, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(value, visitor, context, path); } else { TraverseProperties(value, visitor, context, path); } } protected virtual void TraverseDictionary(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path) { visitor.VisitMappingStart(dictionary, keyType, valueType, context); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); IObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); IObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context)) { Traverse(obj, objectDescriptor, visitor, context, path); Traverse(obj, objectDescriptor2, visitor, context, path); } } visitor.VisitMappingEnd(dictionary, context); } private void TraverseList(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(value.Type, typeof(IEnumerable<>)); Type type = ((implementedGenericInterface != null) ? implementedGenericInterface.GetGenericArguments()[0] : typeof(object)); visitor.VisitSequenceStart(value, type, context); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(num, GetObjectDescriptor(item, type), visitor, context, path); num++; } visitor.VisitSequenceEnd(value, context); } protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { visitor.VisitMappingStart(value, typeof(string), typeof(object), context); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context)) { Traverse(property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string)), visitor, context, path); Traverse(property.Name, value2, visitor, context, path); } } visitor.VisitMappingEnd(value, context); } private IObjectDescriptor GetObjectDescriptor(object? value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly IEnumerable converters; public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention) { this.converters = converters; } protected override void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (!value.Type.HasDefaultConstructor() && !converters.Any((IYamlTypeConverter c) => c.Accepts(value.Type))) { throw new InvalidOperationException($"Type '{value.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value, visitor, context, path); } } } namespace YamlDotNet.Serialization.ObjectFactories { internal sealed class DefaultObjectFactory : IObjectFactory { 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) } }; public DefaultObjectFactory() { } public DefaultObjectFactory(IDictionary mappings) { 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); } } public object Create(Type type) { if (ReflectionExtensions.IsInterface(type)) { Type value2; if (ReflectionExtensions.IsGenericType(type)) { 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); } catch (Exception innerException) { throw new InvalidOperationException("Failed to create an instance of type '" + type.FullName + "'.", innerException); } } } internal sealed class LambdaObjectFactory : IObjectFactory { private readonly Func factory; public LambdaObjectFactory(Func factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public object Create(Type type) { return factory(type); } } } 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}'."); } } _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; } } } bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!expectedType.IsArray) { value = false; return false; } Type? elementType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(elementType, parser, nestedObjectDeserializer, arrayList, canUpdate: true); Array array = Array.CreateInstance(elementType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public CollectionNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { bool canUpdate = true; Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); Type type; IList list; if (implementedGenericInterface != null) { type = implementedGenericInterface.GetGenericArguments()[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { canUpdate = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>)) != null; list = (IList)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(type), value); } } else { if (!typeof(IList).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); value = objectFactory.Create(expectedType); list = (IList)value; } DeserializeHelper(type, parser, nestedObjectDeserializer, list, canUpdate); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate) { parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { throw new ForwardAnchorNotSupportedException(current?.Start ?? Mark.Empty, current?.End ?? Mark.Empty, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result.Add(ReflectionExtensions.IsValueType(tItem) ? Activator.CreateInstance(tItem) : null); valuePromise.ValueAvailable += delegate(object? v) { result[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem); }; } else { result.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem)); } } } } internal sealed class DictionaryNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public DictionaryNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementedGenericInterface != null) { Type[] genericArguments = implementedGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } DeserializeHelper(type, type2, parser, nestedObjectDeserializer, dictionary); return true; } private static void DeserializeHelper(Type tKey, Type tValue, IParser parser, Func nestedObjectDeserializer, IDictionary result) { 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) { result[v] = value; } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += delegate(object? v) { if (hasFirstPart) { result[key] = v; } else { value = v; hasFirstPart = true; } }; } else if (valuePromise == null) { result[key] = value; } else { valuePromise.ValueAvailable += delegate(object? v) { result[key] = v; }; } } } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); if (implementedGenericInterface != expectedType) { value = null; return false; } type = implementedGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } private bool NodeIsNull(NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is YamlDotNet.Core.Events.Scalar { Style: ScalarStyle.Plain } 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 typeDescriptor; private readonly bool ignoreUnmatched; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.ignoreUnmatched = ignoreUnmatched; } bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); IPropertyDescriptor property = typeDescriptor.GetProperty(type, null, scalar.Value, ignoreUnmatched); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } object obj = nestedObjectDeserializer(parser, property.Type); if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += delegate(object? v) { object value3 = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, property.Type); property.Write(valueRef, value3); }; } else { object value2 = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, property.Type); property.Write(value, value2); } } return true; } } internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; if (ReflectionExtensions.IsEnum(type)) { value = Enum.Parse(type, @event.Value, ignoreCase: true); return true; } TypeCode typeCode = ReflectionExtensions.GetTypeCode(type); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { value = @event.Value; } else { value = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(@event.Value, expectedType); } break; } return true; } private object DeserializeBooleanHelper(string value) { bool flag; if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { flag = true; } else { if (!Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } flag = false; } return flag; } private object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilder stringBuilder = new StringBuilder(); 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] != '_') { stringBuilder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(stringBuilder.ToString(), num2); break; case 16: num = ulong.Parse(stringBuilder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", "")); } } if (flag) { return CastInteger(checked(-(long)num), typeCode); } return CastInteger(num, typeCode); } 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, }); } } internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly IEnumerable converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = converters ?? throw new ArgumentNullException("converters"); } bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { IYamlTypeConverter yamlTypeConverter = converters.FirstOrDefault((IYamlTypeConverter c) => c.Accepts(expectedType)); if (yamlTypeConverter == null) { value = null; return false; } value = yamlTypeConverter.ReadYaml(parser, expectedType); 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) { 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) { 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 StringExtensions.ToCamelCase(value); } } 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 StringExtensions.FromCamelCase(value, "-"); } } internal sealed class LowerCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } public string Apply(string value) { return StringExtensions.ToCamelCase(value).ToLower(); } } 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; } } 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 StringExtensions.ToPascalCase(value); } } 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 StringExtensions.FromCamelCase(value, "_"); } } } 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 { public JsonEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { } public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) { eventInfo.NeedsExpansion = true; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { eventInfo.IsPlainImplicit = true; eventInfo.Style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.RenderedValue = "null"; } else { TypeCode typeCode = ReflectionExtensions.GetTypeCode(eventInfo.Source.Type); switch (typeCode) { case TypeCode.Boolean: eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (ReflectionExtensions.IsEnum(eventInfo.Source.Type)) { eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; } else { eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly bool requireTagWhenStaticAndActualTypesAreDifferent; private readonly IDictionary tagMappings; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings) : base(nextEmitter) { this.requireTagWhenStaticAndActualTypesAreDifferent = requireTagWhenStaticAndActualTypesAreDifferent; this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { ScalarStyle style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = ReflectionExtensions.GetTypeCode(eventInfo.Source.Type); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = JsonSchema.Tags.Bool; eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ScalarStyle.Any; break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } eventInfo.IsPlainImplicit = true; if (eventInfo.Style == ScalarStyle.Any) { eventInfo.Style = style; } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } private void AssignTypeIfNeeded(ObjectEventInfo eventInfo) { if (tagMappings.TryGetValue(eventInfo.Source.Type, out var value)) { eventInfo.Tag = value; } else if (requireTagWhenStaticAndActualTypesAreDifferent && eventInfo.Source.Value != null && eventInfo.Source.Type != eventInfo.Source.StaticType) { throw new YamlException("Cannot serialize type '" + eventInfo.Source.Type.FullName + "' where a '" + eventInfo.Source.StaticType.FullName + "' was expected because no tag mapping has been registered for '" + eventInfo.Source.Type.FullName + "', which means that it won't be possible to deserialize the document.\nRegister a tag mapping using the SerializerBuilder.WithTagMapping method.\n\nE.g: builder.WithTagMapping(\"!" + eventInfo.Source.Type.Name + "\", typeof(" + eventInfo.Source.Type.FullName + "));"); } } } 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 DateTimeConverter : IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, IFormatProvider? provider = null, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type) { return EnsureDateTimeKind(DateTime.ParseExact(parser.Consume().Value, style: (kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal, formats: formats, provider: provider), kind); } public void WriteYaml(IEmitter emitter, object? value, Type type) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, 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 GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(IParser parser, Type type) { return new Guid(parser.Consume().Value); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Guid guid = (Guid)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type) { return Type.GetType(parser.Consume().Value, throwOnError: true); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Type type2 = (Type)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, type2.AssemblyQualifiedName, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } } namespace YamlDotNet.RepresentationModel { internal class DocumentLoadingState { private readonly IDictionary anchors = new Dictionary(); private readonly IList nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } if (anchors.ContainsKey(node.Anchor)) { anchors[node.Anchor] = node; } else { anchors.Add(node.Anchor, node); } } public YamlNode GetNode(AnchorName anchor, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out YamlNode value)) { return value; } throw new AnchorNotFoundException(start, 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 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.ToString(); } 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() { new AnchorAssigningVisitor().AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: false)); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } } internal sealed class YamlMappingNode : YamlNode, IEnumerable>, IEnumerable, IYamlConvertible { private readonly IOrderedDictionary children = new OrderedDictionary(); public IOrderedDictionary Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { MappingStart mappingStart = parser.Consume(); Load(mappingStart, state); Style = mappingStart.Style; bool flag = false; MappingEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); YamlNode yamlNode2 = YamlNode.ParseNode(parser, state); try { children.Add(yamlNode, yamlNode2); } catch (ArgumentException innerException) { throw new YamlException(yamlNode.Start, yamlNode.End, "Duplicate key", innerException); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode(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 = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value); } return num; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair child in children) { foreach (YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilder stringBuilder = new StringBuilder("{ "); foreach (KeyValuePair child in children) { if (stringBuilder.Length > 2) { stringBuilder.Append(", "); } stringBuilder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } stringBuilder.Append(" }"); level.Decrement(); return stringBuilder.ToString(); } 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 ReflectionExtensions.GetPublicProperties(mapping.GetType())) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); YamlNode yamlNode = value as YamlNode; if (yamlNode == null) { yamlNode = Convert.ToString(value) ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } 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 { public string? Value { get; set; } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); Value = scalar.Value; Style = scalar.Style; } public YamlScalarNode() { } public YamlScalarNode(string? value) { Value = value; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, base.Tag, Value ?? string.Empty, Style, base.Tag.IsEmpty, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } 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, 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 IList children = new List(); public IList Children => children; public SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { SequenceStart sequenceStart = parser.Consume(); Load(sequenceStart, state); Style = sequenceStart.Style; bool flag = false; SequenceEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); children.Add(yamlNode); flag = flag || yamlNode is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlSequenceNode(IEnumerable children) { foreach (YamlNode child in children) { this.children.Add(child); } } public void Add(YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new YamlScalarNode(child)); } internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } 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!"; } StringBuilder stringBuilder = new StringBuilder("[ "); foreach (YamlNode child in children) { if (stringBuilder.Length > 2) { stringBuilder.Append(", "); } stringBuilder.Append(child.ToString(level)); } stringBuilder.Append(" ]"); level.Decrement(); return stringBuilder.ToString(); } 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 IList documents = new List(); public IList Documents => documents; public YamlStream() { } public YamlStream(params YamlDocument[] documents) : this((IEnumerable)documents) { } public YamlStream(IEnumerable documents) { foreach (YamlDocument document in documents) { this.documents.Add(document); } } public void Add(YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(IParser parser) { documents.Clear(); parser.Consume(); YamlDotNet.Core.Events.StreamEnd @event; while (!parser.TryConsume(out @event)) { YamlDocument item = new YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); foreach (YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [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 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; } 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 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 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 static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] internal 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 Enumerable.Contains(orderedDictionary.dictionary.Keys, item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((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.Values.Contains(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((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(TKey key, TValue value) { Add(new KeyValuePair(key, value)); } public void Add(KeyValuePair item) { dictionary.Add(item.Key, item.Value); list.Add(item); } 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 Lazy { public static Lazy FromValue(T value) { Lazy lazy = new Lazy(() => value, isThreadSafe: false); _ = lazy.Value; return lazy; } } 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; } } } namespace YamlDotNet.Core { internal struct AnchorName : IEquatable { public static readonly AnchorName Empty = default(AnchorName); 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(Mark start, Mark end, string message) : base(start, end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } internal sealed class CharacterAnalyzer where TBuffer : class, ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { Buffer = buffer ?? throw new ArgumentNullException("buffer"); } public char Peek(int offset) { return Buffer.Peek(offset); } public void Skip(int length) { Buffer.Skip(length); } public bool IsAlphaNumericDashOrUnderscore(int offset = 0) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && c != '_') { return c == '-'; } return true; } public bool IsAscii(int offset = 0) { return Buffer.Peek(offset) <= '\u007f'; } public bool IsPrintable(int offset = 0) { char c = Buffer.Peek(offset); switch (c) { default: if (c != '\u0085' && (c < '\u00a0' || c > '\ud7ff')) { if (c >= '\ue000') { return c <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } public bool IsDigit(int offset = 0) { char c = Buffer.Peek(offset); if (c >= '0') { return c <= '9'; } return false; } public int AsDigit(int offset = 0) { return Buffer.Peek(offset) - 48; } public bool IsHex(int offset) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } public int AsHex(int offset) { char c = Buffer.Peek(offset); if (c <= '9') { return c - 48; } if (c <= 'F') { return c - 65 + 10; } return c - 97 + 10; } public bool IsSpace(int offset = 0) { return Check(' ', offset); } public bool IsZero(int offset = 0) { return Check('\0', offset); } public bool IsTab(int offset = 0) { return Check('\t', offset); } public bool IsWhite(int offset = 0) { if (!IsSpace(offset)) { return IsTab(offset); } return true; } public bool IsBreak(int offset = 0) { return Check("\r\n\u0085\u2028\u2029", offset); } public bool IsCrLf(int offset = 0) { if (Check('\r', offset)) { return Check('\n', offset + 1); } return false; } public bool IsBreakOrZero(int offset = 0) { if (!IsBreak(offset)) { return IsZero(offset); } return true; } public bool IsWhiteBreakOrZero(int offset = 0) { if (!IsWhite(offset)) { return IsBreakOrZero(offset); } return true; } public bool Check(char expected, int offset = 0) { return Buffer.Peek(offset) == expected; } public bool Check(string expectedCharacters, int offset = 0) { char value = Buffer.Peek(offset); return expectedCharacters.IndexOf(value) != -1; } } internal static class Constants { 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; } internal sealed class Cursor { public int Index { get; private set; } public int Line { get; private set; } public int LineOffset { get; private set; } public Cursor() { Line = 1; } public Cursor(Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public Mark Mark() { return new Mark(Index, Line, LineOffset + 1); } public void Skip() { Index++; LineOffset++; } public void SkipLineByOffset(int offset) { Index += offset; Line++; LineOffset = 0; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0) { Line++; LineOffset = 0; } } } 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 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 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; this.output = output; outputUsesUnicodeEncoding = IsUnicode(output.Encoding); } public void Emit(ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { ParsingEvent evt = events.Peek(); try { AnalyzeEvent(evt); StateMachine(evt); } finally { events.Dequeue(); } } } private bool NeedMoreEvents() { if (events.Count == 0) { return true; } int num; switch (events.Peek().Type) { case EventType.DocumentStart: num = 1; break; case EventType.SequenceStart: num = 2; break; case EventType.MappingStart: num = 3; break; default: return false; } if (events.Count > num) { return false; } int num2 = 0; using (Queue.Enumerator enumerator = events.GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current.Type) { case EventType.DocumentStart: case EventType.SequenceStart: case EventType.MappingStart: num2++; break; case EventType.DocumentEnd: case EventType.SequenceEnd: case EventType.MappingEnd: num2--; break; } if (num2 == 0) { return false; } } } return true; } private void AnalyzeEvent(ParsingEvent evt) { anchorData.Anchor = AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { AnalyzeAnchor(anchorAlias.Value, isAlias: true); } else if (evt is NodeEvent nodeEvent) { if (evt is YamlDotNet.Core.Events.Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(nodeEvent.Anchor, isAlias: false); if (!nodeEvent.Tag.IsEmpty && (isCanonical || nodeEvent.IsCanonical)) { AnalyzeTag(nodeEvent.Tag); } } } private void AnalyzeAnchor(AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(YamlDotNet.Core.Events.Scalar scalar) { string value = scalar.Value; scalarData.Value = value; if (value.Length == 0) { if (scalar.Tag == "tag:yaml.org,2002:null") { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = false; scalarData.IsBlockAllowed = false; } else { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = false; } return; } bool flag = false; bool flag2 = false; if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) { flag = true; flag2 = true; } CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); bool flag3 = true; bool flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; bool flag10 = false; bool flag11 = false; bool flag12 = false; bool flag13 = false; bool flag14 = false; bool flag15 = false; bool flag16 = !ValueIsRepresentableInOutputEncoding(value); bool flag17 = false; bool flag18 = false; bool flag19 = true; while (!characterAnalyzer.EndOfInput) { if (flag19) { if (characterAnalyzer.Check("#,[]{}&*!|>\\\"%@`'")) { flag = true; flag2 = true; flag9 = characterAnalyzer.Check('\''); flag17 |= characterAnalyzer.Check('\''); } if (characterAnalyzer.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (characterAnalyzer.Check(",?[]{}")) { flag = true; } if (characterAnalyzer.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= characterAnalyzer.Check('\''); } if (!flag16 && !characterAnalyzer.IsPrintable()) { flag16 = true; } if (characterAnalyzer.IsBreak()) { flag15 = true; } if (characterAnalyzer.IsSpace()) { if (flag19) { flag5 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (characterAnalyzer.IsBreak()) { if (flag19) { flag6 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag8 = true; } if (flag12) { flag11 = true; } if (flag14) { flag18 = true; } flag12 = false; flag13 = true; } else { flag12 = false; flag13 = false; flag14 = false; } flag3 = characterAnalyzer.IsWhiteBreakOrZero(); characterAnalyzer.Skip(1); if (!characterAnalyzer.EndOfInput) { flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); } flag19 = false; } scalarData.IsFlowPlainAllowed = true; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = true; if (flag5 || flag6 || flag7 || flag8 || flag9) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag7) { scalarData.IsBlockAllowed = false; } if (flag10) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag11 || flag16) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag18) { scalarData.IsBlockAllowed = false; } scalarData.IsMultiline = flag15; if (flag15) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag) { scalarData.IsFlowPlainAllowed = false; } if (flag2) { scalarData.IsBlockPlainAllowed = false; } scalarData.HasSingleQuotes = flag17; } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); return output.Encoding.GetString(bytes, 0, bytes.Length).Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private bool IsUnicode(Encoding encoding) { if (!(encoding is UTF8Encoding) && !(encoding is UnicodeEncoding)) { return encoding is UTF7Encoding; } return true; } private void AnalyzeTag(TagName tag) { tagData.Handle = tag.Value; foreach (TagDirective tagDirective in tagDirectives) { if (tag.Value.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) { tagData.Handle = tagDirective.Handle; tagData.Suffix = tag.Value.Substring(tagDirective.Prefix.Length); break; } } } private void StateMachine(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.Comment comment) { EmitComment(comment); return; } switch (state) { case EmitterState.StreamStart: EmitStreamStart(evt); break; case EmitterState.FirstDocumentStart: EmitDocumentStart(evt, isFirst: true); break; case EmitterState.DocumentStart: EmitDocumentStart(evt, isFirst: false); break; case EmitterState.DocumentContent: EmitDocumentContent(evt); break; case EmitterState.DocumentEnd: EmitDocumentEnd(evt); break; case EmitterState.FlowSequenceFirstItem: EmitFlowSequenceItem(evt, isFirst: true); break; case EmitterState.FlowSequenceItem: EmitFlowSequenceItem(evt, isFirst: false); break; case EmitterState.FlowMappingFirstKey: EmitFlowMappingKey(evt, isFirst: true); break; case EmitterState.FlowMappingKey: EmitFlowMappingKey(evt, isFirst: false); break; case EmitterState.FlowMappingSimpleValue: EmitFlowMappingValue(evt, isSimple: true); break; case EmitterState.FlowMappingValue: EmitFlowMappingValue(evt, isSimple: false); break; case EmitterState.BlockSequenceFirstItem: EmitBlockSequenceItem(evt, isFirst: true); break; case EmitterState.BlockSequenceItem: EmitBlockSequenceItem(evt, isFirst: false); break; case EmitterState.BlockMappingFirstKey: EmitBlockMappingKey(evt, isFirst: true); break; case EmitterState.BlockMappingKey: EmitBlockMappingKey(evt, isFirst: false); break; case EmitterState.BlockMappingSimpleValue: EmitBlockMappingValue(evt, isSimple: true); break; case EmitterState.BlockMappingValue: EmitBlockMappingValue(evt, isSimple: false); break; case EmitterState.StreamEnd: throw new YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(YamlDotNet.Core.Events.Comment comment) { if (comment.IsInline) { Write(' '); } else { WriteIndent(); } Write("# "); Write(comment.Value); WriteBreak(); 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}", new object[2] { version.Major, version.Minor }), needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } foreach (TagDirective item in tagDirectiveCollection) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectiveCollection); } foreach (TagDirective item2 in tagDirectiveCollection) { WriteIndicator("%TAG", needWhitespace: true, whitespace: false, indentation: false); WriteTagHandle(item2.Handle); WriteTagContent(item2.Prefix, needsWhitespace: true); WriteIndent(); } } if (CheckEmptyDocument()) { flag = false; } if (!flag) { WriteIndent(); WriteIndicator("---", needWhitespace: true, whitespace: false, indentation: false); if (isCanonical) { WriteIndent(); } } state = EmitterState.DocumentContent; } else { if (!(evt is YamlDotNet.Core.Events.StreamEnd)) { throw new YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private TagDirectiveCollection NonDefaultTagsAmong(IEnumerable? tagCollection) { TagDirectiveCollection tagDirectiveCollection = new TagDirectiveCollection(); if (tagCollection == null) { return tagDirectiveCollection; } foreach (TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, tagDirectiveCollection); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective item in defaultTagDirectives) { tagDirectiveCollection.Remove(item); } return tagDirectiveCollection; } private void AnalyzeVersionDirective(VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(ParsingEvent evt, bool isMapping, bool isSimpleKey) { isMappingContext = isMapping; isSimpleKeyContext = isSimpleKey; switch (evt.Type) { case EventType.Alias: EmitAlias(); break; case EventType.Scalar: EmitScalar(evt); break; case EventType.SequenceStart: EmitSequenceStart(evt); break; case EventType.MappingStart: EmitMappingStart(evt); break; default: throw new YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(ParsingEvent evt) { YamlDotNet.Core.Events.Scalar scalar = (YamlDotNet.Core.Events.Scalar)evt; ScalarStyle scalarStyle = scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) { throw new YamlException("Neither tag nor isImplicit flags are specified."); } if (scalarStyle == ScalarStyle.Any) { scalarStyle = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { scalarStyle = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { scalarStyle = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.SingleQuoted; } if (flag && !scalar.IsPlainImplicit) { scalarStyle = ScalarStyle.SingleQuoted; } } if (scalarStyle == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { scalarStyle = ScalarStyle.DoubleQuoted; } if ((scalarStyle == ScalarStyle.Literal || scalarStyle == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.DoubleQuoted; } scalarData.Style = scalarStyle; } private void ProcessScalar() { switch (scalarData.Style) { case ScalarStyle.Plain: WritePlainScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.SingleQuoted: WriteSingleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.DoubleQuoted: WriteDoubleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.Literal: WriteLiteralScalar(scalarData.Value); break; case ScalarStyle.Folded: WriteFoldedScalar(scalarData.Value); break; default: throw new InvalidOperationException(); } } private void WritePlainScalar(string value, bool allowBreaks) { if (!isWhitespace) { Write(' '); } bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsSpace(c)) { if (allowBreaks && !flag && column > bestWidth && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } Write(c); isIndentation = false; flag = false; flag2 = false; } isWhitespace = false; isIndentation = false; } private void WriteSingleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("'", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == ' ') { if (allowBreaks && !flag && column > bestWidth && i != 0 && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } if (c == '\'') { Write(c); } Write(c); isIndentation = false; flag = false; flag2 = false; } WriteIndicator("'", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteDoubleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("\"", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsPrintable(c) && !IsBreak(c, out var _)) { switch (c) { case '"': case '\\': break; case ' ': if (allowBreaks && !flag && column > bestWidth && i > 0 && i + 1 < value.Length) { WriteIndent(); if (value[i + 1] == ' ') { Write('\\'); } } else { Write(c); } flag = true; continue; default: Write(c); flag = false; continue; } } Write('\\'); switch (c) { case '\0': Write('0'); break; case '\a': Write('a'); break; case '\b': Write('b'); break; case '\t': Write('t'); break; case '\n': Write('n'); break; case '\v': Write('v'); break; case '\f': Write('f'); break; case '\r': Write('r'); break; case '\u001b': Write('e'); break; case '"': Write('"'); break; case '\\': Write('\\'); break; case '\u0085': Write('N'); break; case '\u00a0': Write('_'); break; case '\u2028': Write('L'); break; case '\u2029': Write('P'); break; default: { ushort num = c; if (num <= 255) { Write('x'); Write(num.ToString("X02", CultureInfo.InvariantCulture)); } else if (IsHighSurrogate(c)) { if (i + 1 >= value.Length || !IsLowSurrogate(value[i + 1])) { throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); } Write('U'); Write(char.ConvertToUtf32(c, value[i + 1]).ToString("X08", CultureInfo.InvariantCulture)); i++; } else { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); } break; } } flag = false; } WriteIndicator("\"", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteLiteralScalar(string value) { bool flag = true; WriteIndicator("|", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (IsBreak(c, out var breakChar)) { WriteBreak(breakChar); isIndentation = true; flag = true; continue; } if (flag) { WriteIndent(); } Write(c); isIndentation = false; flag = false; } } private void WriteFoldedScalar(string value) { bool flag = true; bool flag2 = true; WriteIndicator(">", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsBreak(c, out var breakChar)) { if (!flag && !flag2 && c == '\n') { int j; char breakChar2; for (j = 0; i + j < value.Length && IsBreak(value[i + j], out breakChar2); j++) { } if (i + j < value.Length && !IsBlank(value[i + j]) && !IsBreak(value[i + j], out breakChar2)) { WriteBreak(); } } WriteBreak(breakChar); isIndentation = true; flag = true; } else { if (flag) { WriteIndent(); flag2 = IsBlank(c); } if (!flag && c == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) { WriteIndent(); } else { Write(c); } isIndentation = false; flag = false; } } } private static bool IsSpace(char character) { return character == ' '; } private static bool IsBreak(char character, out char breakChar) { switch (character) { case '\n': case '\r': case '\u0085': breakChar = '\n'; return true; case '\u2028': case '\u2029': breakChar = character; return true; default: breakChar = '\0'; return false; } } private static bool IsBlank(char character) { if (character != ' ') { return character == '\t'; } return true; } private static bool IsPrintable(char character) { switch (character) { default: if (character != '\u0085' && (character < '\u00a0' || character > '\ud7ff')) { if (character >= '\ue000') { return character <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } private static bool IsHighSurrogate(char c) { if ('\ud800' <= c) { return c <= '\udbff'; } return false; } private static bool IsLowSurrogate(char c) { if ('\udc00' <= c) { return c <= '\udfff'; } return false; } private void EmitSequenceStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) { state = EmitterState.FlowMappingFirstKey; } else { state = EmitterState.BlockMappingFirstKey; } } private void ProcessAnchor() { if (!anchorData.Anchor.IsEmpty && !skipAnchorName) { WriteIndicator(anchorData.IsAlias ? "*" : "&", needWhitespace: true, whitespace: false, indentation: false); WriteAnchor(anchorData.Anchor); } } private void ProcessTag() { if (tagData.Handle == null && tagData.Suffix == null) { return; } if (tagData.Handle != null) { WriteTagHandle(tagData.Handle); if (tagData.Suffix != null) { WriteTagContent(tagData.Suffix, needsWhitespace: false); } } else { WriteIndicator("!<", needWhitespace: true, whitespace: false, indentation: false); WriteTagContent(tagData.Suffix, needsWhitespace: false); WriteIndicator(">", needWhitespace: false, whitespace: false, indentation: false); } } private void EmitDocumentEnd(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.DocumentEnd documentEnd) { WriteIndent(); if (!documentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is SequenceEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("]", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); } else { if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } states.Push(EmitterState.FlowSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } } private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is MappingEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("}", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); return; } if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } if (!isCanonical && CheckSimpleKey()) { states.Push(EmitterState.FlowMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: false); states.Push(EmitterState.FlowMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { if (isCanonical || column > bestWidth) { WriteIndent(); } WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: false); } states.Push(EmitterState.FlowMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is SequenceEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); WriteIndicator("-", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is MappingEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); if (CheckSimpleKey()) { states.Push(EmitterState.BlockMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { WriteIndent(); WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: true); } states.Push(EmitterState.BlockMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void IncreaseIndent(bool isFlow, bool isIndentless) { indents.Push(indent); if (indent < 0) { indent = (isFlow ? bestIndent : 0); } else if (!isIndentless || !forceIndentLess) { indent += bestIndent; } } private bool CheckEmptyDocument() { int num = 0; foreach (ParsingEvent @event in events) { num++; if (num == 2) { if (@event is YamlDotNet.Core.Events.Scalar scalar) { return string.IsNullOrEmpty(scalar.Value); } break; } } return false; } private bool CheckSimpleKey() { if (events.Count < 1) { return false; } int num; switch (events.Peek().Type) { case EventType.Alias: num = AnchorNameLength(anchorData.Anchor); break; case EventType.Scalar: if (scalarData.IsMultiline) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix) + SafeStringLength(scalarData.Value); break; case EventType.SequenceStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; case EventType.MappingStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; default: return false; } return num <= maxSimpleKeyLength; } private int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } private 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) { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); if (characterAnalyzer.IsSpace() || characterAnalyzer.IsBreak()) { int num = bestIndent; string indicator = num.ToString(CultureInfo.InvariantCulture); WriteIndicator(indicator, needWhitespace: false, whitespace: false, indentation: false); } string text = null; if (value.Length == 0 || !characterAnalyzer.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && characterAnalyzer.IsBreak(value.Length - 2)) { text = "+"; } if (text != null) { WriteIndicator(text, needWhitespace: false, whitespace: false, indentation: false); } } private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) { if (needWhitespace && !isWhitespace) { Write(' '); } Write(indicator); isWhitespace = whitespace; isIndentation &= indentation; } private void WriteIndent() { int num = Math.Max(indent, 0); if (!isIndentation || column > num || (column == num && !isWhitespace)) { WriteBreak(); } while (column < num) { Write(' '); } isWhitespace = true; isIndentation = true; } private void WriteAnchor(AnchorName value) { Write(value.Value); isWhitespace = false; isIndentation = false; } private void WriteTagHandle(string value) { if (!isWhitespace) { Write(' '); } Write(value); isWhitespace = false; isIndentation = false; } private void WriteTagContent(string value, bool needsWhitespace) { if (needsWhitespace && !isWhitespace) { Write(' '); } Write(UrlEncode(value)); isWhitespace = false; isIndentation = false; } private string UrlEncode(string text) { return UriReplacer.Replace(text, delegate(Match match) { StringBuilder stringBuilder = new StringBuilder(); byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { stringBuilder.AppendFormat("%{0:X02}", b); } return stringBuilder.ToString(); }); } 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 bool IsCanonical { get; } public bool SkipAnchorName { get; private set; } public int MaxSimpleKeyLength { get; } = 1024; public bool IndentSequences { get; } public EmitterSettings() { } public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = 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; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName); } public EmitterSettings Canonical() { return new EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithoutAnchorName() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: 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(Mark start, Mark end, string message) : base(start, 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)); } public static int CombineHashCodes(object? first, params object?[] others) { int num = GetHashCode(first); foreach (object o in others) { num = CombineHashCodes(num, o); } return num; } 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 (!NumberExtensions.IsPowerOfTwo(initialCapacity)) { 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(); } 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 (!NumberExtensions.IsPowerOfTwo(capacity)) { 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 sealed class Mark : IEquatable, IComparable, IComparable { public static readonly Mark Empty = new Mark(); public int Index { get; } public int Line { get; } public int Column { get; } public Mark() { Line = 1; Column = 1; } public Mark(int index, int line, int column) { if (index < 0) { throw new ArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); } if (line < 1) { throw new ArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); } if (column < 1) { throw new ArgumentOutOfRangeException("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(obj as Mark); } public bool Equals(Mark? other) { if (other != null && 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) { if (obj == null) { throw new ArgumentNullException("obj"); } return CompareTo(obj as Mark); } public int CompareTo(Mark? other) { if (other == null) { throw new ArgumentNullException("other"); } int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } } internal sealed class MaximumRecursionLevelReachedException : YamlException { public MaximumRecursionLevelReachedException(string message) : base(message) { } public MaximumRecursionLevelReachedException(Mark start, Mark end, string message) : base(start, 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 void CleanMarked() { foreach (LinkedListNode item in deleted) { events.Remove(item); } } public IEnumerable> FromAnchor(AnchorName anchor) { LinkedListNode next = references[anchor].Next; return Enumerate(next); } public IEnumerator> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerable> Enumerate(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 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 cloner = new ParsingEventCloner(); int nesting = 0; return from e in (from e in events.FromAnchor(anchor) select e.Value).TakeWhile((ParsingEvent e) => (nesting += e.NestingIncrease) >= 0) select cloner.Clone(e); } } 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 ParsingEvent ParseStreamStart() { Token token = GetCurrentToken(); if (!(token is YamlDotNet.Core.Tokens.StreamStart streamStart)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "Did not find expected ."); } Skip(); state = ParserState.ImplicitDocumentStart; return new YamlDotNet.Core.Events.StreamStart(streamStart.Start, streamStart.End); } private ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is VersionDirective) { throw new SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token token = GetCurrentToken(); if (!isImplicit) { while (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); token = GetCurrentToken(); } } if (token == null) { throw new SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (token is YamlDotNet.Core.Tokens.Scalar && (state == ParserState.ImplicitDocumentStart || state == ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(token is VersionDirective) && !(token is TagDirective) && !(token is YamlDotNet.Core.Tokens.DocumentStart) && !(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) || token is BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new YamlDotNet.Core.Events.DocumentStart(null, tags, isImplicit: true, token.Start, token.End); } if (!(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark start = token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); VersionDirective? versionDirective = ProcessDirectives(tags2); token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(token is YamlDotNet.Core.Tokens.DocumentStart)) { throw new SemanticErrorException(token.Start, token.End, "Did not find expected ."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; Mark end = token.End; Skip(); return new YamlDotNet.Core.Events.DocumentStart(versionDirective, tags2, isImplicit: false, start, end); } if (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); } state = ParserState.StreamEnd; token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); YamlDotNet.Core.Events.StreamEnd result = new YamlDotNet.Core.Events.StreamEnd(token.Start, token.End); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } private VersionDirective? ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; VersionDirective result = null; while (true) { if (GetCurrentToken() is VersionDirective versionDirective) { if (version != null) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found duplicate %YAML directive."); } if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new SemanticErrorException(versionDirective.Start, versionDirective.End, "Found incompatible YAML document."); } result = (version = versionDirective); flag = true; } else { if (!(GetCurrentToken() is TagDirective tagDirective)) { break; } if (tags.Contains(tagDirective.Handle)) { throw new SemanticErrorException(tagDirective.Start, tagDirective.End, "Found duplicate %TAG directive."); } tags.Add(tagDirective); flag = true; } Skip(); } if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && version == null) { version = new VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) { foreach (TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentEnd || GetCurrentToken() is YamlDotNet.Core.Tokens.StreamEnd) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static ParsingEvent ProcessEmptyScalar(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 error) { throw new SemanticErrorException(error.Start, error.End, error.Value); } Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { state = states.Pop(); YamlDotNet.Core.Events.AnchorAlias result = new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); Skip(); return result; } Mark start = 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 anchor4) { throw new SemanticErrorException(anchor4.Start, anchor4.End, "While parsing a node, found more than one anchor."); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias2) { throw new SemanticErrorException(anchorAlias2.Start, 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, start, token.End); } if (token is YamlDotNet.Core.Tokens.Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tag.IsEmpty) || tag.IsNonSpecific) { isPlainImplicit = true; } else if (tag.IsEmpty) { isQuotedImplicit = true; } state = states.Pop(); Skip(); YamlDotNet.Core.Events.Scalar result2 = new YamlDotNet.Core.Events.Scalar(anchor, tag, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start, scalar.End); if (!anchor.IsEmpty && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken is Error) { Error error3 = currentToken as Error; throw new SemanticErrorException(error3.Start, error3.End, error3.Value); } } if (state == ParserState.FlowMappingKey && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { throw new SemanticErrorException(currentToken.Start, currentToken.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (token is FlowSequenceStart flowSequenceStart) { state = ParserState.FlowSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Flow, start, flowSequenceStart.End); } if (token is FlowMappingStart flowMappingStart) { state = ParserState.FlowMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start, flowMappingStart.End); } if (isBlock) { if (token is BlockSequenceStart blockSequenceStart) { state = ParserState.BlockSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start, blockSequenceStart.End); } if (token is BlockMappingStart blockMappingStart) { state = ParserState.BlockMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start, 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, start, token.End); } throw new SemanticErrorException(token.Start, token.End, "While parsing a node, did not find expected node content."); } private ParsingEvent ParseDocumentEnd() { Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; Mark start = token.Start; Mark end = start; if (token is YamlDotNet.Core.Tokens.DocumentEnd) { end = token.End; Skip(); isImplicit = false; } else if (!(currentToken is YamlDotNet.Core.Tokens.StreamEnd) && !(currentToken is YamlDotNet.Core.Tokens.DocumentStart) && !(currentToken is FlowSequenceEnd) && !(currentToken is VersionDirective) && (!(Current is YamlDotNet.Core.Events.Scalar) || !(currentToken is Error))) { throw new SemanticErrorException(start, 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 blockEntry) { Mark end = blockEntry.End; 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(end); } if (token is BlockEnd blockEnd) { state = states.Pop(); SequenceEnd result = new SequenceEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a block collection, did not find expected '-' indicator."); } private ParsingEvent ParseIndentlessSequenceEntry() { Token token = GetCurrentToken(); if (token is BlockEntry blockEntry) { Mark end = blockEntry.End; 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(end); } 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 key) { Mark end = key.End; 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(end); } if (token is Value value) { Skip(); return ProcessEmptyScalar(value.End); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { Skip(); return new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); } if (token is BlockEnd blockEnd) { state = states.Pop(); MappingEnd result = new MappingEnd(blockEnd.Start, blockEnd.End); Skip(); return result; } if (GetCurrentToken() is Error error) { throw new SyntaxErrorException(error.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 value) { Mark end = value.End; 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(end); } if (token is Error error) { throw new SemanticErrorException(error.Start, error.End, error.Value); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (!(token is FlowSequenceEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); token = GetCurrentToken(); } if (token is Key) { state = ParserState.FlowSequenceEntryMappingKey; MappingStart result = new MappingStart(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); SequenceEnd result2 = new SequenceEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); Skip(); return result2; } private ParsingEvent ParseFlowSequenceEntryMappingKey() { Token token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } Mark position = token?.End ?? Mark.Empty; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(position); } private ParsingEvent ParseFlowSequenceEntryMappingValue() { Token token = GetCurrentToken(); if (token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; Token token = GetCurrentToken(); return new MappingEnd(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty); } private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (!(token is FlowMappingEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { throw new SemanticErrorException(token?.Start ?? Mark.Empty, token?.End ?? Mark.Empty, "While parsing a flow mapping, did not find expected ',' or '}'."); } Skip(); token = GetCurrentToken(); } 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) { state = ParserState.FlowMappingKey; return ProcessEmptyScalar(token?.Start ?? Mark.Empty); } if (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; 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")] 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")] 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); } } 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 } internal class Scanner : IScanner { private const int MaxVersionNumberLength = 9; private static readonly IDictionary SimpleEscapeCodes = new SortedDictionary { { '0', '\0' }, { 'a', '\a' }, { 'b', '\b' }, { 't', '\t' }, { '\t', '\t' }, { 'n', '\n' }, { 'v', '\v' }, { 'f', '\f' }, { 'r', '\r' }, { 'e', '\u001b' }, { ' ', ' ' }, { '"', '"' }, { '\\', '\\' }, { '/', '/' }, { 'N', '\u0085' }, { '_', '\u00a0' }, { 'L', '\u2028' }, { 'P', '\u2029' } }; private readonly Stack indents = new Stack(); private readonly InsertionQueue tokens = new InsertionQueue(); private readonly Stack simpleKeys = new Stack(); private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private int flowSequenceStartLine; private int indent = -1; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; private Token? previous; private Anchor? previousAnchor; private static readonly byte[] EmptyBytes = new byte[0]; 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 == 0 && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('.') && analyzer.Check('.', 1) && analyzer.Check('.', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentIndicator() { if (!IsDocumentStart()) { return IsDocumentEnd(); } return true; } public Scanner(TextReader input, bool skipComments = true) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; } public bool MoveNext() { if (Current != null) { ConsumeCurrent(); } return MoveNextWithoutConsuming(); } public bool MoveNextWithoutConsuming() { if (!tokenAvailable && !streamEndProduced) { FetchMoreTokens(); } if (tokens.Count > 0) { Current = tokens.Dequeue(); tokenAvailable = false; return true; } Current = null; return false; } public void ConsumeCurrent() { tokensParsed++; tokenAvailable = false; previous = Current; Current = null; } private char ReadCurrentCharacter() { char result = analyzer.Peek(0); Skip(); return result; } private char ReadLine() { if (analyzer.Check("\r\n\u0085")) { SkipLine(); return '\n'; } char result = analyzer.Peek(0); SkipLine(); return result; } private void FetchMoreTokens() { while (true) { bool flag = false; if (tokens.Count == 0) { flag = true; } else { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) { flag = true; break; } } } if (!flag) { break; } FetchNextToken(); } tokenAvailable = true; } private static bool StartsWith(StringBuilder what, char start) { if (what.Length > 0) { return what[0] == start; } return false; } private void StaleSimpleKeys() { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + 1024 < cursor.Index)) { if (simpleKey.IsRequired) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a simple key, could not find expected ':'.", mark, mark)); } simpleKey.MarkAsImpossible(); } } } private void FetchNextToken() { if (!streamStartProduced) { FetchStreamStart(); return; } ScanToNextToken(); StaleSimpleKeys(); UnrollIndent(cursor.LineOffset); analyzer.Buffer.Cache(4); if (analyzer.Buffer.EndOfInput) { FetchStreamEnd(); return; } if (cursor.LineOffset == 0 && analyzer.Check('%')) { FetchDirective(); return; } if (IsDocumentStart()) { FetchDocumentIndicator(isStartToken: true); return; } if (IsDocumentEnd()) { FetchDocumentIndicator(isStartToken: false); return; } if (analyzer.Check('[')) { FetchFlowCollectionStart(isSequenceToken: true); return; } if (analyzer.Check('{')) { FetchFlowCollectionStart(isSequenceToken: false); return; } if (analyzer.Check(']')) { FetchFlowCollectionEnd(isSequenceToken: true); return; } if (analyzer.Check('}')) { FetchFlowCollectionEnd(isSequenceToken: false); return; } if (analyzer.Check(',')) { FetchFlowEntry(); return; } if (analyzer.Check('-') && analyzer.IsWhiteBreakOrZero(1)) { FetchBlockEntry(); return; } if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1))) { FetchKey(); return; } if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && (!simpleKeyAllowed || flowLevel <= 0)) { FetchValue(); return; } if (analyzer.Check('*')) { FetchAnchor(isAlias: true); return; } if (analyzer.Check('&')) { FetchAnchor(isAlias: false); return; } if (analyzer.Check('!')) { FetchTag(); return; } if (analyzer.Check('|') && flowLevel == 0) { FetchBlockScalar(isLiteral: true); return; } if (analyzer.Check('>') && flowLevel == 0) { FetchBlockScalar(isLiteral: false); return; } if (analyzer.Check('\'')) { FetchFlowScalar(isSingleQuoted: true); return; } if (analyzer.Check('"')) { FetchFlowScalar(isSingleQuoted: false); return; } if ((!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("-?:,[]{}#&*!|>'\"%@`")) || (analyzer.Check('-') && !analyzer.IsWhite(1)) || (flowLevel == 0 && analyzer.Check("?:") && !analyzer.IsWhiteBreakOrZero(1)) || (simpleKeyAllowed && flowLevel > 0 && analyzer.Check("?:"))) { if (plainScalarFollowedByComment) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning plain scalar, found a comment between adjacent scalars.", mark, mark)); } plainScalarFollowedByComment = false; FetchPlainScalar(); return; } if (simpleKeyAllowed && indent >= cursor.LineOffset && analyzer.IsTab()) { throw new SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (analyzer.IsWhiteBreakOrZero()) { Skip(); return; } Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); throw new SyntaxErrorException(start, end, "While scanning for the next token, found character that cannot start any token."); } 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('#')) { Mark mark = cursor.Mark(); Skip(); while (analyzer.IsSpace()) { Skip(); } StringBuilder stringBuilder = new StringBuilder(); while (!analyzer.IsBreakOrZero()) { stringBuilder.Append(ReadCurrentCharacter()); } if (!SkipComments) { bool isInline = previous != null && previous.End.Line == mark.Line && previous.End.Column != 1 && !(previous is YamlDotNet.Core.Tokens.StreamStart); tokens.Enqueue(new YamlDotNet.Core.Tokens.Comment(stringBuilder.ToString(), isInline, mark, cursor.Mark())); } } } private void FetchStreamStart() { simpleKeys.Push(new SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; Mark mark = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamStart(mark, mark)); } private void UnrollIndent(int column) { if (flowLevel == 0) { while (indent > column) { Mark mark = cursor.Mark(); tokens.Enqueue(new BlockEnd(mark, mark)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark mark = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(mark, mark)); } private void FetchDirective() { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } private Token? ScanDirective() { Mark start = cursor.Mark(); Skip(); string text = ScanDirectiveName(start); Token result; if (!(text == "YAML")) { if (!(text == "TAG")) { while (!analyzer.Check('#') && !analyzer.IsBreak()) { Skip(); } return null; } result = ScanTagDirectiveValue(start); } else { if (!(previous is YamlDotNet.Core.Tokens.DocumentStart) && !(previous is YamlDotNet.Core.Tokens.StreamStart) && !(previous is YamlDotNet.Core.Tokens.DocumentEnd)) { throw new SemanticErrorException(start, cursor.Mark(), "While scanning a version directive, did not find preceding ."); } result = ScanVersionDirectiveValue(start); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); } return result; } private void FetchDocumentIndicator(bool isStartToken) { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Mark mark = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentStart(mark, 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.", mark, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentEnd(mark, mark)); if (token != null) { tokens.Enqueue(token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; Mark mark = cursor.Mark(); Skip(); Token token; if (isSequenceToken) { token = new FlowSequenceStart(mark, mark); flowSequenceStartLine = token.Start.Line; } else { token = new FlowMappingStart(mark, mark); } tokens.Enqueue(token); } private void IncreaseFlowLevel() { simpleKeys.Push(new SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; Mark mark = 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 ']'.", mark, mark); } if (previous is YamlDotNet.Core.Tokens.StreamStart && flowSequenceStartLine != mark.Line) { tokens.Enqueue(new Error("While scanning a flow sequence end, found mapping key spanning across multiple lines.", mark, mark)); } item = new FlowSequenceEnd(mark, mark); } else { item = new FlowMappingEnd(mark, mark); } tokens.Enqueue(item); if (token != null) { tokens.Enqueue(token); } } 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(start, 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(start, cursor.Mark())); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); throw new SyntaxErrorException(mark, mark, "Mapping keys are not allowed in this context."); } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = flowLevel == 0; Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new Key(start, cursor.Mark())); } private void FetchValue() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible) { tokens.Insert(simpleKey.TokenNumber - tokensParsed, new Key(simpleKey.Mark, simpleKey.Mark)); RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, isSequence: false, simpleKey.Mark); simpleKey.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Mapping values are not allowed in this context.", mark, mark)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0 && simpleKey.LineOffset == 0) { tokens.Insert(tokens.Count, new Key(simpleKey.Mark, simpleKey.Mark)); flag = false; } } simpleKeyAllowed = flag; } Mark start = cursor.Mark(); Skip(); tokens.Enqueue(new Value(start, cursor.Mark())); } private void RollIndent(int column, int number, bool isSequence, Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new BlockMappingStart(position, position)) : ((Token)new BlockSequenceStart(position, 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; } StringBuilder stringBuilder = new StringBuilder(); while (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("[]{},") && (!flag || !analyzer.Check(':') || !analyzer.IsWhiteBreakOrZero(1))) { stringBuilder.Append(ReadCurrentCharacter()); } if (stringBuilder.Length == 0 || (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("?:,]}%@`"))) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning an anchor or alias, found value containing disallowed: []{},"); } AnchorName value = new AnchorName(stringBuilder.ToString()); if (isAlias) { return new YamlDotNet.Core.Tokens.AnchorAlias(value, start, cursor.Mark()); } return previousAnchor = new Anchor(value, start, cursor.Mark()); } private void FetchTag() { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanTag()); } private Token ScanTag() { Mark start = cursor.Mark(); string text; string text2; if (analyzer.Check('<', 1)) { text = string.Empty; Skip(); Skip(); text2 = ScanTagUri(null, start); if (!analyzer.Check('>')) { throw new SyntaxErrorException(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(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) { RemoveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private Token ScanBlockScalar(bool isLiteral) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); int num = 0; int num2 = 0; int currentIndent = 0; bool flag = false; bool? isFirstLine = null; Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { throw new SyntaxErrorException(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(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(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(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, stringBuilder3, isLiteral, ref end, ref isFirstLine); isFirstLine = false; while (cursor.LineOffset == currentIndent && !analyzer.IsZero() && !IsDocumentEnd()) { bool flag2 = analyzer.IsWhite(); if (!isLiteral && StartsWith(stringBuilder2, '\n') && !flag && !flag2) { if (stringBuilder3.Length == 0) { stringBuilder.Append(' '); } stringBuilder2.Length = 0; } else { stringBuilder.Append(stringBuilder2.ToString()); stringBuilder2.Length = 0; } stringBuilder.Append(stringBuilder3.ToString()); stringBuilder3.Length = 0; flag = analyzer.IsWhite(); while (!analyzer.IsBreakOrZero()) { stringBuilder.Append(ReadCurrentCharacter()); } char c = ReadLine(); if (c != 0) { stringBuilder2.Append(c); } currentIndent = ScanBlockScalarBreaks(currentIndent, stringBuilder3, isLiteral, ref end, ref isFirstLine); } if (num != -1) { stringBuilder.Append((object?)stringBuilder2); } if (num == 1) { stringBuilder.Append((object?)stringBuilder3); } ScalarStyle style = (isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded); return new YamlDotNet.Core.Tokens.Scalar(stringBuilder.ToString(), style, start, end); } private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { int num = 0; int num2 = -1; end = cursor.Mark(); while (true) { if ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) { Skip(); continue; } if (cursor.LineOffset > num) { num = cursor.LineOffset; } if (!analyzer.IsBreak()) { break; } if (isFirstLine == true) { isFirstLine = false; num2 = cursor.LineOffset; } breaks.Append(ReadLine()); end = cursor.Mark(); } if (isLiteral && isFirstLine == true) { int num3 = cursor.LineOffset; int num4 = 0; while (!analyzer.IsBreak(num4) && analyzer.IsSpace(num4)) { num4++; num3++; } if (analyzer.IsBreak(num4) && num3 > cursor.LineOffset) { isFirstLine = false; num2 = num3; } } if (isLiteral && num2 > 1 && currentIndent < num2 - 1) { throw new SemanticErrorException(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(end, cursor.Mark(), "While scanning a literal block scalar, found more spaces in lines above first content line."); } if (currentIndent == 0 && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1)); } return currentIndent; } private void FetchFlowScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanFlowScalar(isSingleQuoted)); if (!isSingleQuoted && analyzer.Check('#')) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", mark, mark)); } } private Token ScanFlowScalar(bool isSingleQuoted) { Mark start = cursor.Mark(); Skip(); StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); StringBuilder stringBuilder4 = new StringBuilder(); bool flag = false; while (true) { if (IsDocumentIndicator()) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { throw new SyntaxErrorException(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)) { stringBuilder.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)) { stringBuilder.Append(value); break; } throw new SyntaxErrorException(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(start, cursor.Mark(), "While scanning a quoted scalar, did not find expected hexadecimal number."); } num2 = (num2 << 4) + analyzer.AsHex(i); } if ((num2 >= 55296 && num2 <= 57343) || num2 > 1114111) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a quoted scalar, found invalid Unicode character escape code."); } stringBuilder.Append(char.ConvertFromUtf32(num2)); for (int j = 0; j < num; j++) { Skip(); } } else { stringBuilder.Append(ReadCurrentCharacter()); } } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (!flag) { stringBuilder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else if (!flag) { stringBuilder2.Length = 0; stringBuilder3.Append(ReadLine()); flag = true; } else { stringBuilder4.Append(ReadLine()); } } if (flag) { if (StartsWith(stringBuilder3, '\n')) { if (stringBuilder4.Length == 0) { stringBuilder.Append(' '); } else { stringBuilder.Append(stringBuilder4.ToString()); } } else { stringBuilder.Append(stringBuilder3.ToString()); stringBuilder.Append(stringBuilder4.ToString()); } stringBuilder3.Length = 0; stringBuilder4.Length = 0; } else { stringBuilder.Append(stringBuilder2.ToString()); stringBuilder2.Length = 0; } } Skip(); return new YamlDotNet.Core.Tokens.Scalar(stringBuilder.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); } private void FetchPlainScalar() { SaveSimpleKey(); simpleKeyAllowed = false; bool isMultiline = false; YamlDotNet.Core.Tokens.Scalar item = 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) { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = new StringBuilder(); StringBuilder stringBuilder3 = new StringBuilder(); StringBuilder stringBuilder4 = new StringBuilder(); bool flag = false; int num = indent + 1; Mark mark = cursor.Mark(); Mark end = mark; 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 || stringBuilder2.Length > 0) { if (flag) { if (StartsWith(stringBuilder3, '\n')) { if (stringBuilder4.Length == 0) { stringBuilder.Append(' '); } else { stringBuilder.Append((object?)stringBuilder4); } } else { stringBuilder.Append((object?)stringBuilder3); stringBuilder.Append((object?)stringBuilder4); } stringBuilder3.Length = 0; stringBuilder4.Length = 0; flag = false; } else { stringBuilder.Append((object?)stringBuilder2); stringBuilder2.Length = 0; } } if (flowLevel > 0 && cursor.LineOffset < num) { throw new Exception(); } stringBuilder.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(mark, cursor.Mark(), "While scanning a plain scalar, found a tab character that violate indentation."); } if (!flag) { stringBuilder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else { isMultiline = true; if (!flag) { stringBuilder2.Length = 0; stringBuilder3.Append(ReadLine()); flag = true; } else { stringBuilder4.Append(ReadLine()); } } } if (flowLevel == 0 && cursor.LineOffset < num) { break; } } if (flag) { simpleKeyAllowed = true; } return new YamlDotNet.Core.Tokens.Scalar(stringBuilder.ToString(), ScalarStyle.Plain, mark, end); } 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(Mark start) { StringBuilder stringBuilder = new StringBuilder(); while (analyzer.IsAlphaNumericDashOrUnderscore()) { stringBuilder.Append(ReadCurrentCharacter()); } if (stringBuilder.Length == 0) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, could not find expected directive name."); } if (!analyzer.IsWhiteBreakOrZero()) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a directive, found unexpected non-alphabetical character."); } return stringBuilder.ToString(); } private void SkipWhitespaces() { while (analyzer.IsWhite()) { Skip(); } } private Token ScanVersionDirectiveValue(Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(start); if (!analyzer.Check('.')) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a %YAML directive, did not find expected digit or '.' character."); } Skip(); int minor = ScanVersionDirectiveNumber(start); return new VersionDirective(new Version(major, minor), start, start); } private Token ScanTagDirectiveValue(Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { throw new SyntaxErrorException(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(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) { StringBuilder stringBuilder = new StringBuilder(); if (head != null && head.Length > 1) { stringBuilder.Append(head.Substring(1)); } while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$.!~*'()[]%") || (analyzer.Check(',') && !analyzer.IsBreak(1))) { if (analyzer.Check('%')) { stringBuilder.Append(ScanUriEscapes(start)); } else if (analyzer.Check('+')) { stringBuilder.Append(' '); Skip(); } else { stringBuilder.Append(ReadCurrentCharacter()); } } if (stringBuilder.Length == 0) { return string.Empty; } return stringBuilder.ToString(); } private string ScanUriEscapes(Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { throw new SyntaxErrorException(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(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(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(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(start, cursor.Mark(), "While scanning a tag, did not find expected '!'."); } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(ReadCurrentCharacter()); while (analyzer.IsAlphaNumericDashOrUnderscore()) { stringBuilder.Append(ReadCurrentCharacter()); } if (analyzer.Check('!')) { stringBuilder.Append(ReadCurrentCharacter()); } else if (isDirective && (stringBuilder.Length != 1 || stringBuilder[0] != '!')) { throw new SyntaxErrorException(start, cursor.Mark(), "While scanning a tag directive, did not find expected '!'."); } return stringBuilder.ToString(); } private int ScanVersionDirectiveNumber(Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { throw new SyntaxErrorException(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(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(Mark start, Mark end, string message) : base(start, 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 int Index => cursor.Index; public int Line => cursor.Line; public int LineOffset => cursor.LineOffset; public Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public SimpleKey() { cursor = new Cursor(); } public SimpleKey(bool isRequired, int tokenNumber, Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new Cursor(cursor); } } internal sealed class StringLookAheadBuffer : ILookAheadBuffer { private readonly string value; public int Position { get; private set; } public int Length => value.Length; public bool EndOfInput => IsOutside(Position); public StringLookAheadBuffer(string value) { this.value = value; } public char Peek(int offset) { int index = Position + offset; if (!IsOutside(index)) { return value[index]; } return '\0'; } private bool IsOutside(int index) { return index >= value.Length; } public void Skip(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } Position += length; } } internal sealed class SyntaxErrorException : YamlException { public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(Mark start, Mark end, string message) : base(start, 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 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(Mark.Empty, Mark.Empty, message) { } public YamlException(Mark start, Mark end, string message) : this(start, end, message, null) { } public YamlException(Mark start, Mark end, string message, Exception? innerException) : base($"({start}) - ({end}): {message}", innerException) { Start = start; End = end; } public YamlException(string message, Exception inner) : this(Mark.Empty, Mark.Empty, message, inner) { } } } 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(start, 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(start, end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class BlockEnd : Token { public BlockEnd() : this(Mark.Empty, Mark.Empty) { } public BlockEnd(Mark start, Mark end) : base(start, end) { } } internal sealed class BlockEntry : Token { public BlockEntry() : this(Mark.Empty, Mark.Empty) { } public BlockEntry(Mark start, Mark end) : base(start, end) { } } internal sealed class BlockMappingStart : Token { public BlockMappingStart() : this(Mark.Empty, Mark.Empty) { } public BlockMappingStart(Mark start, Mark end) : base(start, end) { } } internal sealed class BlockSequenceStart : Token { public BlockSequenceStart() : this(Mark.Empty, Mark.Empty) { } public BlockSequenceStart(Mark start, Mark end) : base(start, 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(start, end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class DocumentEnd : Token { public DocumentEnd() : this(Mark.Empty, Mark.Empty) { } public DocumentEnd(Mark start, Mark end) : base(start, end) { } } internal sealed class DocumentStart : Token { public DocumentStart() : this(Mark.Empty, Mark.Empty) { } public DocumentStart(Mark start, Mark end) : base(start, end) { } } internal class Error : Token { internal string Value { get; } internal Error(string value, Mark start, Mark end) : base(start, end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(Mark.Empty, Mark.Empty) { } public FlowEntry(Mark start, Mark end) : base(start, end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(Mark.Empty, Mark.Empty) { } public FlowMappingEnd(Mark start, Mark end) : base(start, end) { } } internal sealed class FlowMappingStart : Token { public FlowMappingStart() : this(Mark.Empty, Mark.Empty) { } public FlowMappingStart(Mark start, Mark end) : base(start, end) { } } internal sealed class FlowSequenceEnd : Token { public FlowSequenceEnd() : this(Mark.Empty, Mark.Empty) { } public FlowSequenceEnd(Mark start, Mark end) : base(start, end) { } } internal sealed class FlowSequenceStart : Token { public FlowSequenceStart() : this(Mark.Empty, Mark.Empty) { } public FlowSequenceStart(Mark start, Mark end) : base(start, end) { } } internal sealed class Key : Token { public Key() : this(Mark.Empty, Mark.Empty) { } public Key(Mark start, Mark end) : base(start, end) { } } internal sealed class Scalar : Token { 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(start, end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class StreamEnd : Token { public StreamEnd() : this(Mark.Empty, Mark.Empty) { } public StreamEnd(Mark start, Mark end) : base(start, end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(Mark.Empty, Mark.Empty) { } public StreamStart(Mark start, Mark end) : base(start, 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(start, 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(start, 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(Mark start, Mark end) { Start = start ?? throw new ArgumentNullException("start"); End = end ?? throw new ArgumentNullException("end"); } } internal sealed class Value : Token { public Value() : this(Mark.Empty, Mark.Empty) { } public Value(Mark start, Mark end) : base(start, 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(start, 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.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(start, end) { if (value.IsEmpty) { throw new YamlException(start, 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(start, 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(start, 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(start, 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(Mark start, 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(Mark start, Mark end) : base(start, end) { } public MappingEnd() : this(Mark.Empty, 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(start, 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(Mark start, Mark end) { Start = start ?? throw new ArgumentNullException("start"); End = end ?? throw new ArgumentNullException("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 Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; } 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(Mark start, Mark end) : base(start, end) { } public SequenceEnd() : this(Mark.Empty, 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(Mark start, Mark end) : base(start, end) { } public StreamEnd() : this(Mark.Empty, 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(Mark.Empty, Mark.Empty) { } public StreamStart(Mark start, Mark end) : base(start, end) { } public override string ToString() { return "Stream start"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } }