Decompiled source of JSONCardLoader v2.5.4

JSONLoader.dll

Decompiled 4 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using APIPlugin;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using DiskCardGame;
using HarmonyLib;
using InscryptionAPI.Ascension;
using InscryptionAPI.Card;
using InscryptionAPI.Encounters;
using InscryptionAPI.Guid;
using InscryptionAPI.Helpers;
using InscryptionAPI.Localizing;
using InscryptionAPI.Masks;
using InscryptionAPI.Regions;
using InscryptionAPI.Saves;
using InscryptionAPI.Sound;
using InscryptionAPI.TalkingCards;
using InscryptionAPI.TalkingCards.Animation;
using InscryptionAPI.TalkingCards.Create;
using InscryptionAPI.TalkingCards.Helpers;
using InscryptionAPI.Triggers;
using JLPlugin;
using JLPlugin.ConfigilFunctions;
using JLPlugin.Data;
using JLPlugin.Hotkeys;
using JLPlugin.SigilCode;
using JLPlugin.Utils;
using JLPlugin.V2.Data;
using JSONLoader.Data;
using JSONLoader.Data.TalkingCards;
using JSONLoader.V2Code;
using Microsoft.CodeAnalysis;
using MonoMod.Utils;
using NCalc;
using PanoramicData.NCalcExtensions;
using TMPro;
using TinyJson;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("JSONLoader")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("JSON Loader")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0")]
[assembly: AssemblyProduct("JSONLoader")]
[assembly: AssemblyTitle("JSONLoader")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("2.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
public static class ImportExportUtils
{
	private static string ID;

	private static string DebugPath;

	private static string LoggingSuffix;

	public static void SetID(string id)
	{
		ID = id;
	}

	public static void SetDebugPath(string path)
	{
		DebugPath = path.Substring(Plugin.BepInExDirectory.Length);
		LoggingSuffix = "";
	}

	public static T ParseEnum<T>(string value) where T : unmanaged, Enum
	{
		if (Enum.TryParse<T>(value, out var result))
		{
			return result;
		}
		int num = Math.Max(value.LastIndexOf('_'), value.LastIndexOf('.'));
		if (num < 0)
		{
			throw new InvalidCastException("Cannot parse " + value + " as " + typeof(T).FullName);
		}
		string text = value.Substring(0, num);
		string text2 = value.Substring(num + 1);
		return GuidManager.GetEnumValue<T>(text, text2);
	}

	public static void ApplyProperty<T, Y>(Func<T> getter, Action<T> setter, ref Y serializeInfoValue, bool toCardInfo, string category, string suffix)
	{
		if (toCardInfo)
		{
			T a = default(T);
			ApplyValue(ref a, ref serializeInfoValue, toA: true, category, suffix);
			setter(a);
		}
		else
		{
			T a2 = getter();
			ApplyValue(ref a2, ref serializeInfoValue, toA: false, category, suffix);
		}
	}

	public static void ApplyProperty<T, Y>(ref T serializeInfoValue, Func<Y> getter, Action<Y> setter, bool toCardInfo, string category, string suffix)
	{
		if (toCardInfo)
		{
			Y b = getter();
			ApplyValue(ref serializeInfoValue, ref b, toA: false, category, suffix);
		}
		else
		{
			Y b2 = default(Y);
			ApplyValue(ref serializeInfoValue, ref b2, toA: true, category, suffix);
			setter(b2);
		}
	}

	public static void ApplyValue<T, Y>(ref T a, ref Y b, bool toA, string category, string suffix)
	{
		if (toA)
		{
			ConvertValue(ref b, ref a, category, suffix);
		}
		else
		{
			ConvertValue(ref a, ref b, category, suffix);
		}
	}

	private static void ConvertValue<FromType, ToType>(ref FromType from, ref ToType to, string category, string suffix)
	{
		//IL_0882: Unknown result type (might be due to invalid IL or missing references)
		//IL_0889: Expected O, but got Unknown
		//IL_099b: Unknown result type (might be due to invalid IL or missing references)
		//IL_09a2: Expected O, but got Unknown
		LoggingSuffix = suffix;
		Type typeFromHandle = typeof(FromType);
		Type typeFromHandle2 = typeof(ToType);
		try
		{
			if (typeFromHandle == typeFromHandle2)
			{
				to = (ToType)(object)from;
				return;
			}
			if (AreNullableTypesEqual(from, to, out var a2, out var _, out var aHasValue, out var _))
			{
				if (aHasValue)
				{
					to = (ToType)a2;
				}
				return;
			}
			if (typeFromHandle.IsGenericType && typeFromHandle.GetGenericTypeDefinition() == typeof(List<>) && typeFromHandle2.IsGenericType && typeFromHandle2.GetGenericTypeDefinition() == typeof(List<>))
			{
				if (from != null)
				{
					IList list = (IList)Activator.CreateInstance(typeFromHandle2);
					to = (ToType)list;
					IList list2 = (IList)(object)from;
					for (int i = 0; i < list2.Count; i++)
					{
						object o = list2[i];
						object @default = GetDefault(typeFromHandle2.GetGenericArguments().Single());
						object value = ConvertType(typeFromHandle, typeFromHandle2, o, @default, category, $"{suffix}_{i + 1}");
						list.Add(value);
					}
				}
				return;
			}
			if (typeFromHandle.IsGenericType && typeFromHandle.GetGenericTypeDefinition() == typeof(List<>) && typeFromHandle2.IsArray)
			{
				if (from != null)
				{
					IList list3 = (IList)(object)from;
					int length = ((from != null) ? list3.Count : 0);
					Array array = Array.CreateInstance(typeFromHandle2.GetElementType(), length);
					to = (ToType)(object)array;
					for (int j = 0; j < list3.Count; j++)
					{
						object obj = list3[j];
						object default2 = GetDefault(typeFromHandle2.GetElementType());
						object[] array2 = new object[4]
						{
							obj,
							default2,
							category,
							$"{suffix}_{j + 1}"
						};
						MethodInfo methodInfo = typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeFromHandle.GetGenericArguments().Single(), typeFromHandle2.GetElementType());
						methodInfo.Invoke(null, array2);
						array.SetValue(array2[1], j);
					}
				}
				return;
			}
			if (typeFromHandle.IsArray && typeFromHandle2.IsGenericType && typeFromHandle2.GetGenericTypeDefinition() == typeof(List<>))
			{
				if (from != null)
				{
					IList list4 = (IList)Activator.CreateInstance(typeFromHandle2);
					to = (ToType)list4;
					Array array3 = (Array)(object)from;
					for (int k = 0; k < array3.Length; k++)
					{
						object value2 = array3.GetValue(k);
						object default3 = GetDefault(typeFromHandle2.GetGenericArguments().Single());
						object[] array4 = new object[4]
						{
							value2,
							default3,
							category,
							$"{suffix}_{k + 1}"
						};
						MethodInfo methodInfo2 = typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(typeFromHandle.GetElementType(), typeFromHandle2.GetGenericArguments().Single());
						methodInfo2.Invoke(null, array4);
						list4.Add(array4[1]);
					}
				}
				return;
			}
			if (typeFromHandle.IsEnum && typeFromHandle2 == typeof(string))
			{
				string text = from.ToString();
				if (int.TryParse(text, out var result))
				{
					object[] array5 = new object[3] { result, "guid", "name" };
					MethodInfo methodInfo3 = typeof(GuidManager).GetMethod("TryGetGuidAndKeyEnumValue", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeFromHandle);
					if ((bool)methodInfo3.Invoke(null, array5))
					{
						string text2 = (string)array5[1];
						string text3 = (string)array5[2];
						to = (ToType)(object)(text2 + "_" + text3);
					}
					else
					{
						Error($"Failed to convert enum to string! '{from}'");
						to = (ToType)(object)text;
					}
				}
				else
				{
					to = (ToType)(object)text;
				}
				return;
			}
			if (typeFromHandle == typeof(string) && typeFromHandle2.IsEnum)
			{
				if (!string.IsNullOrEmpty((string)(object)from))
				{
					object obj2 = typeof(ImportExportUtils).GetMethod("ParseEnum", BindingFlags.Static | BindingFlags.Public).MakeGenericMethod(typeFromHandle2).Invoke(null, new object[1] { from });
					to = (ToType)obj2;
				}
				return;
			}
			if (typeFromHandle == typeof(CardInfo) && typeFromHandle2 == typeof(string))
			{
				if (from != null)
				{
					object obj3 = from;
					to = (ToType)(object)((Object)((obj3 is CardInfo) ? obj3 : null)).name;
				}
				return;
			}
			if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(CardInfo))
			{
				string text4 = (string)(object)from;
				if (text4 != null)
				{
					text4 = text4.Trim();
				}
				if (string.IsNullOrEmpty(text4))
				{
					return;
				}
				to = (ToType)(object)CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.AllCardsCopy, text4);
				if (to != null)
				{
					return;
				}
				CardInfo[] array6 = FindSimilarCards(text4);
				if (array6.Length == 0)
				{
					string text5 = string.Join(", ", CardManager.AllCardsCopy.Select((CardInfo c) => ((Object)c).name));
					Error("Could not find CardInfo with name '" + text4 + "'!\nAllCards: " + text5);
					return;
				}
				to = (ToType)(object)array6[0];
				string text6 = string.Join(" or ", array6.Select((CardInfo a) => "'" + ((Object)a).name + "'"));
				Warning("Could not find CardInfo with name '" + text4 + "'. Did you mean " + text6 + "?");
				return;
			}
			if (typeFromHandle == typeof(string) && (typeFromHandle2 == typeof(Texture) || typeFromHandle2.IsSubclassOf(typeof(Texture))))
			{
				string text7 = (string)(object)from;
				if (!string.IsNullOrEmpty(text7))
				{
					try
					{
						to = (ToType)(object)TextureHelper.GetImageAsTexture(text7, (FilterMode)0);
						return;
					}
					catch (FileNotFoundException)
					{
						Error("Failed to find texture " + text7 + "!");
						return;
					}
				}
				return;
			}
			if ((typeFromHandle == typeof(Texture) || typeFromHandle.IsSubclassOf(typeof(Texture))) && typeFromHandle2 == typeof(string))
			{
				Texture val = (Texture)(object)from;
				if ((Object)(object)val != (Object)null)
				{
					string path = Path.Combine(Plugin.ExportDirectory, category, "Assets", ID + "_" + suffix + ".png");
					to = (ToType)(object)ExportTexture(val, path);
				}
				return;
			}
			if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(Sprite))
			{
				string text8 = (string)(object)from;
				if (!string.IsNullOrEmpty(text8))
				{
					Texture2D imageAsTexture = TextureHelper.GetImageAsTexture(text8, (FilterMode)0);
					if ((Object)(object)imageAsTexture != (Object)null)
					{
						to = (ToType)(object)TextureHelper.ConvertTexture(imageAsTexture, (Vector2?)null);
					}
				}
				return;
			}
			if (typeFromHandle == typeof(Sprite) && typeFromHandle2 == typeof(string))
			{
				Sprite val2 = (Sprite)(object)from;
				if ((Object)(object)val2 != (Object)null)
				{
					string path2 = Path.Combine(Plugin.ExportDirectory, category, "Assets", ID + "_" + suffix + ".png");
					to = (ToType)(object)ExportTexture(val2.texture, path2);
				}
				return;
			}
			if (typeFromHandle.GetInterfaces().Contains(typeof(IConvertible)) && typeFromHandle2.GetInterfaces().Contains(typeof(IConvertible)))
			{
				IConvertible convertible = from as IConvertible;
				IConvertible convertible2 = to as IConvertible;
				if (convertible != null && convertible2 != null)
				{
					to = (ToType)Convert.ChangeType(convertible, typeFromHandle2);
				}
				return;
			}
			if (typeFromHandle == typeof(JSONParser.LocalizableField) && typeFromHandle2 == typeof(string))
			{
				Error("Use ApplyLocaleField when converted from LocalizableField to string!");
			}
			else if (typeFromHandle == typeof(string) && typeFromHandle2 == typeof(JSONParser.LocalizableField))
			{
				Error("Use ApplyLocaleField when converted from string to LocalizableField!");
			}
		}
		catch (Exception e)
		{
			Error($"Failed to convert: {typeFromHandle} to {typeFromHandle2}");
			Exception(e);
			return;
		}
		Error($"Unsupported conversion type: {typeFromHandle} to {typeFromHandle2}\n{Environment.StackTrace}");
	}

	private static CardInfo[] FindSimilarCards(string misspelledCardName)
	{
		List<Tuple<int, CardInfo>> list = new List<Tuple<int, CardInfo>>();
		string text = misspelledCardName.ToLower().Replace("-", "").Replace("_", "");
		int num = Mathf.Clamp(text.Length - 1, 1, 4);
		foreach (CardInfo item in CardManager.AllCardsCopy)
		{
			string text2 = ((Object)item).name.ToLower().Replace("-", "").Replace("_", "");
			if (Mathf.Abs(text.Length - text2.Length) > num)
			{
				continue;
			}
			int num2 = 0;
			int num3 = Mathf.Max(0, text.Length - text2.Length);
			int num4 = text2.Length - 1;
			int num5 = text.Length - 1;
			while (num5 >= 0 && num4 >= 0)
			{
				if (text2[num4] == text[num5])
				{
					num2++;
				}
				else
				{
					num3++;
					if (num3 > num)
					{
						break;
					}
					if (num4 > 0 && text2[num4 - 1] == text[num5])
					{
						num4--;
						num2++;
					}
					else if (num5 > 0 && text2[num4] == text[num5 - 1])
					{
						num5--;
						num2++;
					}
				}
				num5--;
				num4--;
			}
			if (num2 > 0 && num3 < num)
			{
				list.Add(new Tuple<int, CardInfo>(num2, item));
			}
		}
		list.Sort((Tuple<int, CardInfo> a, Tuple<int, CardInfo> b) => b.Item1 - a.Item1);
		return list.Select((Tuple<int, CardInfo> a) => a.Item2).ToArray();
	}

	private static object ConvertType(Type fromType, Type toType, object o1, object o2, string category, string suffix)
	{
		object[] array = new object[4] { o1, o2, category, suffix };
		MethodInfo methodInfo = typeof(ImportExportUtils).GetMethod("ConvertValue", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(fromType.GetGenericArguments().Single(), toType.GetGenericArguments().Single());
		methodInfo.Invoke(null, array);
		return array[1];
	}

	private static bool AreNullableTypesEqual<T, Y>(T t, Y y, out object a, out object b, out bool aHasValue, out bool bHasValue)
	{
		aHasValue = false;
		bHasValue = false;
		a = null;
		b = null;
		bool flag = typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(Nullable<>);
		bool flag2 = typeof(Y).IsGenericType && typeof(Y).GetGenericTypeDefinition() == typeof(Nullable<>);
		if (!flag && !flag2)
		{
			return false;
		}
		Type type = (flag ? Nullable.GetUnderlyingType(typeof(T)) : typeof(T));
		Type type2 = (flag2 ? Nullable.GetUnderlyingType(typeof(Y)) : typeof(Y));
		if (type == type2)
		{
			if (flag)
			{
				a = GetValueFromNullable(t, out aHasValue);
			}
			else
			{
				a = t;
				aHasValue = true;
			}
			if (flag2)
			{
				b = GetValueFromNullable(y, out bHasValue);
			}
			else
			{
				b = y;
				bHasValue = true;
			}
			return true;
		}
		Error($"Not same types {typeof(T)} {typeof(Y)}");
		return false;
	}

	private static string ExportTexture(Texture texture, string path)
	{
		Texture2D val = (Texture2D)(object)((texture is Texture2D) ? texture : null);
		if (val != null)
		{
			return ExportTexture(val, path);
		}
		Texture2D texture2 = Texture2D.CreateExternalTexture(texture.width, texture.height, (TextureFormat)4, false, false, texture.GetNativeTexturePtr());
		return ExportTexture(texture2, path);
	}

	private static string ExportTexture(Texture2D texture, string path)
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0050: Expected O, but got Unknown
		//IL_006a: Unknown result type (might be due to invalid IL or missing references)
		if (!((Texture)texture).isReadable)
		{
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)1);
			Graphics.Blit((Texture)(object)texture, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height);
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			texture = val;
		}
		byte[] array = ImageConversion.EncodeToPNG(texture);
		if (array == null)
		{
			Error("Failed to turn into bytes??");
		}
		if (string.IsNullOrEmpty(path))
		{
			Error("path is empty????");
		}
		string directoryName = Path.GetDirectoryName(path);
		if (!Directory.Exists(directoryName))
		{
			Directory.CreateDirectory(directoryName);
		}
		File.WriteAllBytes(path, array);
		return Path.GetFileName(path);
	}

	public static string[] ExportTextures(IEnumerable<Texture2D> texture, string type, string fileName)
	{
		int num = 0;
		List<string> list = new List<string>();
		foreach (Texture2D item in texture)
		{
			num++;
			string path = Path.Combine(Plugin.ExportDirectory, type, "Assets", $"{fileName}_{num}.png");
			list.Add(ExportTexture(item, path));
		}
		return list.ToArray();
	}

	public static void ApplyLocaleField(string field, ref JSONParser.LocalizableField rows, ref string cardInfoEnglishField, bool toCardInfo)
	{
		if (toCardInfo)
		{
			ApplyLocaleField(field, rows, ref cardInfoEnglishField);
			return;
		}
		string text = cardInfoEnglishField;
		cardInfoEnglishField = text;
		ImportLocaleField(rows, cardInfoEnglishField);
	}

	private static void ImportLocaleField(JSONParser.LocalizableField rows, string cardInfoEnglishField)
	{
		//IL_0065: 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)
		rows.rows.Clear();
		rows.Initialize(cardInfoEnglishField);
		Translation val = Localization.Translations.Find((Translation a) => a.englishStringFormatted == cardInfoEnglishField);
		if (val != null)
		{
			foreach (KeyValuePair<Language, string> value in val.values)
			{
				string text = LocalizationManager.LanguageToCode(value.Key);
				rows.SetValue(rows.englishFieldName + "_" + text, value.Value);
				VerboseLog($"Loaded {cardInfoEnglishField} translation for {text} => {value.Key}");
			}
			return;
		}
		VerboseLog("ApplyLocaleField could not find any translations from english '" + cardInfoEnglishField + "'");
	}

	private static void ApplyLocaleField(string field, JSONParser.LocalizableField rows, ref string cardInfoEnglishField)
	{
		//IL_0127: Unknown result type (might be due to invalid IL or missing references)
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0132: Invalid comparison between Unknown and I4
		//IL_014d: Unknown result type (might be due to invalid IL or missing references)
		if (rows.rows.TryGetValue(rows.englishFieldName, out var value))
		{
			cardInfoEnglishField = value;
		}
		else
		{
			if (rows.rows.Count <= 0)
			{
				return;
			}
			cardInfoEnglishField = rows.rows.First().Value;
		}
		VerboseLog("ApplyLocaleField " + field + " english " + cardInfoEnglishField);
		foreach (KeyValuePair<string, string> row in rows.rows)
		{
			if (row.Key == rows.englishFieldName)
			{
				continue;
			}
			int num = row.Key.LastIndexOf("_", StringComparison.Ordinal);
			if (num < 0)
			{
				VerboseError("Could not find _ of key " + row.Key + " in field " + field + "!");
				continue;
			}
			int length = row.Key.Length - num - 1;
			string text = row.Key.Substring(num + 1, length);
			Language val = LocalizationManager.CodeToLanguage(text);
			if ((int)val != 12)
			{
				LocalizationManager.Translate("MADH.inscryption.JSONLoader", (string)null, cardInfoEnglishField, row.Value, val);
				VerboseLog("Translation " + cardInfoEnglishField + " to " + text + " = " + row.Value);
			}
			else
			{
				Error("Unknown language code " + text + " for card " + cardInfoEnglishField + " in field " + field);
			}
		}
	}

	private static object GetValueFromNullable<U>(U u, out bool hasValue)
	{
		Type typeFromHandle = typeof(U);
		if (u != null && (bool)typeFromHandle.GetProperty("HasValue", BindingFlags.Instance | BindingFlags.Public).GetValue(u))
		{
			hasValue = true;
			return typeFromHandle.GetProperty("Value", BindingFlags.Instance | BindingFlags.Public).GetValue(u);
		}
		hasValue = false;
		Type underlyingType = Nullable.GetUnderlyingType(typeFromHandle);
		if (underlyingType.IsValueType)
		{
			return Activator.CreateInstance(underlyingType);
		}
		return null;
	}

	private static object GetDefault(Type type)
	{
		if (type.IsValueType)
		{
			return Activator.CreateInstance(type);
		}
		return null;
	}

	private static void VerboseLog(string message)
	{
		Plugin.VerboseLog("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message);
	}

	private static void VerboseWarning(string message)
	{
		if (Configs.VerboseLogging)
		{
			Plugin.VerboseWarning("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message);
		}
	}

	private static void VerboseError(string message)
	{
		if (Configs.VerboseLogging)
		{
			Plugin.VerboseError("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + message);
		}
	}

	private static void Warning(string message)
	{
		if (Configs.VerboseLogging)
		{
			VerboseWarning(message);
			return;
		}
		Plugin.Log.LogWarning((object)("[" + ID + "][" + LoggingSuffix + "] " + message));
	}

	private static void Error(string message)
	{
		if (Configs.VerboseLogging)
		{
			VerboseError(message);
			return;
		}
		Plugin.Log.LogError((object)("[" + ID + "][" + LoggingSuffix + "] " + message));
	}

	private static void Exception(Exception e)
	{
		Plugin.Log.LogError((object)("[" + DebugPath + "][" + ID + "][" + LoggingSuffix + "] " + e.Message + "\n" + e.StackTrace));
	}
}
namespace TinyJson
{
	public static class JSONParser
	{
		public interface IFlexibleField
		{
			bool ContainsKey(string key);

			void SetValue(string key, string value);

			string ToJSON();
		}

		public interface IInitializable
		{
			void Initialize();
		}

		[Serializable]
		public class LocalizableField : IFlexibleField
		{
			public Dictionary<string, string> rows;

			public string englishFieldName;

			public LocalizableField(string EnglishFieldName)
			{
				rows = new Dictionary<string, string>();
				englishFieldName = EnglishFieldName;
			}

			public void Initialize(string englishValue)
			{
				rows[englishFieldName] = englishValue;
			}

			public bool ContainsKey(string key)
			{
				return key.StartsWith(englishFieldName);
			}

			public void SetValue(string key, string value)
			{
				rows[key] = value;
			}

			public string ToJSON()
			{
				string text = "";
				foreach (KeyValuePair<string, string> row in rows)
				{
					text = text + "\t\"" + row.Key + "\": \"" + row.Value + "\",\n";
				}
				return text;
			}

			public override string ToString()
			{
				return rows.ToString();
			}
		}

		[ThreadStatic]
		private static Stack<List<string>> splitArrayPool;

		[ThreadStatic]
		private static StringBuilder stringBuilder;

		[ThreadStatic]
		private static Dictionary<Type, Dictionary<string, FieldInfo>> fieldInfoCache;

		[ThreadStatic]
		private static Dictionary<Type, Dictionary<string, PropertyInfo>> propertyInfoCache;

		[ThreadStatic]
		private static Dictionary<Type, FieldInfo[]> publicFieldInfoCache;

		public static T FromJson<T>(this string json)
		{
			if (propertyInfoCache == null)
			{
				propertyInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
			}
			if (fieldInfoCache == null)
			{
				fieldInfoCache = new Dictionary<Type, Dictionary<string, FieldInfo>>();
			}
			if (stringBuilder == null)
			{
				stringBuilder = new StringBuilder();
			}
			if (splitArrayPool == null)
			{
				splitArrayPool = new Stack<List<string>>();
			}
			if (publicFieldInfoCache == null)
			{
				publicFieldInfoCache = new Dictionary<Type, FieldInfo[]>();
			}
			stringBuilder.Length = 0;
			for (int i = 0; i < json.Length; i++)
			{
				char c = json[i];
				switch (c)
				{
				case '"':
					i = AppendUntilStringEnd(appendEscapeCharacter: true, i, json);
					continue;
				case '/':
					if (i + 1 != json.Length && json[i + 1] == '/')
					{
						i = SkipUntilLineEnd(i, json);
						continue;
					}
					break;
				}
				if (!char.IsWhiteSpace(c))
				{
					stringBuilder.Append(c);
				}
			}
			return (T)ParseValue(typeof(T), stringBuilder.ToString());
		}

		private static int SkipUntilLineEnd(int startIdx, string json)
		{
			for (int i = startIdx + 2; i < json.Length; i++)
			{
				if (json[i] == '\n')
				{
					return i + 1;
				}
			}
			return json.Length - 1;
		}

		private static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json)
		{
			stringBuilder.Append(json[startIdx]);
			for (int i = startIdx + 1; i < json.Length; i++)
			{
				if (json[i] == '\\')
				{
					if (appendEscapeCharacter)
					{
						stringBuilder.Append(json[i]);
					}
					stringBuilder.Append(json[i + 1]);
					i++;
				}
				else
				{
					if (json[i] == '"')
					{
						stringBuilder.Append(json[i]);
						return i;
					}
					stringBuilder.Append(json[i]);
				}
			}
			return json.Length - 1;
		}

		private static List<string> Split(string json)
		{
			List<string> list = ((splitArrayPool.Count > 0) ? splitArrayPool.Pop() : new List<string>());
			list.Clear();
			if (json.Length == 2)
			{
				return list;
			}
			int num = 0;
			stringBuilder.Length = 0;
			for (int i = 1; i < json.Length - 1; i++)
			{
				switch (json[i])
				{
				case '[':
				case '{':
					num++;
					break;
				case ']':
				case '}':
					num--;
					break;
				case '"':
					i = AppendUntilStringEnd(appendEscapeCharacter: true, i, json);
					continue;
				case ',':
				case ':':
					if (num == 0)
					{
						list.Add(stringBuilder.ToString());
						stringBuilder.Length = 0;
						continue;
					}
					break;
				}
				stringBuilder.Append(json[i]);
			}
			list.Add(stringBuilder.ToString());
			return list;
		}

		internal static object ParseValue(Type type, string json)
		{
			if (type == typeof(string))
			{
				if (json.Length <= 2)
				{
					return string.Empty;
				}
				StringBuilder stringBuilder = new StringBuilder(json.Length);
				for (int i = 1; i < json.Length - 1; i++)
				{
					if (json[i] == '\\' && i + 1 < json.Length - 1)
					{
						int num = "\"\\nrtbf/".IndexOf(json[i + 1]);
						if (num >= 0)
						{
							stringBuilder.Append("\"\\\n\r\t\b\f/"[num]);
							i++;
							continue;
						}
						if (json[i + 1] == 'u' && i + 5 < json.Length - 1)
						{
							uint result = 0u;
							if (uint.TryParse(json.Substring(i + 2, 4), NumberStyles.AllowHexSpecifier, null, out result))
							{
								stringBuilder.Append((char)result);
								i += 5;
								continue;
							}
						}
					}
					stringBuilder.Append(json[i]);
				}
				return stringBuilder.ToString();
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
			{
				return Convert.ChangeType(json, type.GetGenericArguments().First(), CultureInfo.InvariantCulture);
			}
			if (type.IsPrimitive)
			{
				return Convert.ChangeType(json, type, CultureInfo.InvariantCulture);
			}
			if (type == typeof(decimal))
			{
				decimal.TryParse(json, NumberStyles.Float, CultureInfo.InvariantCulture, out var result2);
				return result2;
			}
			if (type == typeof(DateTime))
			{
				DateTime.TryParse(json.Replace("\"", ""), CultureInfo.InvariantCulture, DateTimeStyles.None, out var result3);
				return result3;
			}
			if (json == "null")
			{
				return null;
			}
			if (type.IsEnum)
			{
				if (json[0] == '"')
				{
					json = json.Substring(1, json.Length - 2);
				}
				try
				{
					return Enum.Parse(type, json, ignoreCase: false);
				}
				catch
				{
					return 0;
				}
			}
			if (type.IsArray)
			{
				Type elementType = type.GetElementType();
				if (json[0] != '[' || json[json.Length - 1] != ']')
				{
					return null;
				}
				List<string> list = Split(json);
				Array array = Array.CreateInstance(elementType, list.Count);
				for (int j = 0; j < list.Count; j++)
				{
					array.SetValue(ParseValue(elementType, list[j]), j);
				}
				splitArrayPool.Push(list);
				return array;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
			{
				Type type2 = type.GetGenericArguments()[0];
				if (json[0] != '[' || json[json.Length - 1] != ']')
				{
					return null;
				}
				List<string> list2 = Split(json);
				IList list3 = (IList)type.GetConstructor(new Type[1] { typeof(int) }).Invoke(new object[1] { list2.Count });
				for (int k = 0; k < list2.Count; k++)
				{
					list3.Add(ParseValue(type2, list2[k]));
				}
				splitArrayPool.Push(list2);
				return list3;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				Type[] genericArguments = type.GetGenericArguments();
				Type type3 = genericArguments[0];
				Type type4 = genericArguments[1];
				if (type3 != typeof(string))
				{
					return null;
				}
				if (json[0] != '{' || json[json.Length - 1] != '}')
				{
					return null;
				}
				List<string> list4 = Split(json);
				if (list4.Count % 2 != 0)
				{
					return null;
				}
				IDictionary dictionary = (IDictionary)type.GetConstructor(new Type[1] { typeof(int) }).Invoke(new object[1] { list4.Count / 2 });
				for (int l = 0; l < list4.Count; l += 2)
				{
					if (list4[l].Length > 2)
					{
						string key = list4[l].Substring(1, list4[l].Length - 2);
						object value = ParseValue(type4, list4[l + 1]);
						dictionary[key] = value;
					}
				}
				return dictionary;
			}
			if (type == typeof(object))
			{
				return ParseAnonymousValue(json);
			}
			if (json[0] == '{' && json[json.Length - 1] == '}')
			{
				return ParseObject(type, json);
			}
			return null;
		}

		private static object ParseAnonymousValue(string json)
		{
			if (json.Length == 0)
			{
				return null;
			}
			if (json[0] == '{' && json[json.Length - 1] == '}')
			{
				List<string> list = Split(json);
				if (list.Count % 2 != 0)
				{
					return null;
				}
				Dictionary<string, object> dictionary = new Dictionary<string, object>(list.Count / 2);
				for (int i = 0; i < list.Count; i += 2)
				{
					dictionary[list[i].Substring(1, list[i].Length - 2)] = ParseAnonymousValue(list[i + 1]);
				}
				return dictionary;
			}
			if (json[0] == '[' && json[json.Length - 1] == ']')
			{
				List<string> list2 = Split(json);
				List<object> list3 = new List<object>(list2.Count);
				for (int j = 0; j < list2.Count; j++)
				{
					list3.Add(ParseAnonymousValue(list2[j]));
				}
				return list3;
			}
			if (json[0] == '"' && json[json.Length - 1] == '"')
			{
				string text = json.Substring(1, json.Length - 2);
				return text.Replace("\\", string.Empty);
			}
			if (char.IsDigit(json[0]) || json[0] == '-')
			{
				if (json.Contains("."))
				{
					double.TryParse(json, NumberStyles.Float, CultureInfo.InvariantCulture, out var result);
					return result;
				}
				int.TryParse(json, out var result2);
				return result2;
			}
			if (json == "true")
			{
				return true;
			}
			if (json == "false")
			{
				return false;
			}
			return null;
		}

		private static Dictionary<string, T> CreateMemberNameDictionary<T>(T[] members) where T : MemberInfo
		{
			Dictionary<string, T> dictionary = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
			foreach (T val in members)
			{
				if (val.IsDefined(typeof(IgnoreDataMemberAttribute), inherit: true))
				{
					continue;
				}
				string name = val.Name;
				if (val.IsDefined(typeof(DataMemberAttribute), inherit: true))
				{
					DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(val, typeof(DataMemberAttribute), inherit: true);
					if (!string.IsNullOrEmpty(dataMemberAttribute.Name))
					{
						name = dataMemberAttribute.Name;
					}
				}
				dictionary.Add(name.ToLower(), val);
			}
			return dictionary;
		}

		private static object ParseObject(Type type, string json)
		{
			object uninitializedObject = FormatterServices.GetUninitializedObject(type);
			if (uninitializedObject is IInitializable initializable)
			{
				initializable.Initialize();
			}
			List<string> list = Split(json);
			if (list.Count % 2 != 0)
			{
				return uninitializedObject;
			}
			if (!fieldInfoCache.TryGetValue(type, out var value))
			{
				value = CreateMemberNameDictionary(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy));
				fieldInfoCache.Add(type, value);
			}
			if (!propertyInfoCache.TryGetValue(type, out var value2))
			{
				value2 = CreateMemberNameDictionary(type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy));
				propertyInfoCache.Add(type, value2);
			}
			for (int i = 0; i < list.Count; i += 2)
			{
				if (list[i].Length <= 2)
				{
					continue;
				}
				string text = list[i].Substring(1, list[i].Length - 2).ToLower();
				string text2 = list[i + 1];
				if (value.TryGetValue(text, out var value3))
				{
					SetField(value3, uninitializedObject, text2);
					continue;
				}
				if (value2.TryGetValue(text, out var value4))
				{
					SetProperty(value4, uninitializedObject, text2);
					continue;
				}
				bool flag = false;
				foreach (KeyValuePair<string, FieldInfo> item in value)
				{
					FieldInfo value5 = item.Value;
					if (value5.FieldType.GetInterfaces().Contains(typeof(IFlexibleField)))
					{
						object value6 = value5.GetValue(uninitializedObject);
						if (value6 is IFlexibleField flexibleField && flexibleField.ContainsKey(text))
						{
							flexibleField.SetValue(text, (string)ParseValue(typeof(string), text2));
							flag = true;
							break;
						}
					}
				}
				if (!flag)
				{
					Plugin.VerboseWarning($"{text} field not found for {type}");
				}
			}
			return uninitializedObject;
		}

		private static void SetField(FieldInfo info, object o, string v)
		{
			if (info.FieldType.GetInterfaces().Contains(typeof(IFlexibleField)))
			{
				object value = info.GetValue(o);
				if (value == null)
				{
					Debug.LogError((object)$"{info.Name} field is null! {info.FieldType} o:{o} instance:{o}");
				}
				else if (value is IFlexibleField flexibleField)
				{
					flexibleField.SetValue(info.Name, (string)ParseValue(typeof(string), v));
				}
			}
			else
			{
				info.SetValue(o, ParseValue(info.FieldType, v));
			}
		}

		private static void SetProperty(PropertyInfo info, object o, string v)
		{
			info.SetValue(o, ParseValue(info.PropertyType, v), null);
		}

		public static string ToJSON<T>(T t)
		{
			return ToJSONInternal(typeof(T), t, "");
		}

		private static string ToJSONInternal(Type type, object t, string prefix)
		{
			try
			{
				if (type == typeof(string))
				{
					string text = (string)t;
					if (text != null)
					{
						return "\"" + text + "\"";
					}
					return "\"\"";
				}
				if (type == typeof(string[]))
				{
					string[] array = (string[])t;
					if (array != null && array.Length != 0)
					{
						string text2 = "[";
						for (int i = 0; i < array.Length; i++)
						{
							string text3 = array[i];
							text2 = text2 + "\"" + text3 + "\"";
							if (i < array.Length - 1)
							{
								text2 += ",";
							}
						}
						return text2 + "]";
					}
					return "[]";
				}
				if (type == typeof(int?))
				{
					int? num = (int?)t;
					if (num.HasValue)
					{
						return num.Value.ToString();
					}
					return "0";
				}
				if (type == typeof(bool?))
				{
					bool? flag = (bool?)t;
					if (flag.HasValue)
					{
						return flag.Value ? "true" : "false";
					}
					return "false";
				}
				if (type == typeof(bool))
				{
					return ((bool)t) ? "true" : "false";
				}
				if (type == typeof(int) || type == typeof(long))
				{
					return t.ToString();
				}
				if (type == typeof(Dictionary<string, string>))
				{
					Dictionary<string, string> dictionary = (Dictionary<string, string>)t;
					if (dictionary != null && dictionary.Count > 0)
					{
						string text4 = "{";
						int num2 = 0;
						foreach (KeyValuePair<string, string> item in dictionary)
						{
							text4 = ((num2++ <= 0) ? (text4 + "\n\t" + prefix + "\"" + item.Key + "\": \"" + item.Value + "\"") : (text4 + ",\n\t" + prefix + "\"" + item.Key + "\": \"" + item.Value + "\""));
						}
						if (num2 > 0)
						{
							return text4 + "\n" + prefix + "}";
						}
						return text4 + "}";
					}
					return "{}";
				}
				if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
				{
					IList list = (IList)t;
					if (list != null && list.Count > 0)
					{
						Type type2 = list.GetType().GetGenericArguments().Single();
						string text5 = "";
						string text6 = prefix + "\t";
						for (int j = 0; j < list.Count; j++)
						{
							object t2 = list[j];
							text5 = text5 + "\n" + text6 + ToJSONInternal(type2, t2, text6);
							if (j < list.Count - 1)
							{
								text5 += ",";
							}
						}
						return "[" + text5 + "\n" + prefix + "]";
					}
					return "[]";
				}
				if (type.IsAssignableFrom(typeof(IFlexibleField)))
				{
					if (t != null)
					{
						return ((IFlexibleField)t).ToJSON();
					}
					Dictionary<string, string> rows = ((LocalizableField)t).rows;
					return ToJSONInternal(rows.GetType(), rows, prefix);
				}
				if (!type.IsValueType)
				{
					if (!publicFieldInfoCache.TryGetValue(type, out var value))
					{
						value = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
						publicFieldInfoCache[type] = value;
					}
					string text7 = "{";
					int num3 = 0;
					string text8 = prefix + "\t";
					FieldInfo[] array2 = value;
					foreach (FieldInfo fieldInfo in array2)
					{
						string text9 = ToJSONInternal(fieldInfo.FieldType, fieldInfo.GetValue(t), text8);
						if (num3++ > 0)
						{
							text7 += ",";
						}
						text7 = text7 + "\n" + text8 + "\"" + fieldInfo.Name + "\": " + text9;
					}
					if (num3 > 0)
					{
						return text7 + "\n" + prefix + "}";
					}
					return text7 + prefix + "}";
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)$"Something went wrong while serializing JSON type: {type} value: {t}");
				Plugin.Log.LogError((object)ex);
				throw;
			}
			throw new NotImplementedException($"Type not supported for JSON serialization {type}");
		}
	}
}
namespace JLPlugin
{
	public static class Extensions
	{
		public static void Append<K, V>(this Dictionary<K, V> first, Dictionary<K, V> second)
		{
			second.ToList().ForEach(delegate(KeyValuePair<K, V> pair)
			{
				first[pair.Key] = pair.Value;
			});
		}
	}
	internal static class Interpreter
	{
		public static class RegexStrings
		{
			public static string Function = "([a-zA-Z]+)(?<!if|in)(\\(((?>\\((?<c>)|[^()]+|\\)(?<-c>))*(?(c)(?!)))\\))";

			public static string Variable = "\\[((?>\\[(?<c>)|[^\\[\\]]+|\\](?<-c>))*(?(c)(?!)))\\]";

			public static string GeneratedVariable = "\\[([^]]*?\\.[^[]*?)\\]";

			public static string Expression = "\\(((?>\\((?<c>)|[^()]+|\\)(?<-c>))*(?(c)(?!)))\\)";
		}

		public static Random random = new Random();

		public static object Process(in string input, AbilityBehaviourData abilityData, Type type = null, bool sendDebug = true, Dictionary<string, object?> additionalParameters = null)
		{
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00bf: Expected O, but got Unknown
			object obj = input;
			MatchCollection matchCollection = Regex.Matches(input, RegexStrings.Expression);
			if (matchCollection.Cast<Match>().Any((Match expressions) => expressions.Success))
			{
				EvaluateFunctionHandler val2 = default(EvaluateFunctionHandler);
				foreach (Match item in matchCollection)
				{
					string value = item.Groups[0].Value;
					string value2 = item.Groups[1].Value;
					ExtendedExpression val = new ExtendedExpression(value2);
					EvaluateFunctionHandler obj2 = val2;
					if (obj2 == null)
					{
						EvaluateFunctionHandler val3 = delegate(string functionName, FunctionArgs functionArgs)
						{
							ConfigilExtensions.Extend(functionName, functionArgs, abilityData);
						};
						EvaluateFunctionHandler val4 = val3;
						val2 = val3;
						obj2 = val4;
					}
					((Expression)val).EvaluateFunction += obj2;
					if (additionalParameters != null)
					{
						Extensions.AddRange<string, object>(((Expression)val).Parameters, additionalParameters);
					}
					foreach (KeyValuePair<string, string> variable in abilityData.variables)
					{
						((Expression)val).Parameters[variable.Key] = variable.Value;
					}
					foreach (KeyValuePair<string, object> generatedVariable in abilityData.generatedVariables)
					{
						((Expression)val).Parameters[generatedVariable.Key] = generatedVariable.Value;
					}
					MatchCollection matchCollection2 = Regex.Matches(value2, RegexStrings.GeneratedVariable);
					if (matchCollection2.Cast<Match>().Any((Match variables) => variables.Success))
					{
						foreach (Match item2 in matchCollection2)
						{
							string value3 = item2.Groups[1].Value;
							((Expression)val).Parameters[value3] = ProcessGeneratedVariable(value3, abilityData);
						}
					}
					if (sendDebug)
					{
						Plugin.Log.LogDebug((object)("input: " + value));
					}
					object obj3 = ((Expression)val).Evaluate();
					if (type == null || matchCollection.Count > 1)
					{
						if (obj3.GetType() == typeof(bool))
						{
							obj3 = obj3.ToString().ToLower();
						}
						obj = obj.ToString().Replace(value, obj3.ToString());
					}
					else
					{
						obj = obj3;
					}
					if (sendDebug)
					{
						Plugin.Log.LogDebug((object)$"output: {obj3}");
					}
				}
			}
			return obj;
		}

		public static object ProcessGeneratedVariable(string contents, AbilityBehaviourData abilityData = null, object variable = null)
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0155: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
			List<string> list = contents.Split(new char[1] { '.' }).ToList();
			object value = variable;
			if (variable == null && abilityData != null && !abilityData.generatedVariables.TryGetValue(list[0], out value))
			{
				throw new Exception(list[0] + " is an invalid generated variable");
			}
			for (int i = 1; i < list.Count; i++)
			{
				if (value == null)
				{
					return null;
				}
				if (value.GetType() == typeof(PlayableCard))
				{
					if (list[i] == "TemporaryAbilities")
					{
						List<Ability> list2 = new List<Ability>();
						foreach (List<Ability> item in ((PlayableCard)value).TemporaryMods.Select((CardModificationInfo x) => x.abilities).ToList())
						{
							list2.AddRange(item);
						}
						value = list2;
						break;
					}
					if (list[i] == "AllAbilities")
					{
						List<Ability> list3 = new List<Ability>();
						foreach (List<Ability> item2 in ((PlayableCard)value).TemporaryMods.Select((CardModificationInfo x) => x.abilities).ToList())
						{
							list3.AddRange(item2);
						}
						list3.AddRange(((Card)(PlayableCard)value).Info.Abilities);
						value = list3;
						break;
					}
				}
				PropertyInfo property = value.GetType().GetProperty(list[i]);
				if ((object)property == null)
				{
					FieldInfo field = value.GetType().GetField(list[i]);
					if ((object)field == null)
					{
						return null;
					}
					value = field.GetValue(value);
				}
				else
				{
					if (property.GetIndexParameters().Length >= 1)
					{
						break;
					}
					value = property.GetValue(value);
				}
			}
			return value;
		}
	}
	internal static class Configs
	{
		private static ConfigEntry<bool> betaCompatibility;

		private static ConfigEntry<bool> verboseLogging;

		private static ConfigEntry<string> reloadHotkey;

		private static ConfigEntry<string> exportHotkey;

		private static ConfigFile configFile;

		private static Version oldConfigVersion;

		private static Version currentVersion;

		internal static bool BetaCompatibility => betaCompatibility.Value;

		internal static bool VerboseLogging => verboseLogging.Value;

		internal static string ReloadHotkey => reloadHotkey.Value;

		internal static string ExportHotkey => exportHotkey.Value;

		public static void InitializeConfigs(ConfigFile config)
		{
			configFile = config;
			currentVersion = new Version("2.5.3");
			oldConfigVersion = GetOldConfigVersion();
			betaCompatibility = config.Bind<bool>("JSONLoader", "JDLR Backwards Compatibility", true, "Set to true to enable old-style JSON files (JLDR) to be read and converted to new-style files (JLDR2)");
			verboseLogging = config.Bind<bool>("JSONLoader", "Verbose Logging", false, "Set to true to see more logs on what JSONLoader is doing and what isn't working.");
			reloadHotkey = config.Bind<string>("Hotkeys", "Reload JLDR2 and game", "LeftShift+R", "Restarts the game and reloads all JLDR2 files.");
			exportHotkey = config.Bind<string>("Hotkeys", "Export all to JLDR2", "LeftControl+RightControl+X", "Exports all data in the game back to .JLDR2 files.");
			MigrateConfigs();
			ModdedSaveManager.SaveData.SetValue("MADH.inscryption.JSONLoader", "LastLoadedVersion", (object)currentVersion.ToString());
		}

		private static Version GetOldConfigVersion()
		{
			string value = ModdedSaveManager.SaveData.GetValue("MADH.inscryption.JSONLoader", "LastLoadedVersion");
			if (string.IsNullOrEmpty(value))
			{
				return new Version("2.5.2");
			}
			return new Version(value);
		}

		private static void MigrateConfigs()
		{
			if (!(oldConfigVersion == currentVersion) && oldConfigVersion <= new Version("2.5.3"))
			{
				Plugin.Log.LogInfo((object)$"Migrating from {oldConfigVersion} to {currentVersion}!");
				if (ReloadHotkey == (string)((ConfigEntryBase)exportHotkey).DefaultValue && ExportHotkey == (string)((ConfigEntryBase)reloadHotkey).DefaultValue)
				{
					Plugin.Log.LogInfo((object)"\tMigrating hotkeys to new defaults!");
					exportHotkey.Value = (string)((ConfigEntryBase)exportHotkey).DefaultValue;
					reloadHotkey.Value = (string)((ConfigEntryBase)reloadHotkey).DefaultValue;
					configFile.Save();
				}
			}
		}
	}
	[BepInPlugin("MADH.inscryption.JSONLoader", "JSONLoader", "2.5.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public static Plugin Instance;

		public const string PluginGuid = "MADH.inscryption.JSONLoader";

		public const string PluginName = "JSONLoader";

		public const string PluginVersion = "2.5.3";

		public static string JSONLoaderDirectory = "";

		public static string BepInExDirectory = "";

		internal static ManualLogSource Log;

		private HotkeyController hotkeyController;

		public static string ExportDirectory => Path.Combine(JSONLoaderDirectory, "Exported");

		private static List<string> GetAllJLDRFiles()
		{
			return (from a in Directory.GetFiles(Paths.PluginPath, "*.jldr*", SearchOption.AllDirectories)
				where (a.EndsWith(".jldr") || a.EndsWith(".jldr2")) && !a.Contains(Path.Combine(JSONLoaderDirectory, "Examples"))
				select a).ToList();
		}

		private void Awake()
		{
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a2: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Loading JSONLoader!");
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			JSONLoaderDirectory = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
			int num = ((BaseUnityPlugin)this).Info.Location.LastIndexOf("BepInEx");
			if (num > 0)
			{
				BepInExDirectory = ((BaseUnityPlugin)this).Info.Location.Substring(0, num);
			}
			else
			{
				BepInExDirectory = Directory.GetParent(JSONLoaderDirectory)?.FullName ?? "";
			}
			Harmony val = new Harmony("MADH.inscryption.JSONLoader");
			val.PatchAll();
			Configs.InitializeConfigs(((BaseUnityPlugin)this).Config);
			Log.LogWarning((object)"Note: JSONLoader now uses .jldr2 files, not .json files.");
			List<string> allJLDRFiles = GetAllJLDRFiles();
			if (Configs.BetaCompatibility)
			{
				Log.LogWarning((object)"Note: Backwards compatibility has been enabled. Old *.jldr files will be converted to *.jldr2 automatically. This will slow down your game loading!");
				JLUtils.LoadCardsFromFiles(allJLDRFiles);
			}
			LoadAll(allJLDRFiles);
			hotkeyController = new HotkeyController();
			hotkeyController.AddHotkey(Configs.ReloadHotkey, ReloadGame);
			hotkeyController.AddHotkey(Configs.ExportHotkey, ExportAllToJLDR2);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Loaded JSONLoader!");
		}

		public static void LogFields()
		{
			string text = "\n";
			List<Type> list = new List<Type>();
			list.Add(typeof(PlayableCard));
			list.Add(typeof(CardInfo));
			list.Add(typeof(CardSlot));
			List<Type> list2 = list;
			foreach (Type item in list2)
			{
				FieldInfo[] fields = item.GetFields();
				if (fields.Length != 0)
				{
					string text2 = item.Name + " fields:\n";
					text += text2;
					text = text + new string('-', text2.Length - 1) + "\n";
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						text = text + fieldInfo.Name + " (" + fieldInfo.FieldType.Name + ")\n";
					}
					text = text + new string('-', text2.Length - 1) + "\n\n";
				}
				PropertyInfo[] properties = item.GetProperties();
				if (properties.Length != 0)
				{
					string text3 = item.Name + " properties:\n";
					text += text3;
					text = text + new string('-', text3.Length - 1) + "\n";
					PropertyInfo[] array2 = properties;
					foreach (PropertyInfo propertyInfo in array2)
					{
						text = text + propertyInfo.Name + " (" + propertyInfo.PropertyType.Name + ")\n";
					}
					text = text + new string('-', text3.Length - 1) + "\n\n";
				}
			}
			Log.LogInfo((object)text);
		}

		public void LoadAll(List<string> files)
		{
			TribeList.LoadAllTribes(files);
			SigilData.LoadAllSigils(files);
			CardSerializeInfo.LoadAllJLDR2(files);
			EncounterData.LoadAllEncounters(files);
			StarterDeckList.LoadAllStarterDecks(files);
			GramophoneData.LoadAllGramophone(files);
			LanguageData.LoadAllLanguages(files);
			MaskData.LoadAllMasks(files);
			LoadTalkingCards.InitAndLoad(files);
		}

		public void Update()
		{
			hotkeyController.Update();
		}

		private void ReloadGame()
		{
			List<string> allJLDRFiles = GetAllJLDRFiles();
			LoadAll(allJLDRFiles);
			CachedCardData.Flush();
			if (SaveFile.IsAscension)
			{
				ReloadKaycees();
			}
			if (SaveManager.SaveFile.IsPart1)
			{
				ReloadVanilla();
			}
		}

		public void ExportAllToJLDR2()
		{
			TribeList.ExportAllTribes();
			EncounterData.ExportAllEncounters();
			StarterDeckList.ExportAllStarterDecks();
			LanguageData.ExportAllLanguages();
			CardSerializeInfo.ExportAllCards();
		}

		public static void ReloadVanilla()
		{
			FrameLoopManager.Instance.SetIterationDisabled(false);
			MenuController.ReturnToStartScreen();
			MenuController.LoadGameFromMenu(false);
		}

		public static void ReloadKaycees()
		{
			FrameLoopManager.Instance.SetIterationDisabled(false);
			SceneLoader.Load("Ascension_Configure");
			FrameLoopManager.Instance.SetIterationDisabled(false);
			SaveManager.savingDisabled = false;
			MenuController.LoadGameFromMenu(false);
		}

		internal static void VerboseLog(string s)
		{
			if (Configs.VerboseLogging)
			{
				Log.LogInfo((object)s);
			}
		}

		internal static void VerboseWarning(string s)
		{
			if (Configs.VerboseLogging)
			{
				Log.LogWarning((object)s);
			}
		}

		internal static void VerboseError(string s)
		{
			if (Configs.VerboseLogging)
			{
				Log.LogError((object)s);
			}
		}
	}
}
namespace JLPlugin.Hotkeys
{
	internal class HotkeyController
	{
		public class Hotkey
		{
			public KeyCode[] KeyCodes;

			public Action Function;
		}

		private static Action<List<KeyCode>, KeyCode> OnHotkeyPressed = delegate
		{
		};

		private static KeyCode[] AllCodes = Enum.GetValues(typeof(KeyCode)).Cast<KeyCode>().ToArray();

		private List<Hotkey> Hotkeys = new List<Hotkey>();

		private List<KeyCode> m_pressedKeys = new List<KeyCode>();

		private bool m_hotkeyActivated = false;

		private static KeyCode[] DeserializeKeyCodes(string hotkey)
		{
			return hotkey.Trim().Split(new char[1] { '+' }).Select(delegate(string a)
			{
				//IL_002d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Unknown result type (might be due to invalid IL or missing references)
				if (!Enum.TryParse<KeyCode>(a, out KeyCode result))
				{
					Plugin.Log.LogError((object)("Unknown hotkey: '" + a + "'. See possible hotkeys here separated by +. https://docs.unity3d.com/ScriptReference/KeyCode.html"));
				}
				return result;
			})
				.ToArray();
		}

		public void Update()
		{
			//IL_000f: 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_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			KeyCode[] allCodes = AllCodes;
			foreach (KeyCode val in allCodes)
			{
				if (Input.GetKeyDown(val) && !m_pressedKeys.Contains(val))
				{
					m_pressedKeys.Add(val);
					HotkeysChanged(val, triggerHotkey: true);
				}
			}
			for (int j = 0; j < m_pressedKeys.Count; j++)
			{
				KeyCode val2 = m_pressedKeys[j];
				if (!Input.GetKey(val2))
				{
					m_pressedKeys.Remove(val2);
					HotkeysChanged((KeyCode)0, triggerHotkey: false);
					m_hotkeyActivated = false;
				}
			}
		}

		private void HotkeysChanged(KeyCode pressedButton, bool triggerHotkey)
		{
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Invalid comparison between Unknown and I4
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if (triggerHotkey)
			{
				Hotkey hotkey = null;
				foreach (Hotkey hotkey2 in Hotkeys)
				{
					if (!m_hotkeyActivated && hotkey2.KeyCodes.Length != 0 && m_pressedKeys.Intersect(hotkey2.KeyCodes).Count() == hotkey2.KeyCodes.Length && (hotkey == null || hotkey.KeyCodes.Length < hotkey2.KeyCodes.Length))
					{
						hotkey = hotkey2;
					}
				}
				hotkey?.Function?.Invoke();
			}
			if ((int)pressedButton > 0)
			{
				OnHotkeyPressed?.Invoke(m_pressedKeys, pressedButton);
			}
		}

		public void AddHotkey(string hotkeys, Action callback)
		{
			Hotkeys.Add(new Hotkey
			{
				KeyCodes = DeserializeKeyCodes(hotkeys),
				Function = callback
			});
		}
	}
}
namespace JLPlugin.V2.Data
{
	public class CardSerializeInfo : JSONParser.IInitializable
	{
		public const string DEFAULT_MOD_PREFIX = "JSON";

		private static FieldInfo[] PUBLIC_FIELD_INFOS = typeof(CardSerializeInfo).GetFields(BindingFlags.Instance | BindingFlags.Public);

		public string name;

		public string modPrefix;

		public string[] decals;

		public JSONParser.LocalizableField displayedName;

		public JSONParser.LocalizableField description;

		public int? baseAttack;

		public int? baseHealth;

		public int? bloodCost;

		public int? bonesCost;

		public int? energyCost;

		public string[] gemsCost;

		public string[] abilities;

		public string[] specialAbilities;

		public string specialStatIcon;

		public string[] metaCategories;

		public string cardComplexity;

		public bool? onePerDeck;

		public string temple;

		public string titleGraphic;

		public bool? hideAttackAndHealth;

		public string[] appearanceBehaviour;

		public string texture;

		public string emissionTexture;

		public string holoPortraitPrefab;

		public string animatedPortrait;

		public string altTexture;

		public string altEmissionTexture;

		public string pixelTexture;

		public string[] tribes;

		public string[] traits;

		public string evolveIntoName;

		public int? evolveTurns;

		public string defaultEvolutionName;

		public string tailName;

		public string tailLostPortrait;

		public string iceCubeName;

		public bool? flipPortraitForStrafe;

		public Dictionary<string, string> extensionProperties;

		public string filePath;

		public CardSerializeInfo()
		{
			Initialize();
		}

		public void Initialize()
		{
			displayedName = new JSONParser.LocalizableField("displayedName");
			description = new JSONParser.LocalizableField("description");
		}

		public static void Apply(CardInfo cardInfo, CardSerializeInfo serializeInfo, bool toCardInfo, string cardName)
		{
			ImportExportUtils.SetID(cardName);
			ImportExportUtils.ApplyLocaleField("displayedName", ref serializeInfo.displayedName, ref cardInfo.displayedName, toCardInfo);
			ImportExportUtils.ApplyLocaleField("description", ref serializeInfo.description, ref cardInfo.description, toCardInfo);
			ImportExportUtils.ApplyProperty(() => ((Object)cardInfo).name, delegate(string a)
			{
				((Object)cardInfo).name = a;
			}, ref serializeInfo.name, toCardInfo, "Cards", "name");
			ImportExportUtils.ApplyValue(ref cardInfo.baseAttack, ref serializeInfo.baseAttack, toCardInfo, "Cards", "baseAttack");
			ImportExportUtils.ApplyValue(ref cardInfo.baseHealth, ref serializeInfo.baseHealth, toCardInfo, "Cards", "baseHealth");
			ImportExportUtils.ApplyValue(ref cardInfo.cost, ref serializeInfo.bloodCost, toCardInfo, "Cards", "cost");
			ImportExportUtils.ApplyValue(ref cardInfo.bonesCost, ref serializeInfo.bonesCost, toCardInfo, "Cards", "bonesCost");
			ImportExportUtils.ApplyValue(ref cardInfo.energyCost, ref serializeInfo.energyCost, toCardInfo, "Cards", "energyCost");
			ImportExportUtils.ApplyValue(ref cardInfo.gemsCost, ref serializeInfo.gemsCost, toCardInfo, "Cards", "gemsCost");
			ImportExportUtils.ApplyValue(ref cardInfo.abilities, ref serializeInfo.abilities, toCardInfo, "Cards", "abilities");
			ImportExportUtils.ApplyValue(ref cardInfo.specialAbilities, ref serializeInfo.specialAbilities, toCardInfo, "Cards", "specialAbilities");
			ImportExportUtils.ApplyValue(ref cardInfo.specialStatIcon, ref serializeInfo.specialStatIcon, toCardInfo, "Cards", "specialStatIcon");
			ImportExportUtils.ApplyValue(ref cardInfo.metaCategories, ref serializeInfo.metaCategories, toCardInfo, "Cards", "metaCategories");
			ImportExportUtils.ApplyValue(ref cardInfo.cardComplexity, ref serializeInfo.cardComplexity, toCardInfo, "Cards", "cardComplexity");
			ImportExportUtils.ApplyValue(ref cardInfo.onePerDeck, ref serializeInfo.onePerDeck, toCardInfo, "Cards", "onePerDeck");
			ImportExportUtils.ApplyValue(ref cardInfo.temple, ref serializeInfo.temple, toCardInfo, "Cards", "temple");
			ImportExportUtils.ApplyValue(ref cardInfo.titleGraphic, ref serializeInfo.titleGraphic, toCardInfo, "Cards", "titleGraphic");
			ImportExportUtils.ApplyValue(ref cardInfo.hideAttackAndHealth, ref serializeInfo.hideAttackAndHealth, toCardInfo, "Cards", "hideAttackAndHealth");
			ImportExportUtils.ApplyValue(ref cardInfo.appearanceBehaviour, ref serializeInfo.appearanceBehaviour, toCardInfo, "Cards", "appearanceBehaviour");
			ImportExportUtils.ApplyValue(ref cardInfo.tribes, ref serializeInfo.tribes, toCardInfo, "Cards", "tribes");
			ImportExportUtils.ApplyValue(ref cardInfo.traits, ref serializeInfo.traits, toCardInfo, "Cards", "traits");
			ImportExportUtils.ApplyValue(ref cardInfo.defaultEvolutionName, ref serializeInfo.defaultEvolutionName, toCardInfo, "Cards", "defaultEvolutionName");
			ImportExportUtils.ApplyValue(ref cardInfo.flipPortraitForStrafe, ref serializeInfo.flipPortraitForStrafe, toCardInfo, "Cards", "flipPortraitForStrafe");
			ImportExportUtils.ApplyValue(ref cardInfo.decals, ref serializeInfo.decals, toCardInfo, "Cards", "decals");
			ImportExportUtils.ApplyValue(ref cardInfo.portraitTex, ref serializeInfo.texture, toCardInfo, "Cards", "texture");
			ImportExportUtils.ApplyValue(ref cardInfo.alternatePortrait, ref serializeInfo.altTexture, toCardInfo, "Cards", "altTexture");
			ImportExportUtils.ApplyValue(ref cardInfo.pixelPortrait, ref serializeInfo.pixelTexture, toCardInfo, "Cards", "pixelTexture");
			Sprite a2 = CardExtensions.GetEmissivePortrait(cardInfo);
			Sprite a3 = CardExtensions.GetEmissiveAltPortrait(cardInfo);
			ImportExportUtils.ApplyValue(ref a2, ref serializeInfo.emissionTexture, toCardInfo, "Cards", "emissionTexture");
			ImportExportUtils.ApplyValue(ref a3, ref serializeInfo.altEmissionTexture, toCardInfo, "Cards", "altEmissionTexture");
			if ((Object)(object)cardInfo.portraitTex != (Object)null && (Object)(object)a2 != (Object)null)
			{
				CardExtensions.SetEmissivePortrait(cardInfo, a2);
			}
			if ((Object)(object)cardInfo.alternatePortrait != (Object)null && (Object)(object)a3 != (Object)null)
			{
				CardExtensions.SetEmissiveAltPortrait(cardInfo, a3);
			}
			if (toCardInfo)
			{
				if (!string.IsNullOrEmpty(serializeInfo.evolveIntoName))
				{
					CardExtensions.SetEvolve(cardInfo, serializeInfo.evolveIntoName, (!serializeInfo.evolveTurns.HasValue) ? 1 : serializeInfo.evolveTurns.Value, (IEnumerable<CardModificationInfo>)null);
				}
			}
			else if (cardInfo.evolveParams != null)
			{
				CardInfo evolution = cardInfo.evolveParams.evolution;
				serializeInfo.evolveIntoName = ((evolution != null) ? ((Object)evolution).name : null);
				serializeInfo.evolveTurns = cardInfo.evolveParams.turnsToEvolve;
			}
			if (toCardInfo)
			{
				if (!string.IsNullOrEmpty(serializeInfo.tailName))
				{
					CardExtensions.SetTail(cardInfo, serializeInfo.tailName, serializeInfo.tailLostPortrait, (IEnumerable<CardModificationInfo>)null);
				}
			}
			else if (cardInfo.tailParams != null)
			{
				CardInfo tail = cardInfo.tailParams.tail;
				serializeInfo.tailName = ((tail != null) ? ((Object)tail).name : null);
				ImportExportUtils.ApplyValue(ref cardInfo.tailParams.tailLostPortrait, ref serializeInfo.tailLostPortrait, toCardInfo, "Cards", "tailLostPortrait");
			}
			if (toCardInfo)
			{
				if (!string.IsNullOrEmpty(serializeInfo.iceCubeName))
				{
					CardExtensions.SetIceCube(cardInfo, serializeInfo.iceCubeName, (IEnumerable<CardModificationInfo>)null);
				}
			}
			else if (cardInfo.iceCubeParams != null)
			{
				serializeInfo.iceCubeName = ((Object)cardInfo.iceCubeParams.creatureWithin).name;
			}
			if (toCardInfo)
			{
				if (serializeInfo.extensionProperties != null)
				{
					foreach (KeyValuePair<string, string> extensionProperty in serializeInfo.extensionProperties)
					{
						CardExtensions.SetExtendedProperty(cardInfo, extensionProperty.Key, (object)extensionProperty.Value);
					}
				}
				CardExtensions.SetExtendedProperty(cardInfo, "JSONFilePath", (object)serializeInfo.filePath);
			}
			else
			{
				Dictionary<string, string> cardExtensionTable = CardManager.GetCardExtensionTable(cardInfo);
				if (cardExtensionTable != null && cardExtensionTable.Count > 0)
				{
					foreach (KeyValuePair<string, string> item in cardExtensionTable)
					{
						if (item.Key == "ModPrefix")
						{
							serializeInfo.modPrefix = item.Value;
						}
					}
					serializeInfo.extensionProperties = cardExtensionTable;
				}
			}
			if (toCardInfo)
			{
				if (!string.IsNullOrEmpty(serializeInfo.holoPortraitPrefab))
				{
					cardInfo.holoPortraitPrefab = Resources.Load<GameObject>(serializeInfo.holoPortraitPrefab);
				}
			}
			else if ((Object)(object)cardInfo.holoPortraitPrefab != (Object)null)
			{
				serializeInfo.holoPortraitPrefab = ((object)cardInfo.holoPortraitPrefab).ToString();
			}
			if (toCardInfo)
			{
				if (!string.IsNullOrEmpty(serializeInfo.animatedPortrait))
				{
					cardInfo.animatedPortrait = Resources.Load<GameObject>(serializeInfo.animatedPortrait);
				}
			}
			else if ((Object)(object)cardInfo.animatedPortrait != (Object)null)
			{
				serializeInfo.holoPortraitPrefab = ((object)cardInfo.animatedPortrait).ToString();
			}
		}

		private void ApplyLocaleField(string field, JSONParser.LocalizableField rows, out string cardInfoEnglishField)
		{
			//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Invalid comparison between Unknown and I4
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			if (rows.rows.TryGetValue(rows.englishFieldName, out var value))
			{
				cardInfoEnglishField = value;
			}
			else
			{
				if (rows.rows.Count <= 0)
				{
					cardInfoEnglishField = null;
					return;
				}
				cardInfoEnglishField = rows.rows.First().Value;
			}
			foreach (KeyValuePair<string, string> row in rows.rows)
			{
				if (row.Key == rows.englishFieldName)
				{
					continue;
				}
				int num = row.Key.LastIndexOf("_", StringComparison.Ordinal);
				if (num >= 0)
				{
					int length = row.Key.Length - num - 1;
					string text = row.Key.Substring(num + 1, length);
					Language val = LocalizationManager.CodeToLanguage(text);
					if ((int)val != 12)
					{
						LocalizationManager.Translate("MADH.inscryption.JSONLoader", (string)null, cardInfoEnglishField, row.Value, val);
					}
					else
					{
						Plugin.Log.LogDebug((object)$"Unknown language code {text} for card {displayedName} in field {field}");
					}
				}
			}
		}

		internal void Apply(bool UpdateCard = false)
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new InvalidOperationException("Card cannot have an empty name!");
			}
			CardInfo val = (CardInfo)(UpdateCard ? ((object)ScriptableObjectLoader<CardInfo>.AllData.Find((CardInfo x) => ((Object)x).name == name)) : ((object)CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.BaseGameCards, name)));
			if ((Object)(object)val != (Object)null)
			{
				Plugin.VerboseLog("Modifying " + name + " using " + ToJSON());
				Apply(val, this, toCardInfo: true, ((Object)val).name);
				return;
			}
			Plugin.VerboseLog("New Card " + name + " using " + ToJSON());
			string text = modPrefix ?? "JSON";
			CardInfo val2 = ScriptableObject.CreateInstance<CardInfo>();
			((Object)val2).name = (name.StartsWith(text + "_") ? name : (text + "_" + name));
			Apply(val2, this, toCardInfo: true, ((Object)val2).name);
			CardManager.Add(text, val2);
		}

		internal void Remove()
		{
			if (string.IsNullOrEmpty(name))
			{
				throw new InvalidOperationException("Card cannot have an empty name!");
			}
			CardInfo val = CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.BaseGameCards, name);
			if ((Object)(object)val != (Object)null)
			{
				throw new InvalidOperationException("Base game cards cannot be removed!");
			}
			ObservableCollection<CardInfo> source = (ObservableCollection<CardInfo>)typeof(CardManager).GetField("NewCards", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null);
			CardInfo val2 = ((IEnumerable<CardInfo>)source).FirstOrDefault((Func<CardInfo, bool>)((CardInfo x) => ((Object)x).name == name));
			if ((Object)(object)val2 != (Object)null)
			{
				CardManager.Remove(val2);
			}
			else
			{
				Plugin.Log.LogWarning((object)("Cannot remove " + name));
			}
		}

		internal CardInfo ToCardInfo()
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Expected O, but got Unknown
			if (string.IsNullOrEmpty(name))
			{
				throw new InvalidOperationException("Card cannot have an empty name!");
			}
			CardInfo val = (CardInfo)CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.BaseGameCards, name).Clone();
			if ((Object)(object)val != (Object)null)
			{
				Plugin.Log.LogDebug((object)("Modifying " + name + " using " + ToJSON()));
				Apply(val, this, toCardInfo: true, name);
				return val;
			}
			string text = modPrefix ?? "JSON";
			CardInfo val2 = ScriptableObject.CreateInstance<CardInfo>();
			((Object)val2).name = (name.StartsWith(text + "_") ? name : (text + "_" + name));
			Apply(val2, this, toCardInfo: true, name);
			return val2;
		}

		public string WriteToFile(string filename, bool overwrite = true)
		{
			Plugin.Log.LogDebug((object)("Writing card " + (name ?? "Unnamed") + " to " + filename));
			if (!filename.EndsWith("2"))
			{
				filename += "2";
			}
			if (overwrite || !File.Exists(filename))
			{
				File.WriteAllText(filename, ToJSON());
			}
			return filename;
		}

		private string ToJSON()
		{
			string text = "{\n";
			FieldInfo[] pUBLIC_FIELD_INFOS = PUBLIC_FIELD_INFOS;
			foreach (FieldInfo fieldInfo in pUBLIC_FIELD_INFOS)
			{
				if (fieldInfo.FieldType == typeof(string))
				{
					string text2 = (string)fieldInfo.GetValue(this);
					if (!string.IsNullOrEmpty(text2))
					{
						text = text + "\t\"" + fieldInfo.Name + "\": \"" + text2 + "\",\n";
					}
				}
				else if (fieldInfo.FieldType == typeof(string[]))
				{
					string[] array = (string[])fieldInfo.GetValue(this);
					if (array != null && array.Length != 0)
					{
						text = text + "\t\"" + fieldInfo.Name + "\": [" + string.Join(",", array.Select((string v) => "\"" + v + "\"")) + "],\n";
					}
				}
				else if (fieldInfo.FieldType == typeof(int?))
				{
					int? num = (int?)fieldInfo.GetValue(this);
					if (num.HasValue)
					{
						text += $"\t\"{fieldInfo.Name}\": {num.Value},\n";
					}
				}
				else if (fieldInfo.FieldType == typeof(bool?))
				{
					bool? flag = (bool?)fieldInfo.GetValue(this);
					if (flag.HasValue)
					{
						text = text + "\t\"" + fieldInfo.Name + "\": " + (flag.Value ? "true" : "false") + ",\n";
					}
				}
				else if (fieldInfo.FieldType == typeof(Dictionary<string, string>))
				{
					Dictionary<string, string> dictionary = (Dictionary<string, string>)fieldInfo.GetValue(this);
					if (dictionary == null || dictionary.Count <= 0)
					{
						continue;
					}
					text = text + "\t\"" + fieldInfo.Name + "\": {\n";
					foreach (KeyValuePair<string, string> item in dictionary.Where((KeyValuePair<string, string> kvp) => !string.IsNullOrEmpty(kvp.Key) && !string.IsNullOrEmpty(kvp.Value)))
					{
						text = text + "\t\t\"" + item.Key + "\": \"" + item.Value + "\",\n";
					}
					text += "\t},\n";
				}
				else
				{
					if (!fieldInfo.FieldType.IsAssignableFrom(typeof(JSONParser.IFlexibleField)))
					{
						continue;
					}
					object value = fieldInfo.GetValue(this);
					if (value != null)
					{
						text += ((JSONParser.IFlexibleField)value).ToJSON();
					}
					Dictionary<string, string> rows = ((JSONParser.LocalizableField)fieldInfo.GetValue(this)).rows;
					foreach (KeyValuePair<string, string> item2 in rows)
					{
						text = text + "\t\"" + item2.Key + "\": " + item2.Value + ",\n";
					}
				}
			}
			return text.TrimEnd('\n', ',') + "\n}";
		}

		public static void LoadAllJLDR2(List<string> files)
		{
			for (int i = 0; i < files.Count; i++)
			{
				string text = files[i];
				string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1);
				if (!text2.EndsWith("_encounter.jldr2") && !text2.EndsWith("_tribe.jldr2") && !text2.EndsWith("_tribes.jldr2") && !text2.EndsWith("_sigil.jldr2") && !text2.EndsWith("_deck.jldr2") && !text2.EndsWith("_gram.jldr2") && !text2.EndsWith("_language.jldr2") && !text2.EndsWith("_mask.jldr2") && !text2.EndsWith("_talk.jldr2"))
				{
					files.RemoveAt(i--);
					Plugin.VerboseLog("Loading JLDR2 Card " + text2);
					ImportExportUtils.SetDebugPath(text);
					try
					{
						CardSerializeInfo cardSerializeInfo = File.ReadAllText(text).FromJson<CardSerializeInfo>();
						cardSerializeInfo.filePath = text;
						cardSerializeInfo.Apply();
						Plugin.VerboseLog("Loaded JSON card " + cardSerializeInfo.name);
					}
					catch (Exception ex)
					{
						Plugin.Log.LogError((object)("Failed to load " + text2 + ": " + ex.Message));
						Plugin.Log.LogError((object)ex);
					}
				}
			}
		}

		public static void ExportAllCards()
		{
			Plugin.Log.LogInfo((object)$"Exporting {CardManager.AllCardsCopy.Count} cards.");
			foreach (CardInfo item in CardManager.AllCardsCopy)
			{
				string text = Path.Combine(Plugin.ExportDirectory, "Cards", ((Object)item).name + ".jldr2");
				ImportExportUtils.SetDebugPath(text);
				CardSerializeInfo cardSerializeInfo = new CardSerializeInfo();
				Apply(item, cardSerializeInfo, toCardInfo: false, ((Object)item).name);
				string directoryName = Path.GetDirectoryName(text);
				if (!Directory.Exists(directoryName))
				{
					Directory.CreateDirectory(directoryName);
				}
				cardSerializeInfo.WriteToFile(text);
			}
		}
	}
}
namespace JLPlugin.Utils
{
	public static class CDUtils
	{
		public static void CheckValidFields(List<string> fields)
		{
			foreach (string field in fields)
			{
				if (string.IsNullOrEmpty(field))
				{
					Plugin.Log.LogError((object)(ErrorUtil.Card + " - fieldsToEdit cannot contain an empty string"));
				}
				else if (!Dicts.CardDataFields.Contains(field))
				{
					Plugin.Log.LogError((object)(ErrorUtil.Card + " - \"" + field + "\" is an invalid field name"));
				}
			}
		}

		public static T Assign<T>(string data, string field, Dictionary<string, T> dict)
		{
			ErrorUtil.Field = field;
			if (string.IsNullOrEmpty(data))
			{
				return default(T);
			}
			if (!dict.ContainsKey(data))
			{
				ErrorUtil.Log(data);
				return default(T);
			}
			return dict[data];
		}

		public static List<T> Assign<T>(List<string> list, string field, Dictionary<string, T> dict)
		{
			ErrorUtil.Field = field;
			if (list == null || list.Count == 0)
			{
				return null;
			}
			List<T> list2 = new List<T>();
			foreach (string item in list)
			{
				if (!dict.ContainsKey(item))
				{
					ErrorUtil.Log(item);
				}
				else
				{
					list2.Add(dict[item]);
				}
			}
			if (list2.Count == 0)
			{
				return null;
			}
			return list2;
		}

		public static Texture2D Assign(string image, string field)
		{
			ErrorUtil.Field = field;
			if (string.IsNullOrEmpty(image))
			{
				return null;
			}
			if (!image.EndsWith(".png"))
			{
				ErrorUtil.Log(image, ", it must be a .png");
				return null;
			}
			return JLUtils.LoadTexture2D(image);
		}

		public static List<Texture> Assign(List<string> list, string field)
		{
			ErrorUtil.Field = field;
			if (list == null || list.Count == 0)
			{
				return null;
			}
			List<Texture> list2 = new List<Texture>();
			foreach (string item in list)
			{
				if (!string.IsNullOrEmpty(item))
				{
					if (!item.EndsWith(".png"))
					{
						ErrorUtil.Log(item, ", it must be a .png");
					}
					else
					{
						list2.Add((Texture)(object)JLUtils.LoadTexture2D(item));
					}
				}
			}
			if (list2.Count == 0)
			{
				return null;
			}
			return list2;
		}
	}
	public static class Dicts
	{
		public static readonly Dictionary<string, CardMetaCategory> MetaCategory = Enum.GetValues(typeof(CardMetaCategory)).Cast<CardMetaCategory>().ToDictionary((CardMetaCategory t) => ((object)(CardMetaCategory)(ref t)).ToString(), (CardMetaCategory t) => t);

		public static readonly Dictionary<string, CardComplexity> Complexity = Enum.GetValues(typeof(CardComplexity)).Cast<CardComplexity>().ToDictionary((CardComplexity t) => ((object)(CardComplexity)(ref t)).ToString(), (CardComplexity t) => t);

		public static readonly Dictionary<string, CardTemple> Temple = Enum.GetValues(typeof(CardTemple)).Cast<CardTemple>().ToDictionary((CardTemple t) => ((object)(CardTemple)(ref t)).ToString(), (CardTemple t) => t);

		public static readonly Dictionary<string, GemType> GemColour = Enum.GetValues(typeof(GemType)).Cast<GemType>().ToDictionary((GemType t) => ((object)(GemType)(ref t)).ToString(), (GemType t) => t);

		public static readonly Dictionary<string, SpecialStatIcon> StatIcon = Enum.GetValues(typeof(SpecialStatIcon)).Cast<SpecialStatIcon>().ToDictionary((SpecialStatIcon t) => ((object)(SpecialStatIcon)(ref t)).ToString(), (SpecialStatIcon t) => t);

		public static readonly Dictionary<string, Tribe> Tribes = Enum.GetValues(typeof(Tribe)).Cast<Tribe>().ToDictionary((Tribe t) => ((object)(Tribe)(ref t)).ToString(), (Tribe t) => t);

		public static readonly Dictionary<string, Trait> Traits = Enum.GetValues(typeof(Trait)).Cast<Trait>().ToDictionary((Trait t) => ((object)(Trait)(ref t)).ToString(), (Trait t) => t);

		public static readonly Dictionary<string, SpecialTriggeredAbility> SpecialAbilities = Enum.GetValues(typeof(SpecialTriggeredAbility)).Cast<SpecialTriggeredAbility>().ToDictionary((SpecialTriggeredAbility t) => ((object)(SpecialTriggeredAbility)(ref t)).ToString(), (SpecialTriggeredAbility t) => t);

		public static readonly Dictionary<string, Ability> Abilities = Enum.GetValues(typeof(Ability)).Cast<Ability>().ToDictionary((Ability t) => ((object)(Ability)(ref t)).ToString(), (Ability t) => t);

		public static readonly Dictionary<string, Appearance> AppearanceBehaviour = Enum.GetValues(typeof(Appearance)).Cast<Appearance>().ToDictionary((Appearance t) => ((object)(Appearance)(ref t)).ToString(), (Appearance t) => t);

		public static readonly List<string> CardDataFields = (from elem in typeof(CardData).GetFields()
			select elem.Name).ToList();
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	public struct ErrorUtil
	{
		public static string Card { get; set; }

		public static string Field { get; set; }

		public static string Message { get; set; }

		public static void Log(string Data, string addition = "")
		{
			Plugin.Log.LogError((object)string.Format(Message + addition, Card, Field, Data));
		}

		public static void Clear()
		{
			Card = null;
			Field = null;
			Message = null;
		}
	}
	[Obsolete]
	public static class IDUtils
	{
		public static EvolveIdentifier GenerateEvolveIdentifier(CardData card)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Expected O, but got Unknown
			if (card.evolution == null)
			{
				return null;
			}
			if (string.IsNullOrEmpty(card.evolution.name))
			{
				Plugin.Log.LogError((object)(card.name + " - evolution must have a name"));
				return null;
			}
			return new EvolveIdentifier(card.evolution.name, (card.evolution.turnsToEvolve == 0) ? 1 : card.evolution.turnsToEvolve, (CardModificationInfo)null);
		}

		public static TailIdentifier GenerateTailIdentifier(CardData card)
		{
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			if (card.tail == null)
			{
				return null;
			}
			if (string.IsNullOrEmpty(card.tail.name))
			{
				Plugin.Log.LogError((object)(card.name + " - tail must have a name"));
				return null;
			}
			return new TailIdentifier(card.tail.name, CDUtils.Assign(card.tail.tailLostPortrait, "tailLostPortrait"), (CardModificationInfo)null);
		}

		public static IceCubeIdentifier GenerateIceCubeIdentifier(CardData card)
		{
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Expected O, but got Unknown
			if (card.iceCube == null)
			{
				return null;
			}
			if (string.IsNullOrEmpty(card.iceCube.creatureWithin))
			{
				Plugin.Log.LogError((object)(card.name + " - iceCube must have a creatureWithin"));
				return null;
			}
			return new IceCubeIdentifier(card.iceCube.creatureWithin, (CardModificationInfo)null);
		}

		public static List<AbilityIdentifier> GenerateAbilityIdentifiers(List<AbilityData> list)
		{
			return list?.Select((AbilityData elem) => AbilityIdentifier.GetAbilityIdentifier(elem.GUID, elem.name)).ToList();
		}

		public static List<SpecialAbilityIdentifier> GenerateSpecialAbilityIdentifiers(List<SpecialAbilityData> list)
		{
			return list?.Select((SpecialAbilityData elem) => SpecialAbilityIdentifier.GetID(elem.GUID, elem.name)).ToList();
		}
	}
	[Obsolete]
	public static class JLUtils
	{
		public static void LoadCardsFromFiles(List<string> files)
		{
			Dictionary<string, CardData> dictionary = new Dictionary<string, CardData>();
			for (int num = files.Count - 1; num >= 0; num--)
			{
				string text = files[num];
				string text2 = text.Substring(text.LastIndexOf(Path.DirectorySeparatorChar) + 1);
				if (text.EndsWith(".jldr"))
				{
					files.RemoveAt(num);
					CardData cardData = File.ReadAllText(text).FromJson<CardData>();
					if (cardData == null)
					{
						Plugin.Log.LogWarning((object)("Failed to load " + text2));
					}
					else
					{
						dictionary.Add(text, cardData);
					}
				}
			}
			List<CardData> allKnownCards = dictionary.Values.ToList();
			foreach (KeyValuePair<string, CardData> item2 in dictionary)
			{
				string key = item2.Key;
				CardData value = item2.Value;
				CardSerializeInfo cardSerializeInfo = value.ConvertToV2(allKnownCards);
				if (cardSerializeInfo != null)
				{
					string item = cardSerializeInfo.WriteToFile(key, overwrite: false);
					files.Add(item);
				}
				else
				{
					Plugin.Log.LogError((object)(key + " is a JLDR without a valid name"));
				}
			}
		}

		public static Texture2D LoadTexture2D(string image)
		{
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			string[] files = Directory.GetFiles(Paths.PluginPath, image, SearchOption.AllDirectories);
			if (files.Length == 0)
			{
				Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't find texture \"" + image + "\" to load into " + ErrorUtil.Field));
				return null;
			}
			if (files.Length > 1)
			{
				Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't load \"" + image + "\" into " + ErrorUtil.Field + ", more than one file with that name found in the plugins folder"));
				return null;
			}
			byte[] array = File.ReadAllBytes(files[0]);
			Texture2D val = new Texture2D(2, 2);
			if (!ImageConversion.LoadImage(val, array))
			{
				Plugin.Log.LogError((object)(ErrorUtil.Card + " - Couldn't load \"" + image + "\" into " + ErrorUtil.Field));
				return null;
			}
			return val;
		}
	}
}
namespace JLPlugin.SigilCode
{
	public abstract class ConfigurableBase : ActivatedAbilityBehaviour
	{
		public SigilData abilityData = new SigilData();

		public Ability ability = (Ability)0;

		public override Ability Ability => ability;

		public PlayableCard PlayableCard => ((Component)this).GetComponent<PlayableCard>();
	}
	public abstract class ConfigurableSpecialBase : SpecialCardBehaviour
	{
		public SigilData abilityData = new SigilData();

		public SpecialTriggeredAbility specialAbility = (SpecialTriggeredAbility)0;
	}
	[HarmonyPatch(typeof(CardTriggerHandler), "AddAbility", new Type[] { typeof(Ability) })]
	public class Add_Ability_patch
	{
		[HarmonyPrefix]
		public static bool Prefix(Ability ability, CardTriggerHandler __instance)
		{
			//IL_0007: 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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: 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_00c4: Unknown result type (might be due to invalid IL or missing references)
			if (!SigilDicts.ArgumentList.ContainsKey(ability))
			{
				return true;
			}
			Type item = SigilDicts.ArgumentList[ability].Item1;
			if ((!__instance.triggeredAbilities.Exists((Tuple<Ability, AbilityBehaviour> x) => x.Item1 == ability) || AbilitiesUtil.GetInfo(ability).canStack) && !AbilitiesUtil.GetInfo(ability).passive)
			{
				ConfigurableBase configurableBase = ((Component)__instance).gameObject.AddComponent(item) as ConfigurableBase;
				configurableBase.abilityData = SigilData.GetAbilityArguments(ability);
				configurableBase.ability = ability;
				__instance.triggeredAbilities.Add(new Tuple<Ability, AbilityBehaviour>(ability, (AbilityBehaviour)(object)configurableBase));
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(CardTriggerHandler), "AddAbility", new Type[] { typeof(SpecialTriggeredAbility) })]
	public class Add__Special_Ability_patch
	{
		[HarmonyPrefix]
		public static bool Prefix(SpecialTriggeredAbility ability, CardTriggerHandler __instance)
		{
			//IL_0007: 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_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (!SigilDicts.SpecialArgumentList.ContainsKey(ability))
			{
				return true;
			}
			Type item = SigilDicts.SpecialArgumentList[ability].Item1;
			if (!__instance.specialAbilities.Exists((Tuple<SpecialTriggeredAbility, SpecialCardBehaviour> x) => x.Item1 == ability))
			{
				ConfigurableSpecialBase configurableSpecialBase = ((Component)__instance).gameObject.AddComponent(item) as ConfigurableSpecialBase;
				configurableSpecialBase.abilityData = SigilData.GetAbilityArguments(ability);
				__instance.specialAbilities.Add(new Tuple<SpecialTriggeredAbility, SpecialCardBehaviour>(ability, (SpecialCardBehaviour)(object)configurableSpecialBase));
			}
			return false;
		}
	}
	[HarmonyPatch(/*Could not decode attribute arguments.*/)]
	public class GetOpposingSlots_patch
	{
		[HarmonyPostfix]
		public static void Postfix(PlayableCard __instance, ref List<CardSlot> __result)
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: 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_0099: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.OnBoard)
			{
				return;
			}
			foreach (CardSlot item in Singleton<BoardManager>.Instance.AllSlotsCopy)
			{
				if ((Object)(object)item.Card == (Object)null)
				{
					continue;
				}
				foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities())
				{
					if (!SigilDicts.ArgumentList.ContainsKey(triggeredAbility) || !item.Card.HasAbility(triggeredAbility))
					{
						continue;
					}
					foreach (AbilityBehaviourData item2 in SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour.Where((AbilityBehaviourData x) => x?.extraAttacks != null))
					{
						foreach (extraAttacks extraAttack in item2.extraAttacks)
						{
							SigilData.UpdateVariables(item2, item.Card);
							item2.generatedVariables["TriggerCard"] = __instance;
							if (SigilData.ConvertArgument(extraAttack.runOnCondition, item2) == "false")
							{
								continue;
							}
							CardSlot val = slotData.GetSlot(extraAttack.attackingSlot, item2);
							if (extraAttack.attackingSlot == null)
							{
								val = item;
							}
							if (!((Object)(object)val == (Object)(object)__instance.slot))
							{
								continue;
							}
							__result.Remove(__instance.Slot.opposingSlot);
							foreach (slotData item3 in extraAttack.slotsToAttack)
							{
								CardSlot slot = slotData.GetSlot(item3, item2);
								if ((Object)(object)slot != (Object)null)
								{
									__result.Add(slot);
								}
							}
						}
					}
				}
			}
		}
	}
	[HarmonyPatch]
	public class OnBoardCleanup_patch
	{
		[HarmonyPrefix]
		[HarmonyPatch(typeof(TurnManager), "CleanupPhase")]
		public static void CleanupPhase()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			foreach (CardSlot item in Singleton<BoardManager>.Instance.AllSlotsCopy)
			{
				if ((Object)(object)item.Card == (Object)null)
				{
					continue;
				}
				foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities())
				{
					if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility))
					{
						((Card)item.Card).Info.temporaryDecals.Clear();
						((Card)item.Card).RenderCard();
					}
				}
				foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities)
				{
					if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility))
					{
						((Card)item.Card).Info.temporaryDecals.Clear();
						((Card)item.Card).RenderCard();
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayableCard), "GetPassiveAttackBuffs")]
	public class PassiveAttackBuffs_patch
	{
		[HarmonyPostfix]
		public static void Postfix(ref int __result, ref PlayableCard __instance)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.OnBoard)
			{
				return;
			}
			foreach (CardSlot item in Singleton<BoardManager>.Instance.AllSlotsCopy)
			{
				if ((Object)(object)item.Card == (Object)null)
				{
					continue;
				}
				foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities())
				{
					if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility))
					{
						ApplyBuffs(SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour, item, ref __result, ref __instance);
					}
				}
				foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities)
				{
					if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility))
					{
						ApplyBuffs(SigilData.GetAbilityArguments(specialAbility).abilityBehaviour, item, ref __result, ref __instance);
					}
				}
			}
		}

		public static void ApplyBuffs(List<AbilityBehaviourData> AbilityBehaviourList, CardSlot slot, ref int __result, ref PlayableCard __instance)
		{
			foreach (AbilityBehaviourData item in AbilityBehaviourList.Where((AbilityBehaviourData x) => x.trigger?.triggerType == "Passive"))
			{
				if (item.buffCards == null)
				{
					continue;
				}
				foreach (buffCards buffCard in item.buffCards)
				{
					SigilData.UpdateVariables(item, slot.Card);
					if (SigilData.ConvertArgument(buffCard.runOnCondition, item, sendDebug: false) == "false")
					{
						continue;
					}
					CardSlot val = slotData.GetSlot(buffCard.slot, item, sendDebug: false);
					if (buffCard.slot == null)
					{
						val = slot;
					}
					if (!((Object)(object)val == (Object)(object)__instance.slot))
					{
						continue;
					}
					if (!string.IsNullOrEmpty(buffCard.addStats))
					{
						string text = SigilData.ConvertArgument(buffCard.addStats.Split(new char[1] { '/' })[0], item, sendDebug: false);
						if (text != "?")
						{
							__result += int.Parse(text);
						}
					}
					if (!string.IsNullOrEmpty(buffCard.setStats))
					{
						string text2 = SigilData.ConvertArgument(buffCard.setStats.Split(new char[1] { '/' })[0], item, sendDebug: false);
						if (text2 != "?")
						{
							__result = int.Parse(text2) - ((Card)slot.Card).Info.Attack;
						}
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(PlayableCard), "GetPassiveHealthBuffs")]
	public class PassiveHealthBuffs_patch
	{
		[HarmonyPostfix]
		public static void Postfix(ref int __result, ref PlayableCard __instance)
		{
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.OnBoard)
			{
				return;
			}
			foreach (CardSlot item in Singleton<BoardManager>.Instance.AllSlotsCopy)
			{
				if ((Object)(object)item.Card == (Object)null)
				{
					continue;
				}
				foreach (Ability triggeredAbility in item.Card.GetTriggeredAbilities())
				{
					if (SigilDicts.ArgumentList.ContainsKey(triggeredAbility))
					{
						ApplyBuffs(SigilData.GetAbilityArguments(triggeredAbility).abilityBehaviour, item, ref __result, ref __instance);
					}
				}
				foreach (SpecialTriggeredAbility specialAbility in ((Card)item.Card).Info.SpecialAbilities)
				{
					if (SigilDicts.SpecialArgumentList.ContainsKey(specialAbility))
					{
						ApplyBuffs(SigilData.GetAbilityArguments(specialAbility).abilityBehaviour, item, ref __result, ref __instance);
					}
				}
			}
		}

		public static void ApplyBuffs(List<AbilityBehaviourData> AbilityBehaviourList, CardSlot slot, ref int __result, ref PlayableCard __instance)
		{
			foreach (AbilityBehaviourData item in AbilityBehaviourList.Where((AbilityBehaviourData x) => x.trigger?.triggerType == "Passive"))
			{
				if (item.buffCards == null)
				{
					continue;
				}
				foreach (buffCards buffCard in item.buffCards)
				{
					SigilData.UpdateVariables(item, slot.Card);
					if (SigilData.ConvertArgument(buffCard.runOnCondition, item, sendDebug: false) == "false")
					{
						continue;
					}
					CardSlot val = slotData.GetSlot(buffCard.slot, item, sendDebug: false);
					if (buffCard.slot == null)
					{
						val = slot;
					}
					if (!((Object)(object)val == (Object)(object)__instance.slot))
					{
						continue;
					}
					if (!string.IsNullOrEmpty(buffCard.addStats))
					{
						string text = SigilData.ConvertArgument(buffCard.addStats.Split(new char[1] { '/' })[1], item, sendDebug: false);
						if (text != "?")
						{
							__result += int.Parse(text);
						}
					}
					if (!string.IsNullOrEmpty(buffCard.setStats))
					{
						string text2 = SigilData.ConvertArgument(buffCard.setStats.Split(new char[1] { '/' })[1], item, sendDebug: false);
						if (text2 != "?")
						{
							__result = int.Parse(text2) - ((Card)slot.Card).Info.Health;
						}
					}
					if (((Card)__instance).Info.Health + __result <= 0)
					{
						((MonoBehaviour)Singleton<BoardManager>.Instance).StartCoroutine(__instance.Die(false, (PlayableCard)null, true));
					}
				}
			}
		}
	}
	public static class CachedCardData
	{
		private static Dictionary<string, CardSerializeInfo> CardDataCache = new Dictionary<string, CardSerializeInfo>();

		public static CardSerializeInfo? Get(string filePath)
		{
			if (filePath == null)
			{
				return null;
			}
			if (!CardDataCache.ContainsKey(filePath))
			{
				return null;
			}
			return CardDataCache[filePath];
		}

		public static void Add(string filePath, CardSerializeInfo data)
		{
			CardDataCache[filePath] = data;
		}

		public static bool Contains(string? filePath)
		{
			return filePath != null && CardDataCache.ContainsKey(filePath);
		}

		public static void Flush()
		{
			CardDataCache.Clear();
		}
	}
	public class ConfigurableMain : ConfigurableBase, IOnBellRung, IOnOtherCardAddedToHand, IOnCardAssignedToSlotContext, IOnCardDealtDamageDirectly
	{
		public override int BonesCost => (abilityData.activationCost?.bonesCost).GetValueOrDefault();

		public override int EnergyCost => (abilityData.activationCost?.energyCost).GetValueOrDefault();

		public override int Priority => abilityData.priority.GetValueOrDefault();

		public override bool CanActivate()
		{
			AbilityBehaviourData abilityBehaviourData = abilityData.abilityBehaviour.Where((AbilityBehaviourData x) => x.trigger?.triggerType == "OnActivate").ToList()[0];
			if (abilityBehaviourData == null)
			{
				return false;
			}
			SigilData.UpdateVariables(abilityBehaviourData, base.PlayableCard);
			return (SigilData.ConvertArgument(abilityBehaviourData.trigger?.activatesForCardsWithCondition, abilityBehaviourData) ?? "true") == "true";
		}

		public override IEnumerator Activate()
		{
			int BloodCost = (abilityData.activationCost?.bloodCost).GetValueOrDefault();
			if (BloodCost > 0)
			{
				List<CardSlot> occupiedSlots = Singleton<BoardManager>.Instance.PlayerSlotsCopy.FindAll((CardSlot x) => (Object)(object)x.Card != (Object)null && (Object)(object)x.Card != (Object)(object)((AbilityBehaviour)this).Card);
				if (!((Object)(object)Singleton<BoardManager>.Instance != (Object)null) || Singleton<BoardManager>.Instance.AvailableSacrificeValueInSlots(occupiedSlots) < BloodCost)
				{
					((Card)base.PlayableCard).Anim.LightNegationEffect();
					AudioController.Instance.PlaySound2D("toneless_negate", (MixerGroup)10, 0.2f, 0f, (Pitch)null, (Repetition)null, (Randomization)null, (Distortion)null, false);
					yield return (object)new WaitForSeconds(0.25f);
					yield break;
				}
				Singleton<BoardManager>.Instance.CancelledSacrifice = false;
				yield return Singleton<BoardManager>.Instance.ChooseSacrificesForCard(occupiedSlots, ((AbilityBehaviour)this).Card, BloodCost);
				if (Singleton<BoardManager>.Instance.CancelledSacrifice)
				{
					yield break;
				}
			}
			List<GemType> GemCost = abilityData.activationCost?.gemsCost?.Select((string s) => ImportExportUtils.ParseEnum<GemType>(s)).ToList() ?? new List<GemType>();
			foreach (GemType Gem in GemCost)
			{
				if (!Singleton<ResourcesManager>.Instance.HasGem(Gem))
				{
					((Card)base.PlayableCard).Anim.LightNegationEffect();
					AudioController.Instance.PlaySound2D("toneless_negate", (MixerGroup)10, 0.2f, 0f, (Pitch)null, (Repetition)null, (Randomization)null, (Distortion)null, false);
					yield return (object)new WaitForSeconds(0.25f);
					yield break;
				}
			}
			yield return TriggerSigil("OnActivate");
		}

		public void Start()
		{
			if (abilityData?.abilityBehaviour == null)
			{
				return;
			}
			foreach (AbilityBehaviourData item in abilityData.abilityBehaviour)
			{
				item.TurnsInPlay = 0;
				string extendedProperty = CardExtensions.GetExtendedProperty(((Card)base.PlayableCard).Info, "JSONFilePath");
				if (extendedProperty != null)
				{
					if (!CachedCardData.Contains(extendedProperty))
					{
						CachedCardData.Add(extendedProperty, File.ReadAllText(extendedProperty).FromJson<CardSerializeInfo>());
					}
					CardSerializeInfo cardSerializeInfo = CachedCardData.Get(extendedProperty);
					if (cardSerializeInfo.extensionProperties != null)
					{
						foreach (KeyValuePair<string, string> extensionProperty in cardSerializeI

plugins/Libs/Antlr3.Runtime.dll

Decompiled 4 months ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using Antlr.Runtime.Debug;
using Antlr.Runtime.Misc;
using Antlr.Runtime.Tree;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Antlr3.Runtime")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Tunnel Vision Laboratories, LLC")]
[assembly: AssemblyProduct("Antlr3.Runtime")]
[assembly: AssemblyCopyright("Copyright © Sam Harwell 2013")]
[assembly: AssemblyTrademark("")]
[assembly: CLSCompliant(true)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComVisible(false)]
[assembly: Guid("7a0b4db7-f127-4cf5-ac2c-e294957efcd6")]
[assembly: AssemblyFileVersion("3.5.1.0")]
[assembly: AssemblyInformationalVersion("3.5.1")]
[assembly: AssemblyVersion("3.5.0.2")]
namespace Antlr.Runtime
{
	[Serializable]
	[FileIOPermission(SecurityAction.Demand, Unrestricted = true)]
	public class ANTLRFileStream : ANTLRStringStream
	{
		protected string fileName;

		public override string SourceName => fileName;

		public ANTLRFileStream(string fileName)
			: this(fileName, null)
		{
		}

		public ANTLRFileStream(string fileName, Encoding encoding)
		{
			this.fileName = fileName;
			Load(fileName, encoding);
		}

		public virtual void Load(string fileName, Encoding encoding)
		{
			if (fileName != null)
			{
				string text = ((encoding != null) ? File.ReadAllText(fileName, encoding) : File.ReadAllText(fileName));
				data = text.ToCharArray();
				n = data.Length;
			}
		}
	}
	[Serializable]
	public class ANTLRInputStream : ANTLRReaderStream
	{
		public ANTLRInputStream(Stream input)
			: this(input, null)
		{
		}

		public ANTLRInputStream(Stream input, int size)
			: this(input, size, null)
		{
		}

		public ANTLRInputStream(Stream input, Encoding encoding)
			: this(input, 1024, encoding)
		{
		}

		public ANTLRInputStream(Stream input, int size, Encoding encoding)
			: this(input, size, 1024, encoding)
		{
		}

		public ANTLRInputStream(Stream input, int size, int readBufferSize, Encoding encoding)
			: base(GetStreamReader(input, encoding), size, readBufferSize)
		{
		}

		private static StreamReader GetStreamReader(Stream input, Encoding encoding)
		{
			if (encoding != null)
			{
				return new StreamReader(input, encoding);
			}
			return new StreamReader(input);
		}
	}
	[Serializable]
	public class ANTLRReaderStream : ANTLRStringStream
	{
		public const int ReadBufferSize = 1024;

		public const int InitialBufferSize = 1024;

		public ANTLRReaderStream(TextReader r)
			: this(r, 1024, 1024)
		{
		}

		public ANTLRReaderStream(TextReader r, int size)
			: this(r, size, 1024)
		{
		}

		public ANTLRReaderStream(TextReader r, int size, int readChunkSize)
		{
			Load(r, size, readChunkSize);
		}

		public virtual void Load(TextReader r, int size, int readChunkSize)
		{
			if (r == null)
			{
				return;
			}
			if (size <= 0)
			{
				size = 1024;
			}
			if (readChunkSize <= 0)
			{
				readChunkSize = 1024;
			}
			try
			{
				data = r.ReadToEnd().ToCharArray();
				n = data.Length;
			}
			finally
			{
				r.Dispose();
			}
		}
	}
	[Serializable]
	public class ANTLRStringStream : ICharStream, IIntStream
	{
		protected char[] data;

		protected int n;

		protected int p;

		private int line = 1;

		private int charPositionInLine;

		protected int markDepth;

		protected IList<CharStreamState> markers;

		protected int lastMarker;

		public string name;

		public virtual int Index => p;

		public virtual int Line
		{
			get
			{
				return line;
			}
			set
			{
				line = value;
			}
		}

		public virtual int CharPositionInLine
		{
			get
			{
				return charPositionInLine;
			}
			set
			{
				charPositionInLine = value;
			}
		}

		public virtual int Count => n;

		public virtual string SourceName => name;

		public ANTLRStringStream(string input)
			: this(input, null)
		{
		}

		public ANTLRStringStream(string input, string sourceName)
			: this(input.ToCharArray(), input.Length, sourceName)
		{
		}

		public ANTLRStringStream(char[] data, int numberOfActualCharsInArray)
			: this(data, numberOfActualCharsInArray, null)
		{
		}

		public ANTLRStringStream(char[] data, int numberOfActualCharsInArray, string sourceName)
		{
			if (data == null)
			{
				throw new ArgumentNullException("data");
			}
			if (numberOfActualCharsInArray < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			if (numberOfActualCharsInArray > data.Length)
			{
				throw new ArgumentException();
			}
			this.data = data;
			n = numberOfActualCharsInArray;
			name = sourceName;
		}

		protected ANTLRStringStream()
		{
			data = new char[0];
		}

		public virtual void Reset()
		{
			p = 0;
			line = 1;
			charPositionInLine = 0;
			markDepth = 0;
		}

		public virtual void Consume()
		{
			if (p < n)
			{
				charPositionInLine++;
				if (data[p] == '\n')
				{
					line++;
					charPositionInLine = 0;
				}
				p++;
			}
		}

		public virtual int LA(int i)
		{
			if (i == 0)
			{
				return 0;
			}
			if (i < 0)
			{
				i++;
				if (p + i - 1 < 0)
				{
					return -1;
				}
			}
			if (p + i - 1 >= n)
			{
				return -1;
			}
			return data[p + i - 1];
		}

		public virtual int LT(int i)
		{
			return LA(i);
		}

		public virtual int Mark()
		{
			if (markers == null)
			{
				markers = new List<CharStreamState>();
				markers.Add(null);
			}
			markDepth++;
			CharStreamState charStreamState = null;
			if (markDepth >= markers.Count)
			{
				charStreamState = new CharStreamState();
				markers.Add(charStreamState);
			}
			else
			{
				charStreamState = markers[markDepth];
			}
			charStreamState.p = Index;
			charStreamState.line = Line;
			charStreamState.charPositionInLine = CharPositionInLine;
			lastMarker = markDepth;
			return markDepth;
		}

		public virtual void Rewind(int m)
		{
			if (m < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			CharStreamState charStreamState = markers[m];
			Seek(charStreamState.p);
			line = charStreamState.line;
			charPositionInLine = charStreamState.charPositionInLine;
			Release(m);
		}

		public virtual void Rewind()
		{
			Rewind(lastMarker);
		}

		public virtual void Release(int marker)
		{
			markDepth = marker;
			markDepth--;
		}

		public virtual void Seek(int index)
		{
			if (index <= p)
			{
				p = index;
				return;
			}
			while (p < index)
			{
				Consume();
			}
		}

		public virtual string Substring(int start, int length)
		{
			if (start < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			if (length < 0)
			{
				throw new ArgumentOutOfRangeException();
			}
			if (start + length > data.Length)
			{
				throw new ArgumentException();
			}
			if (length == 0)
			{
				return string.Empty;
			}
			return new string(data, start, length);
		}

		public override string ToString()
		{
			return new string(data);
		}
	}
	public class AstParserRuleReturnScope<TTree, TToken> : ParserRuleReturnScope<TToken>, IAstRuleReturnScope<TTree>, IAstRuleReturnScope, IRuleReturnScope
	{
		private TTree _tree;

		public TTree Tree
		{
			get
			{
				return _tree;
			}
			set
			{
				_tree = value;
			}
		}

		object IAstRuleReturnScope.Tree => Tree;
	}
	public abstract class BaseRecognizer
	{
		public const int MemoRuleFailed = -2;

		public const int MemoRuleUnknown = -1;

		public const int InitialFollowStackSize = 100;

		public const int DefaultTokenChannel = 0;

		public const int Hidden = 99;

		public const string NextTokenRuleName = "nextToken";

		protected internal RecognizerSharedState state;

		public TextWriter TraceDestination { get; set; }

		public virtual int NumberOfSyntaxErrors => state.syntaxErrors;

		public virtual int BacktrackingLevel
		{
			get
			{
				return state.backtracking;
			}
			set
			{
				state.backtracking = value;
			}
		}

		public virtual bool Failed => state.failed;

		public virtual string[] TokenNames => null;

		public virtual string GrammarFileName => null;

		public abstract string SourceName { get; }

		public virtual IDebugEventListener DebugListener => null;

		public BaseRecognizer()
			: this(new RecognizerSharedState())
		{
		}

		public BaseRecognizer(RecognizerSharedState state)
		{
			if (state == null)
			{
				state = new RecognizerSharedState();
			}
			this.state = state;
			InitDFAs();
		}

		public virtual void SetState(RecognizerSharedState value)
		{
			state = value;
		}

		protected virtual void InitDFAs()
		{
		}

		public virtual void Reset()
		{
			if (state != null)
			{
				state._fsp = -1;
				state.errorRecovery = false;
				state.lastErrorIndex = -1;
				state.failed = false;
				state.syntaxErrors = 0;
				state.backtracking = 0;
				int num = 0;
				while (state.ruleMemo != null && num < state.ruleMemo.Length)
				{
					state.ruleMemo[num] = null;
					num++;
				}
			}
		}

		public virtual object Match(IIntStream input, int ttype, BitSet follow)
		{
			object currentInputSymbol = GetCurrentInputSymbol(input);
			if (input.LA(1) == ttype)
			{
				input.Consume();
				state.errorRecovery = false;
				state.failed = false;
				return currentInputSymbol;
			}
			if (state.backtracking > 0)
			{
				state.failed = true;
				return currentInputSymbol;
			}
			return RecoverFromMismatchedToken(input, ttype, follow);
		}

		public virtual void MatchAny(IIntStream input)
		{
			state.errorRecovery = false;
			state.failed = false;
			input.Consume();
		}

		public virtual bool MismatchIsUnwantedToken(IIntStream input, int ttype)
		{
			return input.LA(2) == ttype;
		}

		public virtual bool MismatchIsMissingToken(IIntStream input, BitSet follow)
		{
			if (follow == null)
			{
				return false;
			}
			if (follow.Member(1))
			{
				BitSet a = ComputeContextSensitiveRuleFOLLOW();
				follow = follow.Or(a);
				if (state._fsp >= 0)
				{
					follow.Remove(1);
				}
			}
			if (follow.Member(input.LA(1)) || follow.Member(1))
			{
				return true;
			}
			return false;
		}

		public virtual void ReportError(RecognitionException e)
		{
			if (!state.errorRecovery)
			{
				state.syntaxErrors++;
				state.errorRecovery = true;
				DisplayRecognitionError(TokenNames, e);
			}
		}

		public virtual void DisplayRecognitionError(string[] tokenNames, RecognitionException e)
		{
			string errorHeader = GetErrorHeader(e);
			string errorMessage = GetErrorMessage(e, tokenNames);
			EmitErrorMessage(errorHeader + " " + errorMessage);
		}

		public virtual string GetErrorMessage(RecognitionException e, string[] tokenNames)
		{
			string result = e.Message;
			if (e is UnwantedTokenException)
			{
				UnwantedTokenException ex = (UnwantedTokenException)e;
				string text = "<unknown>";
				result = string.Concat(str3: (ex.Expecting != -1) ? tokenNames[ex.Expecting] : "EndOfFile", str0: "extraneous input ", str1: GetTokenErrorDisplay(ex.UnexpectedToken), str2: " expecting ");
			}
			else if (e is MissingTokenException)
			{
				MissingTokenException ex2 = (MissingTokenException)e;
				string text2 = "<unknown>";
				text2 = ((ex2.Expecting != -1) ? tokenNames[ex2.Expecting] : "EndOfFile");
				result = "missing " + text2 + " at " + GetTokenErrorDisplay(e.Token);
			}
			else if (e is MismatchedTokenException)
			{
				MismatchedTokenException ex3 = (MismatchedTokenException)e;
				string text3 = "<unknown>";
				result = string.Concat(str3: (ex3.Expecting != -1) ? tokenNames[ex3.Expecting] : "EndOfFile", str0: "mismatched input ", str1: GetTokenErrorDisplay(e.Token), str2: " expecting ");
			}
			else if (e is MismatchedTreeNodeException)
			{
				MismatchedTreeNodeException ex4 = (MismatchedTreeNodeException)e;
				string text4 = "<unknown>";
				text4 = ((ex4.Expecting != -1) ? tokenNames[ex4.Expecting] : "EndOfFile");
				string text5 = ((ex4.Node != null) ? (ex4.Node.ToString() ?? string.Empty) : string.Empty);
				result = "mismatched tree node: " + text5 + " expecting " + text4;
			}
			else if (e is NoViableAltException)
			{
				result = "no viable alternative at input " + GetTokenErrorDisplay(e.Token);
			}
			else if (e is EarlyExitException)
			{
				result = "required (...)+ loop did not match anything at input " + GetTokenErrorDisplay(e.Token);
			}
			else if (e is MismatchedSetException)
			{
				MismatchedSetException ex5 = (MismatchedSetException)e;
				result = "mismatched input " + GetTokenErrorDisplay(e.Token) + " expecting set " + ex5.Expecting;
			}
			else if (e is MismatchedNotSetException)
			{
				MismatchedNotSetException ex6 = (MismatchedNotSetException)e;
				result = "mismatched input " + GetTokenErrorDisplay(e.Token) + " expecting set " + ex6.Expecting;
			}
			else if (e is FailedPredicateException)
			{
				FailedPredicateException ex7 = (FailedPredicateException)e;
				result = "rule " + ex7.RuleName + " failed predicate: {" + ex7.PredicateText + "}?";
			}
			return result;
		}

		public virtual string GetErrorHeader(RecognitionException e)
		{
			string text = SourceName ?? string.Empty;
			if (text.Length > 0)
			{
				text += " ";
			}
			return $"{text}line {e.Line}:{e.CharPositionInLine + 1}";
		}

		public virtual string GetTokenErrorDisplay(IToken t)
		{
			string text = t.Text;
			if (text == null)
			{
				text = ((t.Type != -1) ? ("<" + t.Type + ">") : "<EOF>");
			}
			text = Regex.Replace(text, "\n", "\\\\n");
			text = Regex.Replace(text, "\r", "\\\\r");
			text = Regex.Replace(text, "\t", "\\\\t");
			return "'" + text + "'";
		}

		public virtual void EmitErrorMessage(string msg)
		{
			if (TraceDestination != null)
			{
				TraceDestination.WriteLine(msg);
			}
		}

		public virtual void Recover(IIntStream input, RecognitionException re)
		{
			if (state.lastErrorIndex == input.Index)
			{
				input.Consume();
			}
			state.lastErrorIndex = input.Index;
			BitSet set = ComputeErrorRecoverySet();
			BeginResync();
			ConsumeUntil(input, set);
			EndResync();
		}

		public virtual void BeginResync()
		{
		}

		public virtual void EndResync()
		{
		}

		protected virtual BitSet ComputeErrorRecoverySet()
		{
			return CombineFollows(exact: false);
		}

		protected virtual BitSet ComputeContextSensitiveRuleFOLLOW()
		{
			return CombineFollows(exact: true);
		}

		protected virtual BitSet CombineFollows(bool exact)
		{
			int fsp = state._fsp;
			BitSet bitSet = new BitSet();
			for (int num = fsp; num >= 0; num--)
			{
				BitSet bitSet2 = state.following[num];
				bitSet.OrInPlace(bitSet2);
				if (exact)
				{
					if (!bitSet2.Member(1))
					{
						break;
					}
					if (num > 0)
					{
						bitSet.Remove(1);
					}
				}
			}
			return bitSet;
		}

		protected virtual object RecoverFromMismatchedToken(IIntStream input, int ttype, BitSet follow)
		{
			RecognitionException e = null;
			if (MismatchIsUnwantedToken(input, ttype))
			{
				e = new UnwantedTokenException(ttype, input, TokenNames);
				BeginResync();
				input.Consume();
				EndResync();
				ReportError(e);
				object currentInputSymbol = GetCurrentInputSymbol(input);
				input.Consume();
				return currentInputSymbol;
			}
			if (MismatchIsMissingToken(input, follow))
			{
				object missingSymbol = GetMissingSymbol(input, e, ttype, follow);
				e = new MissingTokenException(ttype, input, missingSymbol);
				ReportError(e);
				return missingSymbol;
			}
			e = new MismatchedTokenException(ttype, input, TokenNames);
			throw e;
		}

		public virtual object RecoverFromMismatchedSet(IIntStream input, RecognitionException e, BitSet follow)
		{
			if (MismatchIsMissingToken(input, follow))
			{
				ReportError(e);
				return GetMissingSymbol(input, e, 0, follow);
			}
			throw e;
		}

		protected virtual object GetCurrentInputSymbol(IIntStream input)
		{
			return null;
		}

		protected virtual object GetMissingSymbol(IIntStream input, RecognitionException e, int expectedTokenType, BitSet follow)
		{
			return null;
		}

		public virtual void ConsumeUntil(IIntStream input, int tokenType)
		{
			int num = input.LA(1);
			while (num != -1 && num != tokenType)
			{
				input.Consume();
				num = input.LA(1);
			}
		}

		public virtual void ConsumeUntil(IIntStream input, BitSet set)
		{
			int num = input.LA(1);
			while (num != -1 && !set.Member(num))
			{
				input.Consume();
				num = input.LA(1);
			}
		}

		protected void PushFollow(BitSet fset)
		{
			if (state._fsp + 1 >= state.following.Length)
			{
				Array.Resize(ref state.following, state.following.Length * 2);
			}
			state.following[++state._fsp] = fset;
		}

		protected void PopFollow()
		{
			state._fsp--;
		}

		public virtual IList<string> GetRuleInvocationStack()
		{
			return GetRuleInvocationStack(new StackTrace(fNeedFileInfo: true));
		}

		public static IList<string> GetRuleInvocationStack(StackTrace trace)
		{
			if (trace == null)
			{
				throw new ArgumentNullException("trace");
			}
			List<string> list = new List<string>();
			StackFrame[] array = trace.GetFrames() ?? new StackFrame[0];
			for (int num = array.Length - 1; num >= 0; num--)
			{
				GrammarRuleAttribute[] array2 = (GrammarRuleAttribute[])array[num].GetMethod().GetCustomAttributes(typeof(GrammarRuleAttribute), inherit: true);
				if (array2 != null && array2.Length != 0)
				{
					list.Add(array2[0].Name);
				}
			}
			return list;
		}

		public virtual List<string> ToStrings(ICollection<IToken> tokens)
		{
			if (tokens == null)
			{
				return null;
			}
			List<string> list = new List<string>(tokens.Count);
			foreach (IToken token in tokens)
			{
				list.Add(token.Text);
			}
			return list;
		}

		public virtual int GetRuleMemoization(int ruleIndex, int ruleStartIndex)
		{
			if (state.ruleMemo[ruleIndex] == null)
			{
				state.ruleMemo[ruleIndex] = new Dictionary<int, int>();
			}
			if (!state.ruleMemo[ruleIndex].TryGetValue(ruleStartIndex, out var value))
			{
				return -1;
			}
			return value;
		}

		public virtual bool AlreadyParsedRule(IIntStream input, int ruleIndex)
		{
			int ruleMemoization = GetRuleMemoization(ruleIndex, input.Index);
			switch (ruleMemoization)
			{
			case -1:
				return false;
			case -2:
				state.failed = true;
				break;
			default:
				input.Seek(ruleMemoization + 1);
				break;
			}
			return true;
		}

		public virtual void Memoize(IIntStream input, int ruleIndex, int ruleStartIndex)
		{
			int value = (state.failed ? (-2) : (input.Index - 1));
			if (state.ruleMemo == null && TraceDestination != null)
			{
				TraceDestination.WriteLine("!!!!!!!!! memo array is null for " + GrammarFileName);
			}
			if (ruleIndex >= state.ruleMemo.Length && TraceDestination != null)
			{
				TraceDestination.WriteLine("!!!!!!!!! memo size is " + state.ruleMemo.Length + ", but rule index is " + ruleIndex);
			}
			if (state.ruleMemo[ruleIndex] != null)
			{
				state.ruleMemo[ruleIndex][ruleStartIndex] = value;
			}
		}

		public virtual int GetRuleMemoizationCacheSize()
		{
			int num = 0;
			int num2 = 0;
			while (state.ruleMemo != null && num2 < state.ruleMemo.Length)
			{
				IDictionary<int, int> dictionary = state.ruleMemo[num2];
				if (dictionary != null)
				{
					num += dictionary.Count;
				}
				num2++;
			}
			return num;
		}

		public virtual void TraceIn(string ruleName, int ruleIndex, object inputSymbol)
		{
			if (TraceDestination != null)
			{
				TraceDestination.Write("enter " + ruleName + " " + inputSymbol);
				if (state.backtracking > 0)
				{
					TraceDestination.Write(" backtracking=" + state.backtracking);
				}
				TraceDestination.WriteLine();
			}
		}

		public virtual void TraceOut(string ruleName, int ruleIndex, object inputSymbol)
		{
			if (TraceDestination == null)
			{
				return;
			}
			TraceDestination.Write("exit " + ruleName + " " + inputSymbol);
			if (state.backtracking > 0)
			{
				TraceDestination.Write(" backtracking=" + state.backtracking);
				if (state.failed)
				{
					TraceDestination.Write(" failed");
				}
				else
				{
					TraceDestination.Write(" succeeded");
				}
			}
			TraceDestination.WriteLine();
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugEnterRule(string grammarFileName, string ruleName)
		{
			DebugListener?.EnterRule(grammarFileName, ruleName);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugExitRule(string grammarFileName, string ruleName)
		{
			DebugListener?.ExitRule(grammarFileName, ruleName);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugEnterSubRule(int decisionNumber)
		{
			DebugListener?.EnterSubRule(decisionNumber);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugExitSubRule(int decisionNumber)
		{
			DebugListener?.ExitSubRule(decisionNumber);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugEnterAlt(int alt)
		{
			DebugListener?.EnterAlt(alt);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugEnterDecision(int decisionNumber, bool couldBacktrack)
		{
			DebugListener?.EnterDecision(decisionNumber, couldBacktrack);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugExitDecision(int decisionNumber)
		{
			DebugListener?.ExitDecision(decisionNumber);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugLocation(int line, int charPositionInLine)
		{
			DebugListener?.Location(line, charPositionInLine);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugSemanticPredicate(bool result, string predicate)
		{
			DebugListener?.SemanticPredicate(result, predicate);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugBeginBacktrack(int level)
		{
			DebugListener?.BeginBacktrack(level);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugEndBacktrack(int level, bool successful)
		{
			DebugListener?.EndBacktrack(level, successful);
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugRecognitionException(RecognitionException ex)
		{
			DebugListener?.RecognitionException(ex);
		}
	}
	[Serializable]
	public sealed class BitSet : ICloneable
	{
		private const int BITS = 64;

		private const int LOG_BITS = 6;

		private const int MOD_MASK = 63;

		private ulong[] _bits;

		public BitSet()
			: this(64)
		{
		}

		[CLSCompliant(false)]
		public BitSet(ulong[] bits)
		{
			_bits = bits;
		}

		public BitSet(IEnumerable<int> items)
			: this()
		{
			foreach (int item in items)
			{
				Add(item);
			}
		}

		public BitSet(int nbits)
		{
			_bits = new ulong[(nbits - 1 >> 6) + 1];
		}

		public static BitSet Of(int el)
		{
			BitSet bitSet = new BitSet(el + 1);
			bitSet.Add(el);
			return bitSet;
		}

		public static BitSet Of(int a, int b)
		{
			BitSet bitSet = new BitSet(Math.Max(a, b) + 1);
			bitSet.Add(a);
			bitSet.Add(b);
			return bitSet;
		}

		public static BitSet Of(int a, int b, int c)
		{
			BitSet bitSet = new BitSet();
			bitSet.Add(a);
			bitSet.Add(b);
			bitSet.Add(c);
			return bitSet;
		}

		public static BitSet Of(int a, int b, int c, int d)
		{
			BitSet bitSet = new BitSet();
			bitSet.Add(a);
			bitSet.Add(b);
			bitSet.Add(c);
			bitSet.Add(d);
			return bitSet;
		}

		public BitSet Or(BitSet a)
		{
			if (a == null)
			{
				return this;
			}
			BitSet obj = (BitSet)Clone();
			obj.OrInPlace(a);
			return obj;
		}

		public void Add(int el)
		{
			int num = WordNumber(el);
			if (num >= _bits.Length)
			{
				GrowToInclude(el);
			}
			_bits[num] |= BitMask(el);
		}

		public void GrowToInclude(int bit)
		{
			int size = Math.Max(_bits.Length << 1, NumWordsToHold(bit));
			SetSize(size);
		}

		public void OrInPlace(BitSet a)
		{
			if (a != null)
			{
				if (a._bits.Length > _bits.Length)
				{
					SetSize(a._bits.Length);
				}
				for (int num = Math.Min(_bits.Length, a._bits.Length) - 1; num >= 0; num--)
				{
					_bits[num] |= a._bits[num];
				}
			}
		}

		private void SetSize(int nwords)
		{
			Array.Resize(ref _bits, nwords);
		}

		private static ulong BitMask(int bitNumber)
		{
			int num = bitNumber & 0x3F;
			return (ulong)(1L << num);
		}

		public object Clone()
		{
			return new BitSet((ulong[])_bits.Clone());
		}

		public int Size()
		{
			int num = 0;
			for (int num2 = _bits.Length - 1; num2 >= 0; num2--)
			{
				ulong num3 = _bits[num2];
				if (num3 != 0L)
				{
					for (int num4 = 63; num4 >= 0; num4--)
					{
						if ((num3 & (ulong)(1L << num4)) != 0L)
						{
							num++;
						}
					}
				}
			}
			return num;
		}

		public override int GetHashCode()
		{
			throw new NotImplementedException();
		}

		public override bool Equals(object other)
		{
			if (other == null || !(other is BitSet))
			{
				return false;
			}
			BitSet bitSet = (BitSet)other;
			int num = Math.Min(_bits.Length, bitSet._bits.Length);
			for (int i = 0; i < num; i++)
			{
				if (_bits[i] != bitSet._bits[i])
				{
					return false;
				}
			}
			if (_bits.Length > num)
			{
				for (int j = num + 1; j < _bits.Length; j++)
				{
					if (_bits[j] != 0L)
					{
						return false;
					}
				}
			}
			else if (bitSet._bits.Length > num)
			{
				for (int k = num + 1; k < bitSet._bits.Length; k++)
				{
					if (bitSet._bits[k] != 0L)
					{
						return false;
					}
				}
			}
			return true;
		}

		public bool Member(int el)
		{
			if (el < 0)
			{
				return false;
			}
			int num = WordNumber(el);
			if (num >= _bits.Length)
			{
				return false;
			}
			return (_bits[num] & BitMask(el)) != 0;
		}

		public void Remove(int el)
		{
			int num = WordNumber(el);
			if (num < _bits.Length)
			{
				_bits[num] &= ~BitMask(el);
			}
		}

		public bool IsNil()
		{
			for (int num = _bits.Length - 1; num >= 0; num--)
			{
				if (_bits[num] != 0L)
				{
					return false;
				}
			}
			return true;
		}

		private static int NumWordsToHold(int el)
		{
			return (el >> 6) + 1;
		}

		public int NumBits()
		{
			return _bits.Length << 6;
		}

		public int LengthInLongWords()
		{
			return _bits.Length;
		}

		public int[] ToArray()
		{
			int[] array = new int[Size()];
			int num = 0;
			for (int i = 0; i < _bits.Length << 6; i++)
			{
				if (Member(i))
				{
					array[num++] = i;
				}
			}
			return array;
		}

		private static int WordNumber(int bit)
		{
			return bit >> 6;
		}

		public override string ToString()
		{
			return ToString(null);
		}

		public string ToString(string[] tokenNames)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string value = ",";
			bool flag = false;
			stringBuilder.Append('{');
			for (int i = 0; i < _bits.Length << 6; i++)
			{
				if (Member(i))
				{
					if (i > 0 && flag)
					{
						stringBuilder.Append(value);
					}
					if (tokenNames != null)
					{
						stringBuilder.Append(tokenNames[i]);
					}
					else
					{
						stringBuilder.Append(i);
					}
					flag = true;
				}
			}
			stringBuilder.Append('}');
			return stringBuilder.ToString();
		}
	}
	[Serializable]
	public class BufferedTokenStream : ITokenStream, IIntStream, ITokenStreamInformation
	{
		private ITokenSource _tokenSource;

		[CLSCompliant(false)]
		protected List<IToken> _tokens = new List<IToken>(100);

		private int _lastMarker;

		[CLSCompliant(false)]
		protected int _p = -1;

		public virtual ITokenSource TokenSource
		{
			get
			{
				return _tokenSource;
			}
			set
			{
				_tokenSource = value;
				_tokens.Clear();
				_p = -1;
			}
		}

		public virtual int Index => _p;

		public virtual int Range { get; protected set; }

		public virtual int Count => _tokens.Count;

		public virtual string SourceName => _tokenSource.SourceName;

		public virtual IToken LastToken => LB(1);

		public virtual IToken LastRealToken
		{
			get
			{
				int num = 0;
				IToken token;
				do
				{
					num++;
					token = LB(num);
				}
				while (token != null && token.Line <= 0);
				return token;
			}
		}

		public virtual int MaxLookBehind => int.MaxValue;

		public BufferedTokenStream()
		{
		}

		public BufferedTokenStream(ITokenSource tokenSource)
		{
			_tokenSource = tokenSource;
		}

		public virtual int Mark()
		{
			if (_p == -1)
			{
				Setup();
			}
			_lastMarker = Index;
			return _lastMarker;
		}

		public virtual void Release(int marker)
		{
		}

		public virtual void Rewind(int marker)
		{
			Seek(marker);
		}

		public virtual void Rewind()
		{
			Seek(_lastMarker);
		}

		public virtual void Reset()
		{
			_p = 0;
			_lastMarker = 0;
		}

		public virtual void Seek(int index)
		{
			_p = index;
		}

		public virtual void Consume()
		{
			if (_p == -1)
			{
				Setup();
			}
			_p++;
			Sync(_p);
		}

		protected virtual void Sync(int i)
		{
			int num = i - _tokens.Count + 1;
			if (num > 0)
			{
				Fetch(num);
			}
		}

		protected virtual void Fetch(int n)
		{
			for (int i = 0; i < n; i++)
			{
				IToken token = TokenSource.NextToken();
				token.TokenIndex = _tokens.Count;
				_tokens.Add(token);
				if (token.Type == -1)
				{
					break;
				}
			}
		}

		public virtual IToken Get(int i)
		{
			if (i < 0 || i >= _tokens.Count)
			{
				throw new IndexOutOfRangeException("token index " + i + " out of range 0.." + (_tokens.Count - 1));
			}
			return _tokens[i];
		}

		public virtual int LA(int i)
		{
			return LT(i).Type;
		}

		protected virtual IToken LB(int k)
		{
			if (_p - k < 0)
			{
				return null;
			}
			return _tokens[_p - k];
		}

		public virtual IToken LT(int k)
		{
			if (_p == -1)
			{
				Setup();
			}
			if (k == 0)
			{
				return null;
			}
			if (k < 0)
			{
				return LB(-k);
			}
			int num = _p + k - 1;
			Sync(num);
			if (num >= _tokens.Count)
			{
				return _tokens[_tokens.Count - 1];
			}
			if (num > Range)
			{
				Range = num;
			}
			return _tokens[_p + k - 1];
		}

		protected virtual void Setup()
		{
			Sync(0);
			_p = 0;
		}

		public virtual List<IToken> GetTokens()
		{
			return _tokens;
		}

		public virtual List<IToken> GetTokens(int start, int stop)
		{
			return GetTokens(start, stop, (BitSet)null);
		}

		public virtual List<IToken> GetTokens(int start, int stop, BitSet types)
		{
			if (_p == -1)
			{
				Setup();
			}
			if (stop >= _tokens.Count)
			{
				stop = _tokens.Count - 1;
			}
			if (start < 0)
			{
				start = 0;
			}
			if (start > stop)
			{
				return null;
			}
			List<IToken> list = new List<IToken>();
			for (int i = start; i <= stop; i++)
			{
				IToken token = _tokens[i];
				if (types == null || types.Member(token.Type))
				{
					list.Add(token);
				}
			}
			if (list.Count == 0)
			{
				list = null;
			}
			return list;
		}

		public virtual List<IToken> GetTokens(int start, int stop, IEnumerable<int> types)
		{
			return GetTokens(start, stop, new BitSet(types));
		}

		public virtual List<IToken> GetTokens(int start, int stop, int ttype)
		{
			return GetTokens(start, stop, BitSet.Of(ttype));
		}

		public override string ToString()
		{
			if (_p == -1)
			{
				Setup();
			}
			Fill();
			return ToString(0, _tokens.Count - 1);
		}

		public virtual string ToString(int start, int stop)
		{
			if (start < 0 || stop < 0)
			{
				return null;
			}
			if (_p == -1)
			{
				Setup();
			}
			if (stop >= _tokens.Count)
			{
				stop = _tokens.Count - 1;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = start; i <= stop; i++)
			{
				IToken token = _tokens[i];
				if (token.Type == -1)
				{
					break;
				}
				stringBuilder.Append(token.Text);
			}
			return stringBuilder.ToString();
		}

		public virtual string ToString(IToken start, IToken stop)
		{
			if (start != null && stop != null)
			{
				return ToString(start.TokenIndex, stop.TokenIndex);
			}
			return null;
		}

		public virtual void Fill()
		{
			if (_p == -1)
			{
				Setup();
			}
			if (_tokens[_p].Type != -1)
			{
				int num = _p + 1;
				Sync(num);
				while (_tokens[num].Type != -1)
				{
					num++;
					Sync(num);
				}
			}
		}
	}
	public static class CharStreamConstants
	{
		public const int EndOfFile = -1;
	}
	[Serializable]
	public class CharStreamState
	{
		public int p;

		public int line;

		public int charPositionInLine;
	}
	[Serializable]
	public class ClassicToken : IToken
	{
		private string text;

		private int type;

		private int line;

		private int charPositionInLine;

		private int channel;

		private int index;

		public string Text
		{
			get
			{
				return text;
			}
			set
			{
				text = value;
			}
		}

		public int Type
		{
			get
			{
				return type;
			}
			set
			{
				type = value;
			}
		}

		public int Line
		{
			get
			{
				return line;
			}
			set
			{
				line = value;
			}
		}

		public int CharPositionInLine
		{
			get
			{
				return charPositionInLine;
			}
			set
			{
				charPositionInLine = value;
			}
		}

		public int Channel
		{
			get
			{
				return channel;
			}
			set
			{
				channel = value;
			}
		}

		public int StartIndex
		{
			get
			{
				return -1;
			}
			set
			{
			}
		}

		public int StopIndex
		{
			get
			{
				return -1;
			}
			set
			{
			}
		}

		public int TokenIndex
		{
			get
			{
				return index;
			}
			set
			{
				index = value;
			}
		}

		public ICharStream InputStream
		{
			get
			{
				return null;
			}
			set
			{
			}
		}

		public ClassicToken(int type)
		{
			this.type = type;
		}

		public ClassicToken(IToken oldToken)
		{
			text = oldToken.Text;
			type = oldToken.Type;
			line = oldToken.Line;
			charPositionInLine = oldToken.CharPositionInLine;
			channel = oldToken.Channel;
		}

		public ClassicToken(int type, string text)
		{
			this.type = type;
			this.text = text;
		}

		public ClassicToken(int type, string text, int channel)
		{
			this.type = type;
			this.text = text;
			this.channel = channel;
		}

		public override string ToString()
		{
			string text = "";
			if (channel > 0)
			{
				text = ",channel=" + channel;
			}
			string text2 = Text;
			if (text2 != null)
			{
				text2 = text2.Replace("\n", "\\\\n");
				text2 = text2.Replace("\r", "\\\\r");
				text2 = text2.Replace("\t", "\\\\t");
			}
			else
			{
				text2 = "<no text>";
			}
			return "[@" + TokenIndex + ",'" + text2 + "',<" + type + ">" + text + "," + line + ":" + CharPositionInLine + "]";
		}
	}
	[Serializable]
	public class CommonToken : IToken
	{
		private int type;

		private int line;

		private int charPositionInLine = -1;

		private int channel;

		[NonSerialized]
		private ICharStream input;

		private string text;

		private int index = -1;

		private int start;

		private int stop;

		public string Text
		{
			get
			{
				if (text != null)
				{
					return text;
				}
				if (input == null)
				{
					return null;
				}
				if (start <= stop && stop < input.Count)
				{
					return input.Substring(start, stop - start + 1);
				}
				return "<EOF>";
			}
			set
			{
				text = value;
			}
		}

		public int Type
		{
			get
			{
				return type;
			}
			set
			{
				type = value;
			}
		}

		public int Line
		{
			get
			{
				return line;
			}
			set
			{
				line = value;
			}
		}

		public int CharPositionInLine
		{
			get
			{
				return charPositionInLine;
			}
			set
			{
				charPositionInLine = value;
			}
		}

		public int Channel
		{
			get
			{
				return channel;
			}
			set
			{
				channel = value;
			}
		}

		public int StartIndex
		{
			get
			{
				return start;
			}
			set
			{
				start = value;
			}
		}

		public int StopIndex
		{
			get
			{
				return stop;
			}
			set
			{
				stop = value;
			}
		}

		public int TokenIndex
		{
			get
			{
				return index;
			}
			set
			{
				index = value;
			}
		}

		public ICharStream InputStream
		{
			get
			{
				return input;
			}
			set
			{
				input = value;
			}
		}

		public CommonToken()
		{
		}

		public CommonToken(int type)
		{
			this.type = type;
		}

		public CommonToken(ICharStream input, int type, int channel, int start, int stop)
		{
			this.input = input;
			this.type = type;
			this.channel = channel;
			this.start = start;
			this.stop = stop;
		}

		public CommonToken(int type, string text)
		{
			this.type = type;
			channel = 0;
			this.text = text;
		}

		public CommonToken(IToken oldToken)
		{
			text = oldToken.Text;
			type = oldToken.Type;
			line = oldToken.Line;
			index = oldToken.TokenIndex;
			charPositionInLine = oldToken.CharPositionInLine;
			channel = oldToken.Channel;
			input = oldToken.InputStream;
			if (oldToken is CommonToken)
			{
				start = ((CommonToken)oldToken).start;
				stop = ((CommonToken)oldToken).stop;
			}
		}

		public override string ToString()
		{
			string text = "";
			if (channel > 0)
			{
				text = ",channel=" + channel;
			}
			string text2 = Text;
			if (text2 != null)
			{
				text2 = Regex.Replace(text2, "\n", "\\\\n");
				text2 = Regex.Replace(text2, "\r", "\\\\r");
				text2 = Regex.Replace(text2, "\t", "\\\\t");
			}
			else
			{
				text2 = "<no text>";
			}
			return "[@" + TokenIndex + "," + start + ":" + stop + "='" + text2 + "',<" + type + ">" + text + "," + line + ":" + CharPositionInLine + "]";
		}

		[OnSerializing]
		internal void OnSerializing(StreamingContext context)
		{
			if (text == null)
			{
				text = Text;
			}
		}
	}
	[Serializable]
	public class CommonTokenStream : BufferedTokenStream
	{
		private int _channel;

		public int Channel => _channel;

		public override ITokenSource TokenSource
		{
			get
			{
				return base.TokenSource;
			}
			set
			{
				base.TokenSource = value;
				_channel = 0;
			}
		}

		public CommonTokenStream()
		{
		}

		public CommonTokenStream(ITokenSource tokenSource)
			: this(tokenSource, 0)
		{
		}

		public CommonTokenStream(ITokenSource tokenSource, int channel)
			: base(tokenSource)
		{
			_channel = channel;
		}

		public override void Consume()
		{
			if (_p == -1)
			{
				Setup();
			}
			_p++;
			_p = SkipOffTokenChannels(_p);
		}

		protected override IToken LB(int k)
		{
			if (k == 0 || _p - k < 0)
			{
				return null;
			}
			int num = _p;
			for (int i = 1; i <= k; i++)
			{
				num = SkipOffTokenChannelsReverse(num - 1);
			}
			if (num < 0)
			{
				return null;
			}
			return _tokens[num];
		}

		public override IToken LT(int k)
		{
			if (_p == -1)
			{
				Setup();
			}
			if (k == 0)
			{
				return null;
			}
			if (k < 0)
			{
				return LB(-k);
			}
			int num = _p;
			for (int i = 1; i < k; i++)
			{
				num = SkipOffTokenChannels(num + 1);
			}
			if (num > Range)
			{
				Range = num;
			}
			return _tokens[num];
		}

		protected virtual int SkipOffTokenChannels(int i)
		{
			Sync(i);
			while (_tokens[i].Channel != _channel)
			{
				i++;
				Sync(i);
			}
			return i;
		}

		protected virtual int SkipOffTokenChannelsReverse(int i)
		{
			while (i >= 0 && _tokens[i].Channel != _channel)
			{
				i--;
			}
			return i;
		}

		public override void Reset()
		{
			base.Reset();
			_p = SkipOffTokenChannels(0);
		}

		protected override void Setup()
		{
			_p = 0;
			_p = SkipOffTokenChannels(_p);
		}
	}
	public delegate int SpecialStateTransitionHandler(DFA dfa, int s, IIntStream input);
	public class DFA
	{
		protected short[] eot;

		protected short[] eof;

		protected char[] min;

		protected char[] max;

		protected short[] accept;

		protected short[] special;

		protected short[][] transition;

		protected int decisionNumber;

		protected BaseRecognizer recognizer;

		public bool debug;

		public virtual string Description => "n/a";

		public SpecialStateTransitionHandler SpecialStateTransition { get; private set; }

		public DFA()
			: this(SpecialStateTransitionDefault)
		{
		}

		public DFA(SpecialStateTransitionHandler specialStateTransition)
		{
			SpecialStateTransition = specialStateTransition ?? new SpecialStateTransitionHandler(SpecialStateTransitionDefault);
		}

		public virtual int Predict(IIntStream input)
		{
			if (input == null)
			{
				throw new ArgumentNullException("input");
			}
			int marker = input.Mark();
			int num = 0;
			try
			{
				char c;
				while (true)
				{
					int num2 = special[num];
					if (num2 >= 0)
					{
						num = SpecialStateTransition(this, num2, input);
						if (num == -1)
						{
							NoViableAlt(num, input);
							return 0;
						}
						input.Consume();
						continue;
					}
					if (accept[num] >= 1)
					{
						return accept[num];
					}
					c = (char)input.LA(1);
					if (c >= min[num] && c <= max[num])
					{
						int num3 = transition[num][c - min[num]];
						if (num3 < 0)
						{
							if (eot[num] < 0)
							{
								NoViableAlt(num, input);
								return 0;
							}
							num = eot[num];
							input.Consume();
						}
						else
						{
							num = num3;
							input.Consume();
						}
					}
					else
					{
						if (eot[num] < 0)
						{
							break;
						}
						num = eot[num];
						input.Consume();
					}
				}
				if (c == '\uffff' && eof[num] >= 0)
				{
					return accept[eof[num]];
				}
				NoViableAlt(num, input);
				return 0;
			}
			finally
			{
				input.Rewind(marker);
			}
		}

		[Conditional("DEBUG_DFA")]
		private void DfaDebugMessage(string format, params object[] args)
		{
			Console.Error.WriteLine(format, args);
		}

		[Conditional("DEBUG_DFA")]
		private void DfaDebugInvalidSymbol(int s)
		{
			Console.Error.WriteLine("min[{0}]={1}", s, min[s]);
			Console.Error.WriteLine("max[{0}]={1}", s, max[s]);
			Console.Error.WriteLine("eot[{0}]={1}", s, eot[s]);
			Console.Error.WriteLine("eof[{0}]={1}", s, eof[s]);
			for (int i = 0; i < transition[s].Length; i++)
			{
				Console.Error.Write(transition[s][i] + " ");
			}
			Console.Error.WriteLine();
		}

		protected virtual void NoViableAlt(int s, IIntStream input)
		{
			if (recognizer.state.backtracking > 0)
			{
				recognizer.state.failed = true;
				return;
			}
			NoViableAltException ex = new NoViableAltException(Description, decisionNumber, s, input);
			Error(ex);
			throw ex;
		}

		public virtual void Error(NoViableAltException nvae)
		{
		}

		private static int SpecialStateTransitionDefault(DFA dfa, int s, IIntStream input)
		{
			return -1;
		}

		public static short[] UnpackEncodedString(string encodedString)
		{
			int num = 0;
			for (int i = 0; i < encodedString.Length; i += 2)
			{
				num += encodedString[i];
			}
			short[] array = new short[num];
			int num2 = 0;
			for (int j = 0; j < encodedString.Length; j += 2)
			{
				char c = encodedString[j];
				char c2 = encodedString[j + 1];
				for (int k = 1; k <= c; k++)
				{
					array[num2++] = (short)c2;
				}
			}
			return array;
		}

		public static char[] UnpackEncodedStringToUnsignedChars(string encodedString)
		{
			int num = 0;
			for (int i = 0; i < encodedString.Length; i += 2)
			{
				num += encodedString[i];
			}
			char[] array = new char[num];
			int num2 = 0;
			for (int j = 0; j < encodedString.Length; j += 2)
			{
				char c = encodedString[j];
				char c2 = encodedString[j + 1];
				for (int k = 1; k <= c; k++)
				{
					array[num2++] = c2;
				}
			}
			return array;
		}

		[Conditional("ANTLR_DEBUG")]
		protected virtual void DebugRecognitionException(RecognitionException ex)
		{
			recognizer.DebugListener?.RecognitionException(ex);
		}
	}
	[Serializable]
	public class EarlyExitException : RecognitionException
	{
		private readonly int _decisionNumber;

		public int DecisionNumber => _decisionNumber;

		public EarlyExitException()
		{
		}

		public EarlyExitException(string message)
			: base(message)
		{
		}

		public EarlyExitException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public EarlyExitException(int decisionNumber, IIntStream input)
			: base(input)
		{
			_decisionNumber = decisionNumber;
		}

		public EarlyExitException(string message, int decisionNumber, IIntStream input)
			: base(message, input)
		{
			_decisionNumber = decisionNumber;
		}

		public EarlyExitException(string message, int decisionNumber, IIntStream input, Exception innerException)
			: base(message, input, innerException)
		{
			_decisionNumber = decisionNumber;
		}

		protected EarlyExitException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_decisionNumber = info.GetInt32("DecisionNumber");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("DecisionNumber", DecisionNumber);
		}
	}
	[Serializable]
	public class FailedPredicateException : RecognitionException
	{
		private readonly string _ruleName;

		private readonly string _predicateText;

		public string RuleName => _ruleName;

		public string PredicateText => _predicateText;

		public FailedPredicateException()
		{
		}

		public FailedPredicateException(string message)
			: base(message)
		{
		}

		public FailedPredicateException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public FailedPredicateException(IIntStream input, string ruleName, string predicateText)
			: base(input)
		{
			_ruleName = ruleName;
			_predicateText = predicateText;
		}

		public FailedPredicateException(string message, IIntStream input, string ruleName, string predicateText)
			: base(message, input)
		{
			_ruleName = ruleName;
			_predicateText = predicateText;
		}

		public FailedPredicateException(string message, IIntStream input, string ruleName, string predicateText, Exception innerException)
			: base(message, input, innerException)
		{
			_ruleName = ruleName;
			_predicateText = predicateText;
		}

		protected FailedPredicateException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_ruleName = info.GetString("RuleName");
			_predicateText = info.GetString("PredicateText");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("RuleName", _ruleName);
			info.AddValue("PredicateText", _predicateText);
		}

		public override string ToString()
		{
			return "FailedPredicateException(" + RuleName + ",{" + PredicateText + "}?)";
		}
	}
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
	public sealed class GrammarRuleAttribute : Attribute
	{
		private readonly string _name;

		public string Name => _name;

		public GrammarRuleAttribute(string name)
		{
			_name = name;
		}
	}
	public interface IAstRuleReturnScope : IRuleReturnScope
	{
		object Tree { get; }
	}
	public interface IAstRuleReturnScope<TAstLabel> : IAstRuleReturnScope, IRuleReturnScope
	{
		new TAstLabel Tree { get; }
	}
	public interface ICharStream : IIntStream
	{
		int Line { get; set; }

		int CharPositionInLine { get; set; }

		string Substring(int start, int length);

		int LT(int i);
	}
	public interface IIntStream
	{
		int Index { get; }

		int Count { get; }

		string SourceName { get; }

		void Consume();

		int LA(int i);

		int Mark();

		void Rewind(int marker);

		void Rewind();

		void Release(int marker);

		void Seek(int index);
	}
	public interface IRuleReturnScope
	{
		object Start { get; }

		object Stop { get; }
	}
	public interface IRuleReturnScope<TLabel> : IRuleReturnScope
	{
		new TLabel Start { get; }

		new TLabel Stop { get; }
	}
	public interface ITemplateRuleReturnScope
	{
		object Template { get; }
	}
	public interface ITemplateRuleReturnScope<TTemplate> : ITemplateRuleReturnScope
	{
		new TTemplate Template { get; }
	}
	public interface IToken
	{
		string Text { get; set; }

		int Type { get; set; }

		int Line { get; set; }

		int CharPositionInLine { get; set; }

		int Channel { get; set; }

		int StartIndex { get; set; }

		int StopIndex { get; set; }

		int TokenIndex { get; set; }

		ICharStream InputStream { get; set; }
	}
	public interface ITokenSource
	{
		string SourceName { get; }

		string[] TokenNames { get; }

		IToken NextToken();
	}
	public interface ITokenStream : IIntStream
	{
		int Range { get; }

		ITokenSource TokenSource { get; }

		IToken LT(int k);

		IToken Get(int i);

		string ToString(int start, int stop);

		string ToString(IToken start, IToken stop);
	}
	public interface ITokenStreamInformation
	{
		IToken LastToken { get; }

		IToken LastRealToken { get; }

		int MaxLookBehind { get; }
	}
	[Serializable]
	public class LegacyCommonTokenStream : ITokenStream, IIntStream
	{
		[NonSerialized]
		private ITokenSource _tokenSource;

		protected List<IToken> tokens;

		protected IDictionary<int, int> channelOverrideMap;

		protected List<int> discardSet;

		protected int channel;

		protected bool discardOffChannelTokens;

		protected int lastMarker;

		protected int p = -1;

		public virtual int Index => p;

		public virtual int Range { get; protected set; }

		public virtual int Count => tokens.Count;

		public virtual ITokenSource TokenSource => _tokenSource;

		public virtual string SourceName => TokenSource.SourceName;

		public LegacyCommonTokenStream()
		{
			tokens = new List<IToken>(500);
		}

		public LegacyCommonTokenStream(ITokenSource tokenSource)
			: this()
		{
			_tokenSource = tokenSource;
		}

		public LegacyCommonTokenStream(ITokenSource tokenSource, int channel)
			: this(tokenSource)
		{
			this.channel = channel;
		}

		public virtual void SetTokenSource(ITokenSource tokenSource)
		{
			_tokenSource = tokenSource;
			tokens.Clear();
			p = -1;
			channel = 0;
		}

		public virtual void FillBuffer()
		{
			if (p != -1)
			{
				return;
			}
			int num = 0;
			IToken token = _tokenSource.NextToken();
			while (token != null && token.Type != -1)
			{
				bool flag = false;
				if (channelOverrideMap != null && channelOverrideMap.TryGetValue(token.Type, out var value))
				{
					token.Channel = value;
				}
				if (discardSet != null && discardSet.Contains(token.Type))
				{
					flag = true;
				}
				else if (discardOffChannelTokens && token.Channel != channel)
				{
					flag = true;
				}
				if (!flag)
				{
					token.TokenIndex = num;
					tokens.Add(token);
					num++;
				}
				token = _tokenSource.NextToken();
			}
			p = 0;
			p = SkipOffTokenChannels(p);
		}

		public virtual void Consume()
		{
			if (p < tokens.Count)
			{
				p++;
				p = SkipOffTokenChannels(p);
			}
		}

		protected virtual int SkipOffTokenChannels(int i)
		{
			int count = tokens.Count;
			while (i < count && tokens[i].Channel != channel)
			{
				i++;
			}
			return i;
		}

		protected virtual int SkipOffTokenChannelsReverse(int i)
		{
			while (i >= 0 && tokens[i].Channel != channel)
			{
				i--;
			}
			return i;
		}

		public virtual void SetTokenTypeChannel(int ttype, int channel)
		{
			if (channelOverrideMap == null)
			{
				channelOverrideMap = new Dictionary<int, int>();
			}
			channelOverrideMap[ttype] = channel;
		}

		public virtual void DiscardTokenType(int ttype)
		{
			if (discardSet == null)
			{
				discardSet = new List<int>();
			}
			discardSet.Add(ttype);
		}

		public virtual void SetDiscardOffChannelTokens(bool discardOffChannelTokens)
		{
			this.discardOffChannelTokens = discardOffChannelTokens;
		}

		public virtual IList<IToken> GetTokens()
		{
			if (p == -1)
			{
				FillBuffer();
			}
			return tokens;
		}

		public virtual IList<IToken> GetTokens(int start, int stop)
		{
			return GetTokens(start, stop, (BitSet)null);
		}

		public virtual IList<IToken> GetTokens(int start, int stop, BitSet types)
		{
			if (p == -1)
			{
				FillBuffer();
			}
			if (stop >= tokens.Count)
			{
				stop = tokens.Count - 1;
			}
			if (start < 0)
			{
				start = 0;
			}
			if (start > stop)
			{
				return null;
			}
			IList<IToken> list = new List<IToken>();
			for (int i = start; i <= stop; i++)
			{
				IToken token = tokens[i];
				if (types == null || types.Member(token.Type))
				{
					list.Add(token);
				}
			}
			if (list.Count == 0)
			{
				list = null;
			}
			return list;
		}

		public virtual IList<IToken> GetTokens(int start, int stop, IList<int> types)
		{
			return GetTokens(start, stop, new BitSet(types));
		}

		public virtual IList<IToken> GetTokens(int start, int stop, int ttype)
		{
			return GetTokens(start, stop, BitSet.Of(ttype));
		}

		public virtual IToken LT(int k)
		{
			if (p == -1)
			{
				FillBuffer();
			}
			if (k == 0)
			{
				return null;
			}
			if (k < 0)
			{
				return LB(-k);
			}
			if (p + k - 1 >= tokens.Count)
			{
				return tokens[tokens.Count - 1];
			}
			int num = p;
			for (int i = 1; i < k; i++)
			{
				num = SkipOffTokenChannels(num + 1);
			}
			if (num >= tokens.Count)
			{
				return tokens[tokens.Count - 1];
			}
			if (num > Range)
			{
				Range = num;
			}
			return tokens[num];
		}

		protected virtual IToken LB(int k)
		{
			if (p == -1)
			{
				FillBuffer();
			}
			if (k == 0)
			{
				return null;
			}
			if (p - k < 0)
			{
				return null;
			}
			int num = p;
			for (int i = 1; i <= k; i++)
			{
				num = SkipOffTokenChannelsReverse(num - 1);
			}
			if (num < 0)
			{
				return null;
			}
			return tokens[num];
		}

		public virtual IToken Get(int i)
		{
			return tokens[i];
		}

		public virtual int LA(int i)
		{
			return LT(i).Type;
		}

		public virtual int Mark()
		{
			if (p == -1)
			{
				FillBuffer();
			}
			lastMarker = Index;
			return lastMarker;
		}

		public virtual void Release(int marker)
		{
		}

		public virtual void Rewind(int marker)
		{
			Seek(marker);
		}

		public virtual void Rewind()
		{
			Seek(lastMarker);
		}

		public virtual void Reset()
		{
			p = 0;
			lastMarker = 0;
		}

		public virtual void Seek(int index)
		{
			p = index;
		}

		public override string ToString()
		{
			if (p == -1)
			{
				throw new InvalidOperationException("Buffer is not yet filled.");
			}
			return ToString(0, tokens.Count - 1);
		}

		public virtual string ToString(int start, int stop)
		{
			if (start < 0 || stop < 0)
			{
				return null;
			}
			if (p == -1)
			{
				throw new InvalidOperationException("Buffer is not yet filled.");
			}
			if (stop >= tokens.Count)
			{
				stop = tokens.Count - 1;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = start; i <= stop; i++)
			{
				IToken token = tokens[i];
				stringBuilder.Append(token.Text);
			}
			return stringBuilder.ToString();
		}

		public virtual string ToString(IToken start, IToken stop)
		{
			if (start != null && stop != null)
			{
				return ToString(start.TokenIndex, stop.TokenIndex);
			}
			return null;
		}
	}
	public abstract class Lexer : BaseRecognizer, ITokenSource
	{
		protected ICharStream input;

		public string Text
		{
			get
			{
				if (state.text != null)
				{
					return state.text;
				}
				return input.Substring(state.tokenStartCharIndex, CharIndex - state.tokenStartCharIndex);
			}
			set
			{
				state.text = value;
			}
		}

		public int Line
		{
			get
			{
				return input.Line;
			}
			set
			{
				input.Line = value;
			}
		}

		public int CharPositionInLine
		{
			get
			{
				return input.CharPositionInLine;
			}
			set
			{
				input.CharPositionInLine = value;
			}
		}

		public virtual ICharStream CharStream
		{
			get
			{
				return input;
			}
			set
			{
				input = null;
				Reset();
				input = value;
			}
		}

		public override string SourceName => input.SourceName;

		public virtual int CharIndex => input.Index;

		public Lexer()
		{
		}

		public Lexer(ICharStream input)
		{
			this.input = input;
		}

		public Lexer(ICharStream input, RecognizerSharedState state)
			: base(state)
		{
			this.input = input;
		}

		public override void Reset()
		{
			base.Reset();
			if (input != null)
			{
				input.Seek(0);
			}
			if (state != null)
			{
				state.token = null;
				state.type = 0;
				state.channel = 0;
				state.tokenStartCharIndex = -1;
				state.tokenStartCharPositionInLine = -1;
				state.tokenStartLine = -1;
				state.text = null;
			}
		}

		public virtual IToken NextToken()
		{
			while (true)
			{
				state.token = null;
				state.channel = 0;
				state.tokenStartCharIndex = input.Index;
				state.tokenStartCharPositionInLine = input.CharPositionInLine;
				state.tokenStartLine = input.Line;
				state.text = null;
				if (input.LA(1) == -1)
				{
					break;
				}
				try
				{
					ParseNextToken();
					if (state.token == null)
					{
						Emit();
						goto IL_00b0;
					}
					if (state.token != Tokens.Skip)
					{
						goto IL_00b0;
					}
					goto end_IL_007d;
					IL_00b0:
					return state.token;
					end_IL_007d:;
				}
				catch (MismatchedRangeException e)
				{
					ReportError(e);
				}
				catch (MismatchedTokenException e2)
				{
					ReportError(e2);
				}
				catch (RecognitionException ex)
				{
					ReportError(ex);
					Recover(ex);
				}
			}
			return GetEndOfFileToken();
		}

		public virtual IToken GetEndOfFileToken()
		{
			return new CommonToken(input, -1, 0, input.Index, input.Index)
			{
				Line = Line,
				CharPositionInLine = CharPositionInLine
			};
		}

		public virtual void Skip()
		{
			state.token = Tokens.Skip;
		}

		public abstract void mTokens();

		public virtual void Emit(IToken token)
		{
			state.token = token;
		}

		public virtual IToken Emit()
		{
			IToken token = new CommonToken(input, state.type, state.channel, state.tokenStartCharIndex, CharIndex - 1);
			token.Line = state.tokenStartLine;
			token.Text = state.text;
			token.CharPositionInLine = state.tokenStartCharPositionInLine;
			Emit(token);
			return token;
		}

		public virtual void Match(string s)
		{
			int num = 0;
			while (num < s.Length)
			{
				if (input.LA(1) != s[num])
				{
					if (state.backtracking > 0)
					{
						state.failed = true;
						break;
					}
					MismatchedTokenException ex = new MismatchedTokenException(s[num], input, TokenNames);
					Recover(ex);
					throw ex;
				}
				num++;
				input.Consume();
				state.failed = false;
			}
		}

		public virtual void MatchAny()
		{
			input.Consume();
		}

		public virtual void Match(int c)
		{
			if (input.LA(1) != c)
			{
				if (state.backtracking <= 0)
				{
					MismatchedTokenException ex = new MismatchedTokenException(c, input, TokenNames);
					Recover(ex);
					throw ex;
				}
				state.failed = true;
			}
			else
			{
				input.Consume();
				state.failed = false;
			}
		}

		public virtual void MatchRange(int a, int b)
		{
			if (input.LA(1) < a || input.LA(1) > b)
			{
				if (state.backtracking <= 0)
				{
					MismatchedRangeException ex = new MismatchedRangeException(a, b, input);
					Recover(ex);
					throw ex;
				}
				state.failed = true;
			}
			else
			{
				input.Consume();
				state.failed = false;
			}
		}

		public override void ReportError(RecognitionException e)
		{
			DisplayRecognitionError(TokenNames, e);
		}

		public override string GetErrorMessage(RecognitionException e, string[] tokenNames)
		{
			string text = null;
			if (e is MismatchedTokenException)
			{
				MismatchedTokenException ex = (MismatchedTokenException)e;
				return "mismatched character " + GetCharErrorDisplay(e.Character) + " expecting " + GetCharErrorDisplay(ex.Expecting);
			}
			if (e is NoViableAltException)
			{
				_ = (NoViableAltException)e;
				return "no viable alternative at character " + GetCharErrorDisplay(e.Character);
			}
			if (e is EarlyExitException)
			{
				_ = (EarlyExitException)e;
				return "required (...)+ loop did not match anything at character " + GetCharErrorDisplay(e.Character);
			}
			if (e is MismatchedNotSetException)
			{
				MismatchedNotSetException ex2 = (MismatchedNotSetException)e;
				return "mismatched character " + GetCharErrorDisplay(e.Character) + " expecting set " + ex2.Expecting;
			}
			if (e is MismatchedSetException)
			{
				MismatchedSetException ex3 = (MismatchedSetException)e;
				return "mismatched character " + GetCharErrorDisplay(e.Character) + " expecting set " + ex3.Expecting;
			}
			if (e is MismatchedRangeException)
			{
				MismatchedRangeException ex4 = (MismatchedRangeException)e;
				return "mismatched character " + GetCharErrorDisplay(e.Character) + " expecting set " + GetCharErrorDisplay(ex4.A) + ".." + GetCharErrorDisplay(ex4.B);
			}
			return base.GetErrorMessage(e, tokenNames);
		}

		public virtual string GetCharErrorDisplay(int c)
		{
			string text = ((char)c).ToString();
			switch (c)
			{
			case -1:
				text = "<EOF>";
				break;
			case 10:
				text = "\\n";
				break;
			case 9:
				text = "\\t";
				break;
			case 13:
				text = "\\r";
				break;
			}
			return "'" + text + "'";
		}

		public virtual void Recover(RecognitionException re)
		{
			input.Consume();
		}

		[Conditional("ANTLR_TRACE")]
		public virtual void TraceIn(string ruleName, int ruleIndex)
		{
			string inputSymbol = ((char)input.LT(1)).ToString() + " line=" + Line + ":" + CharPositionInLine;
			base.TraceIn(ruleName, ruleIndex, inputSymbol);
		}

		[Conditional("ANTLR_TRACE")]
		public virtual void TraceOut(string ruleName, int ruleIndex)
		{
			string inputSymbol = ((char)input.LT(1)).ToString() + " line=" + Line + ":" + CharPositionInLine;
			base.TraceOut(ruleName, ruleIndex, inputSymbol);
		}

		protected virtual void ParseNextToken()
		{
			mTokens();
		}
	}
	[Serializable]
	public class MismatchedNotSetException : MismatchedSetException
	{
		public MismatchedNotSetException()
		{
		}

		public MismatchedNotSetException(string message)
			: base(message)
		{
		}

		public MismatchedNotSetException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MismatchedNotSetException(BitSet expecting, IIntStream input)
			: base(expecting, input)
		{
		}

		public MismatchedNotSetException(string message, BitSet expecting, IIntStream input)
			: base(message, expecting, input)
		{
		}

		public MismatchedNotSetException(string message, BitSet expecting, IIntStream input, Exception innerException)
			: base(message, expecting, input, innerException)
		{
		}

		protected MismatchedNotSetException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public override string ToString()
		{
			return string.Concat("MismatchedNotSetException(", UnexpectedType, "!=", base.Expecting, ")");
		}
	}
	[Serializable]
	public class MismatchedRangeException : RecognitionException
	{
		private readonly int _a;

		private readonly int _b;

		public int A => _a;

		public int B => _b;

		public MismatchedRangeException()
		{
		}

		public MismatchedRangeException(string message)
			: base(message)
		{
		}

		public MismatchedRangeException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MismatchedRangeException(int a, int b, IIntStream input)
			: base(input)
		{
			_a = a;
			_b = b;
		}

		public MismatchedRangeException(string message, int a, int b, IIntStream input)
			: base(message, input)
		{
			_a = a;
			_b = b;
		}

		public MismatchedRangeException(string message, int a, int b, IIntStream input, Exception innerException)
			: base(message, input, innerException)
		{
			_a = a;
			_b = b;
		}

		protected MismatchedRangeException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_a = info.GetInt32("A");
			_b = info.GetInt32("B");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("A", _a);
			info.AddValue("B", _b);
		}

		public override string ToString()
		{
			return "MismatchedRangeException(" + UnexpectedType + " not in [" + A + "," + B + "])";
		}
	}
	[Serializable]
	public class MismatchedSetException : RecognitionException
	{
		private readonly BitSet _expecting;

		public BitSet Expecting => _expecting;

		public MismatchedSetException()
		{
		}

		public MismatchedSetException(string message)
			: base(message)
		{
		}

		public MismatchedSetException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MismatchedSetException(BitSet expecting, IIntStream input)
			: base(input)
		{
			_expecting = expecting;
		}

		public MismatchedSetException(string message, BitSet expecting, IIntStream input)
			: base(message, input)
		{
			_expecting = expecting;
		}

		public MismatchedSetException(string message, BitSet expecting, IIntStream input, Exception innerException)
			: base(message, input, innerException)
		{
			_expecting = expecting;
		}

		protected MismatchedSetException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_expecting = (BitSet)info.GetValue("Expecting", typeof(BitSet));
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("Expecting", _expecting);
		}

		public override string ToString()
		{
			return string.Concat("MismatchedSetException(", UnexpectedType, "!=", Expecting, ")");
		}
	}
	[Serializable]
	public class MismatchedTokenException : RecognitionException
	{
		private readonly int _expecting;

		private readonly ReadOnlyCollection<string> _tokenNames;

		public int Expecting => _expecting;

		public ReadOnlyCollection<string> TokenNames => _tokenNames;

		public MismatchedTokenException()
		{
		}

		public MismatchedTokenException(string message)
			: base(message)
		{
		}

		public MismatchedTokenException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MismatchedTokenException(int expecting, IIntStream input)
			: this(expecting, input, null)
		{
		}

		public MismatchedTokenException(int expecting, IIntStream input, IList<string> tokenNames)
			: base(input)
		{
			_expecting = expecting;
			if (tokenNames != null)
			{
				_tokenNames = new ReadOnlyCollection<string>(new List<string>(tokenNames));
			}
		}

		public MismatchedTokenException(string message, int expecting, IIntStream input, IList<string> tokenNames)
			: base(message, input)
		{
			_expecting = expecting;
			if (tokenNames != null)
			{
				_tokenNames = new ReadOnlyCollection<string>(new List<string>(tokenNames));
			}
		}

		public MismatchedTokenException(string message, int expecting, IIntStream input, IList<string> tokenNames, Exception innerException)
			: base(message, input, innerException)
		{
			_expecting = expecting;
			if (tokenNames != null)
			{
				_tokenNames = new ReadOnlyCollection<string>(new List<string>(tokenNames));
			}
		}

		protected MismatchedTokenException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_expecting = info.GetInt32("Expecting");
			_tokenNames = new ReadOnlyCollection<string>((string[])info.GetValue("TokenNames", typeof(string[])));
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("Expecting", _expecting);
			info.AddValue("TokenNames", (_tokenNames != null) ? new List<string>(_tokenNames).ToArray() : null);
		}

		public override string ToString()
		{
			int unexpectedType = UnexpectedType;
			string text = ((TokenNames != null && unexpectedType >= 0 && unexpectedType < TokenNames.Count) ? TokenNames[unexpectedType] : unexpectedType.ToString());
			string text2 = ((TokenNames != null && Expecting >= 0 && Expecting < TokenNames.Count) ? TokenNames[Expecting] : Expecting.ToString());
			return "MismatchedTokenException(" + text + "!=" + text2 + ")";
		}
	}
	[Serializable]
	public class MismatchedTreeNodeException : RecognitionException
	{
		private readonly int _expecting;

		public int Expecting => _expecting;

		public MismatchedTreeNodeException()
		{
		}

		public MismatchedTreeNodeException(string message)
			: base(message)
		{
		}

		public MismatchedTreeNodeException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MismatchedTreeNodeException(int expecting, ITreeNodeStream input)
			: base(input)
		{
			_expecting = expecting;
		}

		public MismatchedTreeNodeException(string message, int expecting, ITreeNodeStream input)
			: base(message, input)
		{
			_expecting = expecting;
		}

		public MismatchedTreeNodeException(string message, int expecting, ITreeNodeStream input, Exception innerException)
			: base(message, input, innerException)
		{
			_expecting = expecting;
		}

		protected MismatchedTreeNodeException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_expecting = info.GetInt32("Expecting");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("Expecting", _expecting);
		}

		public override string ToString()
		{
			return "MismatchedTreeNodeException(" + UnexpectedType + "!=" + Expecting + ")";
		}
	}
	[Serializable]
	public class MissingTokenException : MismatchedTokenException
	{
		private readonly object _inserted;

		public virtual int MissingType => base.Expecting;

		public MissingTokenException()
		{
		}

		public MissingTokenException(string message)
			: base(message)
		{
		}

		public MissingTokenException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public MissingTokenException(int expecting, IIntStream input, object inserted)
			: this(expecting, input, inserted, null)
		{
		}

		public MissingTokenException(int expecting, IIntStream input, object inserted, IList<string> tokenNames)
			: base(expecting, input, tokenNames)
		{
			_inserted = inserted;
		}

		public MissingTokenException(string message, int expecting, IIntStream input, object inserted, IList<string> tokenNames)
			: base(message, expecting, input, tokenNames)
		{
			_inserted = inserted;
		}

		public MissingTokenException(string message, int expecting, IIntStream input, object inserted, IList<string> tokenNames, Exception innerException)
			: base(message, expecting, input, tokenNames, innerException)
		{
			_inserted = inserted;
		}

		protected MissingTokenException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public override string ToString()
		{
			if (_inserted != null && base.Token != null)
			{
				return string.Concat("MissingTokenException(inserted ", _inserted, " at ", base.Token.Text, ")");
			}
			if (base.Token != null)
			{
				return "MissingTokenException(at " + base.Token.Text + ")";
			}
			return "MissingTokenException";
		}
	}
	[Serializable]
	public class NoViableAltException : RecognitionException
	{
		private readonly string _grammarDecisionDescription;

		private readonly int _decisionNumber;

		private readonly int _stateNumber;

		public int DecisionNumber => _decisionNumber;

		public string GrammarDecisionDescription => _grammarDecisionDescription;

		public int StateNumber => _stateNumber;

		public NoViableAltException()
		{
		}

		public NoViableAltException(string grammarDecisionDescription)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
		}

		public NoViableAltException(string message, string grammarDecisionDescription)
			: base(message)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
		}

		public NoViableAltException(string message, string grammarDecisionDescription, Exception innerException)
			: base(message, innerException)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
		}

		public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
			: this(grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
		{
		}

		public NoViableAltException(string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
			: base(input, k)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
			_decisionNumber = decisionNumber;
			_stateNumber = stateNumber;
		}

		public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input)
			: this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1)
		{
		}

		public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k)
			: base(message, input, k)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
			_decisionNumber = decisionNumber;
			_stateNumber = stateNumber;
		}

		public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, Exception innerException)
			: this(message, grammarDecisionDescription, decisionNumber, stateNumber, input, 1, innerException)
		{
		}

		public NoViableAltException(string message, string grammarDecisionDescription, int decisionNumber, int stateNumber, IIntStream input, int k, Exception innerException)
			: base(message, input, k, innerException)
		{
			_grammarDecisionDescription = grammarDecisionDescription;
			_decisionNumber = decisionNumber;
			_stateNumber = stateNumber;
		}

		protected NoViableAltException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_grammarDecisionDescription = info.GetString("GrammarDecisionDescription");
			_decisionNumber = info.GetInt32("DecisionNumber");
			_stateNumber = info.GetInt32("StateNumber");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("GrammarDecisionDescription", _grammarDecisionDescription);
			info.AddValue("DecisionNumber", _decisionNumber);
			info.AddValue("StateNumber", _stateNumber);
		}

		public override string ToString()
		{
			if (base.Input is ICharStream)
			{
				return "NoViableAltException('" + (char)UnexpectedType + "'@[" + GrammarDecisionDescription + "])";
			}
			return "NoViableAltException(" + UnexpectedType + "@[" + GrammarDecisionDescription + "])";
		}
	}
	public class Parser : BaseRecognizer
	{
		public ITokenStream input;

		public virtual ITokenStream TokenStream
		{
			get
			{
				return input;
			}
			set
			{
				input = null;
				Reset();
				input = value;
			}
		}

		public override string SourceName => input.SourceName;

		public Parser(ITokenStream input)
		{
			TokenStream = input;
		}

		public Parser(ITokenStream input, RecognizerSharedState state)
			: base(state)
		{
			this.input = input;
		}

		public override void Reset()
		{
			base.Reset();
			if (input != null)
			{
				input.Seek(0);
			}
		}

		protected override object GetCurrentInputSymbol(IIntStream input)
		{
			return ((ITokenStream)input).LT(1);
		}

		protected override object GetMissingSymbol(IIntStream input, RecognitionException e, int expectedTokenType, BitSet follow)
		{
			string text = null;
			text = ((expectedTokenType != -1) ? ("<missing " + TokenNames[expectedTokenType] + ">") : "<missing EOF>");
			CommonToken commonToken = new CommonToken(expectedTokenType, text);
			IToken token = ((ITokenStream)input).LT(1);
			if (token.Type == -1)
			{
				token = ((ITokenStream)input).LT(-1);
			}
			commonToken.Line = token.Line;
			commonToken.CharPositionInLine = token.CharPositionInLine;
			commonToken.Channel = 0;
			commonToken.InputStream = token.InputStream;
			return commonToken;
		}

		[Conditional("ANTLR_TRACE")]
		public virtual void TraceIn(string ruleName, int ruleIndex)
		{
			base.TraceIn(ruleName, ruleIndex, input.LT(1));
		}

		[Conditional("ANTLR_TRACE")]
		public virtual void TraceOut(string ruleName, int ruleIndex)
		{
			base.TraceOut(ruleName, ruleIndex, input.LT(1));
		}
	}
	public class ParserRuleReturnScope<TToken> : IRuleReturnScope<TToken>, IRuleReturnScope
	{
		private TToken _start;

		private TToken _stop;

		public TToken Start
		{
			get
			{
				return _start;
			}
			set
			{
				_start = value;
			}
		}

		public TToken Stop
		{
			get
			{
				return _stop;
			}
			set
			{
				_stop = value;
			}
		}

		object IRuleReturnScope.Start => Start;

		object IRuleReturnScope.Stop => Stop;
	}
	[Serializable]
	public class RecognitionException : Exception
	{
		private IIntStream _input;

		private int _k;

		private int _index;

		private IToken _token;

		private object _node;

		private int _c;

		private int _line;

		private int _charPositionInLine;

		private bool _approximateLineInfo;

		public virtual int UnexpectedType
		{
			get
			{
				if (_input is ITokenStream)
				{
					return _token.Type;
				}
				if (_input is ITreeNodeStream treeNodeStream)
				{
					return treeNodeStream.TreeAdaptor.GetType(_node);
				}
				return _c;
			}
		}

		public bool ApproximateLineInfo
		{
			get
			{
				return _approximateLineInfo;
			}
			protected set
			{
				_approximateLineInfo = value;
			}
		}

		public IIntStream Input
		{
			get
			{
				return _input;
			}
			protected set
			{
				_input = value;
			}
		}

		public int Lookahead => _k;

		public IToken Token
		{
			get
			{
				return _token;
			}
			set
			{
				_token = value;
			}
		}

		public object Node
		{
			get
			{
				return _node;
			}
			protected set
			{
				_node = value;
			}
		}

		public int Character
		{
			get
			{
				return _c;
			}
			protected set
			{
				_c = value;
			}
		}

		public int Index
		{
			get
			{
				return _index;
			}
			protected set
			{
				_index = value;
			}
		}

		public int Line
		{
			get
			{
				return _line;
			}
			set
			{
				_line = value;
			}
		}

		public int CharPositionInLine
		{
			get
			{
				return _charPositionInLine;
			}
			set
			{
				_charPositionInLine = value;
			}
		}

		public RecognitionException()
			: this("A recognition error occurred.", null, null)
		{
		}

		public RecognitionException(IIntStream input)
			: this("A recognition error occurred.", input, 1, null)
		{
		}

		public RecognitionException(IIntStream input, int k)
			: this("A recognition error occurred.", input, k, null)
		{
		}

		public RecognitionException(string message)
			: this(message, null, null)
		{
		}

		public RecognitionException(string message, IIntStream input)
			: this(message, input, 1, null)
		{
		}

		public RecognitionException(string message, IIntStream input, int k)
			: this(message, input, k, null)
		{
		}

		public RecognitionException(string message, Exception innerException)
			: this(message, null, innerException)
		{
		}

		public RecognitionException(string message, IIntStream input, Exception innerException)
			: this(message, input, 1, innerException)
		{
		}

		public RecognitionException(string message, IIntStream input, int k, Exception innerException)
			: base(message, innerException)
		{
			_input = input;
			_k = k;
			if (input == null)
			{
				return;
			}
			_index = input.Index + k - 1;
			if (input is ITokenStream)
			{
				_token = ((ITokenStream)input).LT(k);
				_line = _token.Line;
				_charPositionInLine = _token.CharPositionInLine;
			}
			if (input is ITreeNodeStream input2)
			{
				ExtractInformationFromTreeNodeStream(input2, k);
				return;
			}
			if (input is ICharStream)
			{
				int marker = input.Mark();
				try
				{
					for (int i = 0; i < k - 1; i++)
					{
						input.Consume();
					}
					_c = input.LA(1);
					_line = ((ICharStream)input).Line;
					_charPositionInLine = ((ICharStream)input).CharPositionInLine;
					return;
				}
				finally
				{
					input.Rewind(marker);
				}
			}
			_c = input.LA(k);
		}

		protected RecognitionException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			_index = info.GetInt32("Index");
			_c = info.GetInt32("C");
			_line = info.GetInt32("Line");
			_charPositionInLine = info.GetInt32("CharPositionInLine");
			_approximateLineInfo = info.GetBoolean("ApproximateLineInfo");
		}

		[SecurityCritical]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			if (info == null)
			{
				throw new ArgumentNullException("info");
			}
			base.GetObjectData(info, context);
			info.AddValue("Index", _index);
			info.AddValue("C", _c);
			info.AddValue("Line", _line);
			info.AddValue("CharPositionInLine", _charPositionInLine);
			info.AddValue("ApproximateLineInfo", _approximateLineInfo);
		}

		protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input)
		{
			_node = input.LT(1);
			object obj = null;
			if (input is IPositionTrackingStream positionTrackingStream)
			{
				obj = positionTrackingStream.GetKnownPositionElement(allowApproximateLocation: false);
				if (obj == null)
				{
					obj = positionTrackingStream.GetKnownPositionElement(allowApproximateLocation: true);
					_approximateLineInfo = obj != null;
				}
			}
			if (input is ITokenStreamInformation tokenStreamInformation)
			{
				IToken lastToken = tokenStreamInformation.LastToken;
				IToken lastRealToken = tokenStreamInformation.LastRealToken;
				if (lastRealToken != null)
				{
					_token = lastRealToken;
					_line = lastRealToken.Line;
					_charPositionInLine = lastRealToken.CharPositionInLine;
					_approximateLineInfo = lastRealToken.Equals(lastToken);
				}
				return;
			}
			ITreeAdaptor treeAdaptor = input.TreeAdaptor;
			IToken token = treeAdaptor.GetToken(obj ?? _node);
			if (token != null)
			{
				_token = token;
				if (token.Line <= 0)
				{
					int num = -1;
					object obj2 = input.LT(num);
					while (obj2 != null)
					{
						IToken token2 = treeAdaptor.GetToken(obj2);
						if (token2 != null && token2.Line > 0)
						{
							_line = token2.Line;
							_charPositionInLine = token2.CharPositionInLine;
							_approximateLineInfo = true;
							break;
						}
						num--;
						try
						{
							obj2 = input.LT(num);
						}
						catch (NotSupportedException)
						{
							obj2 = null;
						}
					}
				}
				else
				{
					_line = token.Line;
					_charPositionInLine = token.CharPositionInLine;
				}
			}
			else if (_node is ITree)
			{
				_line = ((ITree)_node).Line;
				_charPositionInLine = ((ITree)_node).CharPositionInLine;
				if (_node is CommonTree)
				{
					_token = ((CommonTree)_node).Token;
				}
			}
			else
			{
				int type = treeAdaptor.GetType(_node);
				string text = treeAdaptor.GetText(_node);
				_token = new CommonToken(type, text);
			}
		}

		protected virtual void ExtractInformationFromTreeNodeStream(ITreeNodeStream input, int k)
		{
			int marker = input.Mark();
			try
			{
				for (int i = 0; i < k - 1; i++)
				{
					input.Consume();
				}
				ExtractInformationFromTreeNodeStream(input);
			}
			finally
			{
				input.Rewind(marker);
			}
		}
	}
	public class RecognizerSharedState
	{
		public BitSet[] following;

		[CLSCompliant(false)]
		public int _fsp;

		public bool errorRecovery;

		public int lastErrorIndex;

		public bool failed;

		public int syntaxErrors;

		public int backtracking;

		public IDictionary<int, int>[] ruleMemo;

		public IToken token;

		public int tokenStartCharIndex;

		public int tokenStartLine;

		public int tokenStartCharPositionInLine;

		public int channel;

		public int type;

		public string text;

		public RecognizerSharedState()
		{
			following = new BitSet[100];
			_fsp = -1;
			lastErrorIndex = -1;
			tokenStartCharIndex = -1;
		}

		public RecognizerSharedState(RecognizerSharedState state)
		{
			if (state == null)
			{
				throw new ArgumentNullException("state");
			}
			following = (BitSet[])state.following.Clone();
			_fsp = state._fsp;
			errorRecovery = state.errorRecovery;
			lastErrorIndex = state.lastErrorIndex;
			failed = state.failed;
			syntaxErrors = state.syntaxErrors;
			backtracking = state.backtracking;
			if (state.ruleMemo != null)
			{
				ruleMemo = (IDictionary<int, int>[])state.ruleMemo.Clone();
			}
			token = state.token;
			tokenStartCharIndex = state.tokenStartCharIndex;
			tokenStartCharPositionInLine = state.tokenStartCharPositionInLine;
			channel = state.channel;
			type = state.type;
			text = state.text;
		}
	}
	public class TemplateParserRuleReturnScope<TTemplate, TToken> : ParserRuleReturnScope<TToken>, ITemplateRuleReturnScope<TTemplate>, ITemplateRuleReturnScope
	{
		private TTemplate _template;

		public TTemplate Template
		{
			get
			{
				return _template;
			}
			set
			{
				_template = value;
			}
		}

		object ITemplateRuleReturnScope.Template => Template;
	}
	public static class TokenChannels
	{
		public const int Default = 0;

		public const int Hidden = 99;
	}
	[Serializable]
	[DebuggerDisplay("TODO: TokenRewriteStream debugger display")]
	public class TokenRewriteStream : CommonTokenStream
	{
		protected class RewriteOperation
		{
			public int instructionIndex;

			public int index;

			public object text;

			protected TokenRewriteStream stream;

			protected RewriteOperation(TokenRewriteStream stream, int index)
			{
				this.stream = stream;
				this.index = index;
			}

			protected RewriteOperation(TokenRewriteStream stream, int index, object text)
			{
				this.index = index;
				this.text = text;
				this.stream = stream;
			}

			public virtual int Execute(StringBuilder buf)
			{
				return index;
			}

			public override string ToString()
			{
				string name = GetType().Name;
				int num = name.IndexOf('$');
				name = name.Substring(num + 1);
				return $"<{name}@{stream._tokens[index]}:\"{text}\">";
			}
		}

		private class InsertBeforeOp : RewriteOperation
		{
			public InsertBeforeOp(TokenRewriteStream stream, int index, object text)
				: base(stream, index, text)
			{
			}

			public override int Execute(StringBuilder buf)
			{
				buf.Append(text);
				if (stream._tokens[index].Type != -1)
				{
					buf.Append(stream._tokens[index].Text);
				}
				return index + 1;
			}
		}

		private class ReplaceOp : RewriteOperation
		{
			public int lastIndex;

			public ReplaceOp(TokenRewriteStream stream, int from, int to, object text)
				: base(stream, from, text)
			{
				lastIndex = to;
			}

			public override int Execute(StringBuilder buf)
			{
				if (text != null)
				{
					buf.Append(text);
				}
				return lastIndex + 1;
			}

			public override string ToString()
			{
				if (text == null)
				{
					return $"<DeleteOp@{stream._tokens[index]}..{stream._tokens[lastIndex]}>";
				}
				return $"<ReplaceOp@{stream._tokens[index]}..{stream._tokens[lastIndex]}:\"{text}\">";
			}
		}

		public const string DEFAULT_PROGRAM_NAME = "default";

		public const int PROGRAM_INIT_SIZE = 100;

		public const int MIN_TOKEN_INDEX = 0;

		protected IDictionary<string, IList<RewriteOperation>> programs;

		protected IDictionary<string, int> lastRewriteTokenIndexes;

		public TokenRewriteStream()
		{
			Init();
		}

		protected void Init()
		{
			programs = new Dictionary<string, IList<RewriteOperation>>();
			programs["default"] = new List<RewriteOperation>(100);
			lastRewriteTokenIndexes = new Dictionary<string, int>();
		}

		public TokenRewriteStream(ITokenSource tokenSource)
			: base(tokenSource)
		{
			Init();
		}

		public TokenRewriteStream(ITokenSource tokenSource, int channel)
			: base(tokenSource, channel)
		{
			Init();
		}

		public virtual void Rollback(int instructionIndex)
		{
			Rollback("default", instructionIndex);
		}

		public virtual void Rollback(string programName, int instructionIndex)
		{
			if (programs.TryGetValue(programName, out var value) && value != null)
			{
				List<RewriteOperation> list = new List<RewriteOperation>();
				for (int i = 0; i <= instructionIndex; i++)
				{
					list.Add(value[i]);
				}
				programs[programName] = list;
			}
		}

		public virtual void DeleteProgram()
		{
			DeleteProgram("default");
		}

		public virtual void DeleteProgram(string programName)
		{
			Rollback(programName, 0);
		}

		public virtual void InsertAfter(IToken t, object text)
		{
			InsertAfter("default", t, text);
		}

		public virtual void InsertAfter(int index, object text)
		{
			InsertAfter("default", index, text);
		}

		public virtual void InsertAfter(string programName, IToken t, object text)
		{
			InsertAfter(programName, t.TokenIndex, text);
		}

		public virtual void InsertAfter(string programName, int index, object text)
		{
			InsertBefore(programName, index + 1, text);
		}

		public virtual void InsertBefore(IToken t, object text)
		{
			InsertBefore("default", t, text);
		}

		public virtual void InsertBefore(int index, object text)
		{
			InsertBefore("default", index, text);
		}

		public virtual void InsertBefore(string programName, IToken t, object text)
		{
			InsertBefore(programName, t.TokenIndex, text);
		}

		public virtual void InsertBefore(string programName, int index, object text)
		{
			RewriteOperation rewriteOperation = new InsertBeforeOp(this, index, text);
			IList<RewriteOperation> program = GetProgram(programName);
			rewriteOperation.instructionIndex = program.Count;
			program.Add(rewriteOperation);
		}

		public virtual void Replace(int index, object text)
		{
			Replace("default", index, index, text);
		}

		public virtual void Replace(int from, int to, object text)
		{
			Replace("default", from, to, text);
		}

		public virtual void Replace(IToken indexT, object text)
		{
			Replace("default", indexT, indexT, text);
		}

		public virtual void Replace(IToken from, IToken to, object text)
		{
			Replace("default", from, to, text);
		}

		public virtual void Replace(string programName, int from, int to, object text)
		{
			if (from > to || from < 0 || to < 0 || to >= _tokens.Count)
			{
				throw new ArgumentException("replace: range invalid: " + from + ".." + to + "(size=" + _tokens.Count + ")");
			}
			RewriteOperation rewriteOperation = new ReplaceOp(this, from, to, text);
			IList<RewriteOperation> program = GetProgram(programName);
			rewriteOperation.instructionIndex = program.Count;
			program.Add(rewriteOperation);
		}

		public virtual void Replace(string programName, IToken from, IToken to, object text)
		{
			Replace(programName, from.TokenIndex, to.TokenIndex, text);
		}

		public virtual void Delete(int index)
		{
			Delete("default", index, index);
		}

		public virtual void Delete(int from, int to)
		{
			Delete("default", from, to);
		}

		public virtual void Delete(IToken indexT)
		{
			Delete("default", indexT, indexT);
		}

		public virtual void Delete(IToken from, IToken to)
		{
			Delete("default", from, to);
		}

		public virtual void Delete(string programName, int from, int to)
		{
			Replace(programName, from, to, null);
		}

		public virtual void Delete(string programName, IToken from, IToken to)
		{
			Replace(programName, from, to, null);
		}

		public virtual int GetLastRewriteTokenIndex()
		{
			return GetLastRewriteTokenIndex("default");
		}

		protected virtual int GetLastRewriteTokenIndex(string programName)
		{
			if (lastRewriteTokenIndexes.TryGetValue(programName, out var value))
			{
				return value;
			}
			return -1;
		}

		protected virtual void SetLastRewriteTokenIndex(string programName, int i)
		{
			lastRewriteTokenIndexes[programName] = i;
		}

		protected virtual IList<RewriteOperation> GetProgram(string name)
		{
			if (!programs.TryGetValue(name, out var value) || value == null)
			{
				return InitializeProgram(name);
			}
			return value;
		}

		private IList<RewriteOperation> InitializeProgram(string name)
		{
			IList<RewriteOperation> list = new List<RewriteOperation>(100);
			programs[name] = list;
			return list;
		}

		public virtual string ToOriginalString()
		{
			Fill();
			return ToOriginalString(0, Count - 1);
		}

		public virtual string ToOriginalString(int start, int end)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = start; i >= 0 && i <= end && i < _tokens.Count; i++)
			{
				if (Get(i).Type != -1)
				{
					stringBuilder.Append(Get(i).Text);
				}
			}
			return stringBuilder.ToString();
		}

		public override string ToString()
		{
			Fill();
			return ToString(0, Count - 1);
		}

		public virtual string ToString(string programName)
		{
			Fill();
			return ToString(programName, 0, Count - 1);
		}

		public override string ToString(int start, int end)
		{
			return ToString("default", start, end);
		}

		public virtual string ToString(string programName, int start, int end)
		{
			if (!programs.TryGetValue(programName, out var value))
			{
				value = null;
			}
			if (end > _tokens.Count - 1)
			{
				end = _tokens.Count - 1;
			}
			if (start < 0)
			{
				start = 0;
			}
			if (value == null || value.Count == 0)
			{
				return ToOriginalString(start, end);
			}
			StringBuilder stringBuilder = new StringBuilder();
			IDictionary<int, RewriteOperation> dictionary = ReduceToSingleOperationPerIndex(value);
			int num = start;
			while (num <= end && num < _tokens.Count)
			{
				RewriteOperation value2;
				bool num2 = dictionary.TryGetValue(num, out value2);
				if (num2)
				{
					dictionary.Remove(num);
				}
				if (!num2 || value2 == null)
				{
					IToken token = _tokens[num];
					if (token.Type != -1)
					{
						stringBuilder.Append(token.Text);
					}
					num++;
				}
				else
				{
					num = value2.Execute(stringBuilder);
				}
			}
			if (end == _tokens.Count - 1)
			{
				foreach (RewriteOperation value3 in dictionary.Values)
				{
					if (value3.index >= _tokens.Count - 1)
					{
						stringBuilder.Append(value3.text);
					}
				}
			}
			return stringBuilder.ToString();
		}

		protected virtual IDictionary<int, RewriteOperation> ReduceToSingleOperationPerIndex(IList<RewriteOperation> rewrites)
		{
			for (int i = 0; i < rewrites.Count; i++)
			{
				RewriteOperation rewriteOperation = rewrites[i];
				if (rewriteOperation == null || !(rewriteOperation is ReplaceOp))
				{
					continue;
				}
				ReplaceOp replaceOp = (ReplaceOp)rewrites[i];
				IList<RewriteOperation> kindOfOps = GetKindOfOps(rewrites, typeof(InsertBeforeOp), i);
				for (int j = 0; j < kindOfOps.Count; j++)
				{
					InsertBeforeOp insertBeforeOp = (InsertBeforeOp)kindOfOps[j];
					if (insertBeforeOp.index == replaceOp.index)
					{
						rewrites[insertBeforeOp.instructionIndex] = null;
						replaceOp.text = insertBeforeOp.text.ToString() + ((replaceOp.text != null) ? replaceOp.text.ToString() : string.Empty);
					}
					else if (insertBeforeOp.index > replaceOp.index && insertBeforeOp.index <= replaceOp.lastIndex)
					{
						rewrites[insertBeforeOp.instructionIndex] = null;
					}
				}
				IList<RewriteOperation> kindOfOps2 = GetKindOfOps(rewrites, typeof(ReplaceOp), i);
				for (int k = 0; k < kindOfOps2.Count; k++)
				{
					ReplaceOp replaceOp2 = (ReplaceOp)kindOfOps2[k];
					if (replaceOp2.index >= replaceOp.index && replaceOp2.lastIndex <= replaceOp.lastIndex)
					{
						rewrites[replaceOp2.instructionIndex] = null;
						continue;
					}
					bool flag = replaceOp2.lastIndex < replaceOp.index || replaceOp2.index > replaceOp.lastIndex;
					bool flag2 = replaceOp2.index == replaceOp.index && replaceOp2.lastIndex == replaceOp.lastIndex;
					if (replaceOp2.text == null && replaceOp.text == null && !flag)
					{
						rewrites[replaceOp2.instructionIndex] = null;
						replaceOp.index = Math.Min(replaceOp2.index, replaceOp.index);
						replaceOp.lastIndex = Math.Max(replaceOp2.lastIndex, replaceOp.lastIndex);
						Console.WriteLine("new rop " + replaceOp);
					}
					else if (!flag && !flag2)
					{
						throw new ArgumentException(string.Concat("replace op boundaries of ", replaceOp, " overlap with previous ", replaceOp2));
					}
				}
			}
			for (int l = 0; l < rewrites.Count; l++)
			{
				RewriteOperation rewriteOperation2 = rewrites[l];
				if (rewriteOperation2 == null || !(rewriteOperation2 is InsertBeforeOp))
				{
					continue;
				}
				InsertBeforeOp insertBeforeOp2 = (InsertBeforeOp)rewrites[l];
				IList<RewriteOperation> kindOfOps3 = GetKindOfOps(rewrites, typeof(InsertBeforeOp), l);
				for (int m = 0; m < kindOfOps3.Count; m++)
				{
					InsertBeforeOp insertBeforeOp3 = (InsertBeforeOp)kindOfOps3[m];
					if (insertBeforeOp3.index == insertBeforeOp2.index)
					{
						insertBeforeOp2.text = CatOpText(insertBeforeOp2.text, insertBeforeOp3.text);
						rewrites[insertBeforeOp3.instructionIndex] = null;
					}
				}
				IList<RewriteOperation> kindOfOps4 = GetKindOfOps(rewrites, typeof(ReplaceOp), l);
				for (int n = 0; n < kindOfOps4.Count; n++)
				{
					ReplaceOp replaceOp3 = (ReplaceOp)kindOfOps4[n];
					if (insertBeforeOp2.index == replaceOp3.index)
					{
						replaceOp3.text = CatOpText(insertBeforeOp2.text, replaceOp3.text);
						rewrites[l] = null;
					}
					else if (insertBeforeOp2.index >= replaceOp3.index && insertBeforeOp2.index <= replaceOp3.lastIndex)
					{
						throw new ArgumentException(string.Concat("insert op ", insertBeforeOp2, " within boundaries of previous ", replaceOp3));
					}
				}
			}
			IDictionary<int, RewriteOperation> dictionary = new Dictionary<int, RewriteOperation>();
			for (int num = 0; num < rewrites.Count; num++)
			{
				RewriteOperation rewriteOperation3 = rewrites[num];
				if (rewriteOperation3 != null)
				{
					if (dictionary.TryGetValue(rewriteOperation3.index, out var value) && value != null)
					{
						throw new Exception("should only be one op per index");
					}
					dictionary[rewriteOperation3.index] = rewriteOperation3;
				}
			}
			return dictionary;
		}

		protected virtual string CatOpText(object a, object b)
		{
			return string.Concat(a, b);
		}

		protected virtual IList<RewriteOperation> GetKindOfOps(IList<RewriteOperation> rewrites, Type kind)
		{
			return GetKindOfOps(rewrites, kind, rewrites.Count);
		}

		protected virtual IList<RewriteOperation> GetKindOfOps(IList<RewriteOperation> rewrites, Type kind, int before)
		{
			IList<RewriteOperation> list = new List<RewriteOperation>();
			for (int i = 0; i < before && i < rewrites.Count; i++)
			{
				RewriteOperation rewriteOperation = rewrites[i];
				if (rewriteOperation != null && (object)rewriteOperation.GetType() == kind)
				{
					list.Add(rewriteOperation);
				}
			}
			return list;
		}

		public virtual string ToDebugString()
		{
			return ToDebugString(0, Count - 1);
		}

		public virtual string ToDebugString(int start, int end)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = start; i >= 0 && i <= end && i < _tokens.Count; i++)
			{
				stringBuilder.Append(Get(i));
			}
			return stringBuilder.ToString();
		}
	}
	public static class Tokens
	{
		public static readonly IToken Skip = new CommonToken(0);
	}
	public static class TokenTypes
	{
		public const int EndOfFile = -1;

		public const int Invalid = 0;

		public const int EndOfRule = 1;

		public const int Down = 2;

		public const int Up = 3;

		public const int Min = 4;
	}
	public class UnbufferedTokenStream : LookaheadStream<IToken>, ITokenStream, IIntStream, ITokenStreamInformation
	{
		[CLSCompliant(false)]
		protected ITokenSource tokenSource;

		protected int tokenIndex;

		protected int channel;

		private readonly ListStack<IToken> _realTokens = new ListStack<IToken> { null };

		public ITokenSource TokenSource => tokenSource;

		public string SourceName => TokenSource.SourceName;

		public IToken LastToken => LB(1);

		public IToken LastRealToken => _realTokens.Peek();

		public int MaxLookBehind => 1;

		public UnbufferedTokenStream(ITokenSource tokenSource)
		{
			this.tokenSource = tokenSource;
		}

		public override int Mark()
		{
			_realTokens.Push(_realTokens.Peek());
			return base.Mark();
		}

		public override void Release(int marker)
		{
			base.Release(marker);
			_realTokens.Pop();
		}

		public override void Clear()
		{
			_realTokens.Clear();
			_realTokens.Push(null);
		}

		public override void Consume()
		{
			base.Consume();
			if (base.PreviousElement != null && base.PreviousElement.Line > 0)
			{
				_realTokens[_realTokens.Count - 1] = base.PreviousElement;
			}
		}

		public override IToken NextElement()
		{
			IToken token = tokenSource.NextToken();
			token.TokenIndex = tokenIndex++;
			return token;
		}

		public override bool IsEndOfFile(IToken o)
		{
			return o.Type == -1;
		}

		public IToken Get(int i)
		{
			throw new NotSupportedException("Absolute token indexes are meaningless in an unbuffered stream");
		}

		public int LA(int i)
		{
			return LT(i).Type;
		}

		public string ToString(int start, int stop)
		{
			return "n/a";
		}

		public string ToString(IToken start, IToken stop)
		{
			return "n/a";
		}
	}
	[Serializable]
	public class UnwantedTokenException : MismatchedTokenException
	{
		public virtual IToken UnexpectedToken => base.Token;

		public UnwantedTokenException()
		{
		}

		public UnwantedTokenException(string message)
			: base(message)
		{
		}

		public UnwantedTokenException(string message, Exception innerException)
			: base(message, innerException)
		{
		}

		public UnwantedTokenException(int expecting, IIntStream input)
			: base(expecting, input)
		{
		}

		public UnwantedTokenException(int expecting, IIntStream input, IList<string> tokenNames)
			: base(expecting, input, tokenNames)
		{
		}

		public UnwantedTokenException(string message, int expecting, IIntStream input, IList<string> tokenNames)
			: base(message, expecting, input, tokenNames)
		{
		}

		public UnwantedTokenException(string message, int expecting, IIntStream input, IList<string> tokenNames, Exception innerException)
			: base(message, expecting, input, tokenNames, innerE

plugins/Libs/NCalc.dll

Decompiled 4 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using Antlr.Runtime;
using Antlr.Runtime.Tree;
using NCalc.Domain;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("3.5.0.4")]
[assembly: AssemblyInformationalVersion("3.5.0+cbc3cfcd0b")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("https://github.com/ncalc")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Sebastien Ros and contributors")]
[assembly: AssemblyDescription("NCalc is a mathematical expressions evaluator in .NET. NCalc can parse any expression and evaluate the result, including static or dynamic parameters and custom functions. This version targets .NET Standard 2.0 framework.")]
[assembly: AssemblyProduct("NCalc")]
[assembly: AssemblyTitle("NCalc")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/ncalc/ncalc.git")]
[assembly: AssemblyVersion("3.5.0.0")]
[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.4.244.2758")]
[ExcludeFromCodeCoverage]
internal static class ThisAssembly
{
	internal const string AssemblyConfiguration = "Release";

	internal const string AssemblyFileVersion = "3.5.0.4";

	internal const string AssemblyInformationalVersion = "3.5.0+cbc3cfcd0b";

	internal const string AssemblyName = "NCalc";

	internal const string AssemblyTitle = "NCalc";

	internal const string AssemblyVersion = "3.5.0.0";

	internal static readonly DateTime GitCommitDate = new DateTime(637904536960000000L, DateTimeKind.Utc);

	internal const string GitCommitId = "cbc3cfcd0b440d3378cde3ecdf0183064ab15f85";

	internal const bool IsPrerelease = false;

	internal const bool IsPublicRelease = true;

	internal const string RootNamespace = "NCalc";
}
namespace NCalc
{
	public delegate void EvaluateFunctionHandler(string name, FunctionArgs args);
	public delegate void EvaluateParameterHandler(string name, ParameterArgs args);
	public class EvaluationException : ApplicationException
	{
		public EvaluationException(string message)
			: base(message)
		{
		}

		public EvaluationException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
	[Flags]
	public enum EvaluateOptions
	{
		None = 1,
		IgnoreCase = 2,
		NoCache = 4,
		IterateParameters = 8,
		RoundAwayFromZero = 0x10
	}
	public class Expression
	{
		protected string OriginalExpression;

		protected CultureInfo CultureInfo;

		private static bool _cacheEnabled = true;

		private static Dictionary<string, WeakReference> _compiledExpressions = new Dictionary<string, WeakReference>();

		private static readonly ReaderWriterLock Rwl = new ReaderWriterLock();

		protected Dictionary<string, IEnumerator> ParameterEnumerators;

		protected Dictionary<string, object> ParametersBackup;

		private Dictionary<string, object> _parameters;

		public EvaluateOptions Options { get; set; }

		public static bool CacheEnabled
		{
			get
			{
				return _cacheEnabled;
			}
			set
			{
				_cacheEnabled = value;
				if (!CacheEnabled)
				{
					_compiledExpressions = new Dictionary<string, WeakReference>();
				}
			}
		}

		public string Error { get; private set; }

		public LogicalExpression ParsedExpression { get; private set; }

		public Dictionary<string, object> Parameters
		{
			get
			{
				return _parameters ?? (_parameters = new Dictionary<string, object>());
			}
			set
			{
				_parameters = value;
			}
		}

		public event EvaluateFunctionHandler EvaluateFunction;

		public event EvaluateParameterHandler EvaluateParameter;

		public Expression(string expression)
			: this(expression, EvaluateOptions.None, CultureInfo.CurrentCulture)
		{
		}

		public Expression(string expression, CultureInfo cultureInfo)
			: this(expression, EvaluateOptions.None, cultureInfo)
		{
		}

		public Expression(string expression, EvaluateOptions options)
			: this(expression, options, CultureInfo.CurrentCulture)
		{
		}

		public Expression(string expression, EvaluateOptions options, CultureInfo cultureInfo)
		{
			if (string.IsNullOrEmpty(expression))
			{
				throw new ArgumentException("Expression can't be empty", "expression");
			}
			OriginalExpression = expression;
			Options = options;
			CultureInfo = cultureInfo;
		}

		public Expression(LogicalExpression expression)
			: this(expression, EvaluateOptions.None, CultureInfo.CurrentCulture)
		{
		}

		public Expression(LogicalExpression expression, EvaluateOptions options, CultureInfo cultureInfo)
		{
			if (expression == null)
			{
				throw new ArgumentException("Expression can't be null", "expression");
			}
			ParsedExpression = expression;
			Options = options;
			CultureInfo = cultureInfo;
		}

		private static void CleanCache()
		{
			List<string> list = new List<string>();
			try
			{
				Rwl.AcquireWriterLock(-1);
				foreach (KeyValuePair<string, WeakReference> compiledExpression in _compiledExpressions)
				{
					if (!compiledExpression.Value.IsAlive)
					{
						list.Add(compiledExpression.Key);
					}
				}
				foreach (string item in list)
				{
					_compiledExpressions.Remove(item);
				}
			}
			finally
			{
				Rwl.ReleaseReaderLock();
			}
		}

		public static LogicalExpression Compile(string expression, bool nocache)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			LogicalExpression logicalExpression = null;
			if (_cacheEnabled && !nocache)
			{
				try
				{
					Rwl.AcquireReaderLock(-1);
					if (_compiledExpressions.ContainsKey(expression))
					{
						WeakReference weakReference = _compiledExpressions[expression];
						logicalExpression = weakReference.Target as LogicalExpression;
						if (weakReference.IsAlive && logicalExpression != null)
						{
							return logicalExpression;
						}
					}
				}
				finally
				{
					Rwl.ReleaseReaderLock();
				}
			}
			if (logicalExpression == null)
			{
				NCalcParser nCalcParser = new NCalcParser((ITokenStream)new CommonTokenStream((ITokenSource)(object)new NCalcLexer((ICharStream)new ANTLRStringStream(expression))));
				logicalExpression = nCalcParser.GetExpression();
				if (nCalcParser.Errors != null && nCalcParser.Errors.Count > 0)
				{
					throw new EvaluationException(string.Join(Environment.NewLine, nCalcParser.Errors.ToArray()));
				}
				if (_cacheEnabled && !nocache)
				{
					try
					{
						Rwl.AcquireWriterLock(-1);
						_compiledExpressions[expression] = new WeakReference(logicalExpression);
					}
					finally
					{
						Rwl.ReleaseWriterLock();
					}
					CleanCache();
				}
			}
			return logicalExpression;
		}

		public bool HasErrors()
		{
			try
			{
				if (ParsedExpression == null)
				{
					ParsedExpression = Compile(OriginalExpression, (Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache);
				}
				return ParsedExpression != null && Error != null;
			}
			catch (Exception ex)
			{
				Error = ex.Message;
				return true;
			}
		}

		public object Evaluate()
		{
			if (HasErrors())
			{
				throw new EvaluationException(Error);
			}
			if (ParsedExpression == null)
			{
				ParsedExpression = Compile(OriginalExpression, (Options & EvaluateOptions.NoCache) == EvaluateOptions.NoCache);
			}
			EvaluationVisitor evaluationVisitor = new EvaluationVisitor(Options, CultureInfo);
			evaluationVisitor.EvaluateFunction += this.EvaluateFunction;
			evaluationVisitor.EvaluateParameter += this.EvaluateParameter;
			evaluationVisitor.Parameters = Parameters;
			if ((Options & EvaluateOptions.IterateParameters) == EvaluateOptions.IterateParameters)
			{
				int num = -1;
				ParametersBackup = new Dictionary<string, object>();
				foreach (string key in Parameters.Keys)
				{
					ParametersBackup.Add(key, Parameters[key]);
				}
				ParameterEnumerators = new Dictionary<string, IEnumerator>();
				foreach (object value in Parameters.Values)
				{
					if (!(value is IEnumerable))
					{
						continue;
					}
					int num2 = 0;
					foreach (object item in (IEnumerable)value)
					{
						_ = item;
						num2++;
					}
					if (num == -1)
					{
						num = num2;
					}
					else if (num2 != num)
					{
						throw new EvaluationException("When IterateParameters option is used, IEnumerable parameters must have the same number of items");
					}
				}
				foreach (string key2 in Parameters.Keys)
				{
					if (Parameters[key2] is IEnumerable enumerable)
					{
						ParameterEnumerators.Add(key2, enumerable.GetEnumerator());
					}
				}
				List<object> list = new List<object>();
				for (int i = 0; i < num; i++)
				{
					foreach (string key3 in ParameterEnumerators.Keys)
					{
						IEnumerator enumerator5 = ParameterEnumerators[key3];
						enumerator5.MoveNext();
						Parameters[key3] = enumerator5.Current;
					}
					ParsedExpression.Accept(evaluationVisitor);
					list.Add(evaluationVisitor.Result);
				}
				return list;
			}
			ParsedExpression.Accept(evaluationVisitor);
			return evaluationVisitor.Result;
		}
	}
	public class FunctionArgs : EventArgs
	{
		private object _result;

		private Expression[] _parameters = new Expression[0];

		public object Result
		{
			get
			{
				return _result;
			}
			set
			{
				_result = value;
				HasResult = true;
			}
		}

		public bool HasResult { get; set; }

		public Expression[] Parameters
		{
			get
			{
				return _parameters;
			}
			set
			{
				_parameters = value;
			}
		}

		public object[] EvaluateParameters()
		{
			object[] array = new object[_parameters.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = _parameters[i].Evaluate();
			}
			return array;
		}
	}
	[GeneratedCode("ANTLR", "3.5.0.2")]
	[CLSCompliant(false)]
	public class NCalcLexer : Lexer
	{
		private class DFA10 : DFA
		{
			private const string DFA10_eotS = "\u0003\uffff\u0001\u0006\u0003\uffff";

			private const string DFA10_eofS = "\a\uffff";

			private const string DFA10_minS = "\u0002.\u0001\uffff\u00010\u0003\uffff";

			private const string DFA10_maxS = "\u00019\u0001e\u0001\uffff\u00019\u0003\uffff";

			private const string DFA10_acceptS = "\u0002\uffff\u0001\u0001\u0001\uffff\u0001\u0003\u0001\u0001\u0001\u0002";

			private const string DFA10_specialS = "\a\uffff}>";

			private static readonly string[] DFA10_transitionS;

			private static readonly short[] DFA10_eot;

			private static readonly short[] DFA10_eof;

			private static readonly char[] DFA10_min;

			private static readonly char[] DFA10_max;

			private static readonly short[] DFA10_accept;

			private static readonly short[] DFA10_special;

			private static readonly short[][] DFA10_transition;

			public override string Description => "262:1: FLOAT : ( ( DIGIT )* '.' ( DIGIT )+ ( EXPONENT )? | ( DIGIT )+ '.' ( DIGIT )* ( EXPONENT )? | ( DIGIT )+ EXPONENT );";

			static DFA10()
			{
				DFA10_transitionS = new string[7] { "\u0001\u0002\u0001\uffff\n\u0001", "\u0001\u0003\u0001\uffff\n\u0001\v\uffff\u0001\u0004\u001f\uffff\u0001\u0004", "", "\n\u0005", "", "", "" };
				DFA10_eot = DFA.UnpackEncodedString("\u0003\uffff\u0001\u0006\u0003\uffff");
				DFA10_eof = DFA.UnpackEncodedString("\a\uffff");
				DFA10_min = DFA.UnpackEncodedStringToUnsignedChars("\u0002.\u0001\uffff\u00010\u0003\uffff");
				DFA10_max = DFA.UnpackEncodedStringToUnsignedChars("\u00019\u0001e\u0001\uffff\u00019\u0003\uffff");
				DFA10_accept = DFA.UnpackEncodedString("\u0002\uffff\u0001\u0001\u0001\uffff\u0001\u0003\u0001\u0001\u0001\u0002");
				DFA10_special = DFA.UnpackEncodedString("\a\uffff}>");
				int num = DFA10_transitionS.Length;
				DFA10_transition = new short[num][];
				for (int i = 0; i < num; i++)
				{
					DFA10_transition[i] = DFA.UnpackEncodedString(DFA10_transitionS[i]);
				}
			}

			public DFA10(BaseRecognizer recognizer)
			{
				base.recognizer = recognizer;
				base.decisionNumber = 10;
				base.eot = DFA10_eot;
				base.eof = DFA10_eof;
				base.min = DFA10_min;
				base.max = DFA10_max;
				base.accept = DFA10_accept;
				base.special = DFA10_special;
				base.transition = DFA10_transition;
			}

			public override void Error(NoViableAltException nvae)
			{
			}
		}

		private class DFA17 : DFA
		{
			private const string DFA17_eotS = "\u0001\uffff\u0001!\u0001\uffff\u0001#\u0002\uffff\u0001%\u0005\uffff\u0001)\u0001+\u0001.\u0002\uffff\u00010\u0001\uffff\u0006\u001e\u00018\u0017\uffff\u0003\u001e\u0001<\u0002\u001e\u0002\uffff\u0002\u001e\u0001@\u0001\uffff\u0001A\u0001B\u0001\u001e\u0003\uffff\u0001D\u0001\uffff";

			private const string DFA17_eofS = "E\uffff";

			private const string DFA17_minS = "\u0001\t\u0001=\u0001\uffff\u0001&\u0002\uffff\u0001*\u0005\uffff\u0001<\u0002=\u0002\uffff\u0001|\u0001\uffff\u0001R\u0001A\u0001N\u0001R\u0001O\u0001+\u0001.\u0017\uffff\u0001U\u0001L\u0001D\u00010\u0001T\u00010\u0002\uffff\u0001E\u0001S\u00010\u0001\uffff\u00020\u0001E\u0003\uffff\u00010\u0001\uffff";

			private const string DFA17_maxS = "\u0001~\u0001=\u0001\uffff\u0001&\u0002\uffff\u0001*\u0005\uffff\u0001>\u0001=\u0001>\u0002\uffff\u0001|\u0001\uffff\u0001r\u0001a\u0001n\u0001r\u0001o\u00019\u0001e\u0017\uffff\u0001u\u0001l\u0001d\u0001z\u0001t\u00019\u0002\uffff\u0001e\u0001s\u0001z\u0001\uffff\u0002z\u0001e\u0003\uffff\u0001z\u0001\uffff";

			private const string DFA17_acceptS = "\u0002\uffff\u0001\u0003\u0001\uffff\u0001\u0006\u0001\a\u0001\uffff\u0001\n\u0001\v\u0001\f\u0001\r\u0001\u000e\u0003\uffff\u0001\u0018\u0001\u0019\u0001\uffff\u0001\u001c\a\uffff\u0001$\u0001%\u0001&\u0001'\u0001\"\u0001)\u0001\u0002\u0001\u0001\u0001\u0004\u0001\u0005\u0001\t\u0001\b\u0001\u0010\u0001\u0011\u0001\u0012\u0001\u000f\u0001\u0014\u0001\u0013\u0001\u0016\u0001\u0017\u0001\u0015\u0001\u001b\u0001\u001a\u0006\uffff\u0001(\u0001#\u0003\uffff\u0001 \u0003\uffff\u0001\u001f\u0001!\u0001\u001d\u0001\uffff\u0001\u001e";

			private const string DFA17_specialS = "E\uffff}>";

			private static readonly string[] DFA17_transitionS;

			private static readonly short[] DFA17_eot;

			private static readonly short[] DFA17_eof;

			private static readonly char[] DFA17_min;

			private static readonly char[] DFA17_max;

			private static readonly short[] DFA17_accept;

			private static readonly short[] DFA17_special;

			private static readonly short[][] DFA17_transition;

			public override string Description => "1:1: Tokens : ( T__48 | T__49 | T__50 | T__51 | T__52 | T__53 | T__54 | T__55 | T__56 | T__57 | T__58 | T__59 | T__60 | T__61 | T__62 | T__63 | T__64 | T__65 | T__66 | T__67 | T__68 | T__69 | T__70 | T__71 | T__72 | T__73 | T__74 | T__75 | TRUE | FALSE | AND | OR | NOT | ID | INTEGER | FLOAT | STRING | DATETIME | NAME | EXPONENT | WS );";

			static DFA17()
			{
				DFA17_transitionS = new string[69]
				{
					"\u0002\u001f\u0001\uffff\u0002\u001f\u0012\uffff\u0001\u001f\u0001\u0001\u0001\uffff\u0001\u001c\u0001\uffff\u0001\u0002\u0001\u0003\u0001\u001b\u0001\u0004\u0001\u0005\u0001\u0006\u0001\a\u0001\b\u0001\t\u0001\u001a\u0001\n\n\u0019\u0001\v\u0001\uffff\u0001\f\u0001\r\u0001\u000e\u0001\u000f\u0001\uffff\u0001\u0015\u0003\u001e\u0001\u0018\u0001\u0014\a\u001e\u0001\u0017\u0001\u0016\u0004\u001e\u0001\u0013\u0006\u001e\u0001\u001d\u0002\uffff\u0001\u0010\u0001\u001e\u0001\uffff\u0001\u0015\u0003\u001e\u0001\u0018\u0001\u0014\a\u001e\u0001\u0017\u0001\u0016\u0004\u001e\u0001\u0013\u0006\u001e\u0001\uffff\u0001\u0011\u0001\uffff\u0001\u0012", "\u0001 ", "", "\u0001\"", "", "", "\u0001$", "", "", "",
					"", "", "\u0001&\u0001'\u0001(", "\u0001*", "\u0001,\u0001-", "", "", "\u0001/", "", "\u00011\u001f\uffff\u00011",
					"\u00012\u001f\uffff\u00012", "\u00013\u001f\uffff\u00013", "\u00014\u001f\uffff\u00014", "\u00015\u001f\uffff\u00015", "\u00017\u0001\uffff\u00017\u0002\uffff\n6", "\u0001\u001a\u0001\uffff\n\u0019\v\uffff\u0001\u001a\u001f\uffff\u0001\u001a", "", "", "", "",
					"", "", "", "", "", "", "", "", "", "",
					"", "", "", "", "", "", "", "", "", "\u00019\u001f\uffff\u00019",
					"\u0001:\u001f\uffff\u0001:", "\u0001;\u001f\uffff\u0001;", "\n\u001e\a\uffff\u001a\u001e\u0004\uffff\u0001\u001e\u0001\uffff\u001a\u001e", "\u0001=\u001f\uffff\u0001=", "\n6", "", "", "\u0001>\u001f\uffff\u0001>", "\u0001?\u001f\uffff\u0001?", "\n\u001e\a\uffff\u001a\u001e\u0004\uffff\u0001\u001e\u0001\uffff\u001a\u001e",
					"", "\n\u001e\a\uffff\u001a\u001e\u0004\uffff\u0001\u001e\u0001\uffff\u001a\u001e", "\n\u001e\a\uffff\u001a\u001e\u0004\uffff\u0001\u001e\u0001\uffff\u001a\u001e", "\u0001C\u001f\uffff\u0001C", "", "", "", "\n\u001e\a\uffff\u001a\u001e\u0004\uffff\u0001\u001e\u0001\uffff\u001a\u001e", ""
				};
				DFA17_eot = DFA.UnpackEncodedString("\u0001\uffff\u0001!\u0001\uffff\u0001#\u0002\uffff\u0001%\u0005\uffff\u0001)\u0001+\u0001.\u0002\uffff\u00010\u0001\uffff\u0006\u001e\u00018\u0017\uffff\u0003\u001e\u0001<\u0002\u001e\u0002\uffff\u0002\u001e\u0001@\u0001\uffff\u0001A\u0001B\u0001\u001e\u0003\uffff\u0001D\u0001\uffff");
				DFA17_eof = DFA.UnpackEncodedString("E\uffff");
				DFA17_min = DFA.UnpackEncodedStringToUnsignedChars("\u0001\t\u0001=\u0001\uffff\u0001&\u0002\uffff\u0001*\u0005\uffff\u0001<\u0002=\u0002\uffff\u0001|\u0001\uffff\u0001R\u0001A\u0001N\u0001R\u0001O\u0001+\u0001.\u0017\uffff\u0001U\u0001L\u0001D\u00010\u0001T\u00010\u0002\uffff\u0001E\u0001S\u00010\u0001\uffff\u00020\u0001E\u0003\uffff\u00010\u0001\uffff");
				DFA17_max = DFA.UnpackEncodedStringToUnsignedChars("\u0001~\u0001=\u0001\uffff\u0001&\u0002\uffff\u0001*\u0005\uffff\u0001>\u0001=\u0001>\u0002\uffff\u0001|\u0001\uffff\u0001r\u0001a\u0001n\u0001r\u0001o\u00019\u0001e\u0017\uffff\u0001u\u0001l\u0001d\u0001z\u0001t\u00019\u0002\uffff\u0001e\u0001s\u0001z\u0001\uffff\u0002z\u0001e\u0003\uffff\u0001z\u0001\uffff");
				DFA17_accept = DFA.UnpackEncodedString("\u0002\uffff\u0001\u0003\u0001\uffff\u0001\u0006\u0001\a\u0001\uffff\u0001\n\u0001\v\u0001\f\u0001\r\u0001\u000e\u0003\uffff\u0001\u0018\u0001\u0019\u0001\uffff\u0001\u001c\a\uffff\u0001$\u0001%\u0001&\u0001'\u0001\"\u0001)\u0001\u0002\u0001\u0001\u0001\u0004\u0001\u0005\u0001\t\u0001\b\u0001\u0010\u0001\u0011\u0001\u0012\u0001\u000f\u0001\u0014\u0001\u0013\u0001\u0016\u0001\u0017\u0001\u0015\u0001\u001b\u0001\u001a\u0006\uffff\u0001(\u0001#\u0003\uffff\u0001 \u0003\uffff\u0001\u001f\u0001!\u0001\u001d\u0001\uffff\u0001\u001e");
				DFA17_special = DFA.UnpackEncodedString("E\uffff}>");
				int num = DFA17_transitionS.Length;
				DFA17_transition = new short[num][];
				for (int i = 0; i < num; i++)
				{
					DFA17_transition[i] = DFA.UnpackEncodedString(DFA17_transitionS[i]);
				}
			}

			public DFA17(BaseRecognizer recognizer)
			{
				base.recognizer = recognizer;
				base.decisionNumber = 17;
				base.eot = DFA17_eot;
				base.eof = DFA17_eof;
				base.min = DFA17_min;
				base.max = DFA17_max;
				base.accept = DFA17_accept;
				base.special = DFA17_special;
				base.transition = DFA17_transition;
			}

			public override void Error(NoViableAltException nvae)
			{
			}
		}

		public const int EOF = -1;

		public const int A = 4;

		public const int AND = 5;

		public const int B = 6;

		public const int C = 7;

		public const int D = 8;

		public const int DATETIME = 9;

		public const int DIGIT = 10;

		public const int E = 11;

		public const int EXPONENT = 12;

		public const int EscapeSequence = 13;

		public const int F = 14;

		public const int FALSE = 15;

		public const int FLOAT = 16;

		public const int G = 17;

		public const int H = 18;

		public const int HexDigit = 19;

		public const int I = 20;

		public const int ID = 21;

		public const int INTEGER = 22;

		public const int J = 23;

		public const int K = 24;

		public const int L = 25;

		public const int LETTER = 26;

		public const int M = 27;

		public const int N = 28;

		public const int NAME = 29;

		public const int NOT = 30;

		public const int O = 31;

		public const int OR = 32;

		public const int P = 33;

		public const int Q = 34;

		public const int R = 35;

		public const int S = 36;

		public const int STRING = 37;

		public const int T = 38;

		public const int TRUE = 39;

		public const int U = 40;

		public const int UnicodeEscape = 41;

		public const int V = 42;

		public const int W = 43;

		public const int WS = 44;

		public const int X = 45;

		public const int Y = 46;

		public const int Z = 47;

		public const int T__48 = 48;

		public const int T__49 = 49;

		public const int T__50 = 50;

		public const int T__51 = 51;

		public const int T__52 = 52;

		public const int T__53 = 53;

		public const int T__54 = 54;

		public const int T__55 = 55;

		public const int T__56 = 56;

		public const int T__57 = 57;

		public const int T__58 = 58;

		public const int T__59 = 59;

		public const int T__60 = 60;

		public const int T__61 = 61;

		public const int T__62 = 62;

		public const int T__63 = 63;

		public const int T__64 = 64;

		public const int T__65 = 65;

		public const int T__66 = 66;

		public const int T__67 = 67;

		public const int T__68 = 68;

		public const int T__69 = 69;

		public const int T__70 = 70;

		public const int T__71 = 71;

		public const int T__72 = 72;

		public const int T__73 = 73;

		public const int T__74 = 74;

		public const int T__75 = 75;

		private DFA10 dfa10;

		private DFA17 dfa17;

		public override string GrammarFileName => "NCalc.g";

		public NCalcLexer()
		{
		}

		public NCalcLexer(ICharStream input)
			: this(input, new RecognizerSharedState())
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown


		public NCalcLexer(ICharStream input, RecognizerSharedState state)
			: base(input, state)
		{
		}

		[GrammarRule("T__48")]
		private void mT__48()
		{
			try
			{
				int type = 48;
				int channel = 0;
				((Lexer)this).Match(33);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__49")]
		private void mT__49()
		{
			try
			{
				int type = 49;
				int channel = 0;
				((Lexer)this).Match("!=");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__50")]
		private void mT__50()
		{
			try
			{
				int type = 50;
				int channel = 0;
				((Lexer)this).Match(37);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__51")]
		private void mT__51()
		{
			try
			{
				int type = 51;
				int channel = 0;
				((Lexer)this).Match("&&");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__52")]
		private void mT__52()
		{
			try
			{
				int type = 52;
				int channel = 0;
				((Lexer)this).Match(38);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__53")]
		private void mT__53()
		{
			try
			{
				int type = 53;
				int channel = 0;
				((Lexer)this).Match(40);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__54")]
		private void mT__54()
		{
			try
			{
				int type = 54;
				int channel = 0;
				((Lexer)this).Match(41);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__55")]
		private void mT__55()
		{
			try
			{
				int type = 55;
				int channel = 0;
				((Lexer)this).Match(42);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__56")]
		private void mT__56()
		{
			try
			{
				int type = 56;
				int channel = 0;
				((Lexer)this).Match("**");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__57")]
		private void mT__57()
		{
			try
			{
				int type = 57;
				int channel = 0;
				((Lexer)this).Match(43);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__58")]
		private void mT__58()
		{
			try
			{
				int type = 58;
				int channel = 0;
				((Lexer)this).Match(44);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__59")]
		private void mT__59()
		{
			try
			{
				int type = 59;
				int channel = 0;
				((Lexer)this).Match(45);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__60")]
		private void mT__60()
		{
			try
			{
				int type = 60;
				int channel = 0;
				((Lexer)this).Match(47);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__61")]
		private void mT__61()
		{
			try
			{
				int type = 61;
				int channel = 0;
				((Lexer)this).Match(58);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__62")]
		private void mT__62()
		{
			try
			{
				int type = 62;
				int channel = 0;
				((Lexer)this).Match(60);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__63")]
		private void mT__63()
		{
			try
			{
				int type = 63;
				int channel = 0;
				((Lexer)this).Match("<<");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__64")]
		private void mT__64()
		{
			try
			{
				int type = 64;
				int channel = 0;
				((Lexer)this).Match("<=");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__65")]
		private void mT__65()
		{
			try
			{
				int type = 65;
				int channel = 0;
				((Lexer)this).Match("<>");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__66")]
		private void mT__66()
		{
			try
			{
				int type = 66;
				int channel = 0;
				((Lexer)this).Match(61);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__67")]
		private void mT__67()
		{
			try
			{
				int type = 67;
				int channel = 0;
				((Lexer)this).Match("==");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__68")]
		private void mT__68()
		{
			try
			{
				int type = 68;
				int channel = 0;
				((Lexer)this).Match(62);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__69")]
		private void mT__69()
		{
			try
			{
				int type = 69;
				int channel = 0;
				((Lexer)this).Match(">=");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__70")]
		private void mT__70()
		{
			try
			{
				int type = 70;
				int channel = 0;
				((Lexer)this).Match(">>");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__71")]
		private void mT__71()
		{
			try
			{
				int type = 71;
				int channel = 0;
				((Lexer)this).Match(63);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__72")]
		private void mT__72()
		{
			try
			{
				int type = 72;
				int channel = 0;
				((Lexer)this).Match(94);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__73")]
		private void mT__73()
		{
			try
			{
				int type = 73;
				int channel = 0;
				((Lexer)this).Match(124);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__74")]
		private void mT__74()
		{
			try
			{
				int type = 74;
				int channel = 0;
				((Lexer)this).Match("||");
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("T__75")]
		private void mT__75()
		{
			try
			{
				int type = 75;
				int channel = 0;
				((Lexer)this).Match(126);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("TRUE")]
		private void mTRUE()
		{
			try
			{
				int type = 39;
				int channel = 0;
				mT();
				mR();
				mU();
				mE();
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("FALSE")]
		private void mFALSE()
		{
			try
			{
				int type = 15;
				int channel = 0;
				mF();
				mA();
				mL();
				mS();
				mE();
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("AND")]
		private void mAND()
		{
			try
			{
				int type = 5;
				int channel = 0;
				mA();
				mN();
				mD();
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("OR")]
		private void mOR()
		{
			try
			{
				int type = 32;
				int channel = 0;
				mO();
				mR();
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("NOT")]
		private void mNOT()
		{
			try
			{
				int type = 30;
				int channel = 0;
				mN();
				mO();
				mT();
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("ID")]
		private void mID()
		{
			try
			{
				int type = 21;
				int channel = 0;
				mLETTER();
				try
				{
					while (true)
					{
						int num = 2;
						try
						{
							int num2 = ((IIntStream)base.input).LA(1);
							if ((num2 < 48 || num2 > 57) && (num2 < 65 || num2 > 90))
							{
								switch (num2)
								{
								case 95:
								case 97:
								case 98:
								case 99:
								case 100:
								case 101:
								case 102:
								case 103:
								case 104:
								case 105:
								case 106:
								case 107:
								case 108:
								case 109:
								case 110:
								case 111:
								case 112:
								case 113:
								case 114:
								case 115:
								case 116:
								case 117:
								case 118:
								case 119:
								case 120:
								case 121:
								case 122:
									break;
								default:
									goto end_IL_000d;
								}
							}
							num = 1;
							end_IL_000d:;
						}
						finally
						{
						}
						if (num != 1)
						{
							break;
						}
						((IIntStream)base.input).Consume();
					}
				}
				finally
				{
				}
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("INTEGER")]
		private void mINTEGER()
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int type = 22;
				int channel = 0;
				int num = 0;
				try
				{
					while (true)
					{
						int num2 = 2;
						try
						{
							int num3 = ((IIntStream)base.input).LA(1);
							if (num3 >= 48 && num3 <= 57)
							{
								num2 = 1;
							}
						}
						finally
						{
						}
						if (num2 != 1)
						{
							break;
						}
						((IIntStream)base.input).Consume();
						num++;
					}
					if (num < 1)
					{
						throw new EarlyExitException(2, (IIntStream)(object)base.input);
					}
				}
				finally
				{
				}
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("FLOAT")]
		private void mFLOAT()
		{
			//IL_0149: 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)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int type = 16;
				int channel = 0;
				int num = 3;
				try
				{
					num = ((DFA)dfa10).Predict((IIntStream)(object)base.input);
				}
				catch (NoViableAltException)
				{
					throw;
				}
				finally
				{
				}
				switch (num)
				{
				case 1:
				{
					try
					{
						while (true)
						{
							int num5 = 2;
							try
							{
								int num6 = ((IIntStream)base.input).LA(1);
								if (num6 >= 48 && num6 <= 57)
								{
									num5 = 1;
								}
							}
							finally
							{
							}
							if (num5 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
						}
					}
					finally
					{
					}
					((Lexer)this).Match(46);
					int num7 = 0;
					try
					{
						while (true)
						{
							int num8 = 2;
							try
							{
								int num9 = ((IIntStream)base.input).LA(1);
								if (num9 >= 48 && num9 <= 57)
								{
									num8 = 1;
								}
							}
							finally
							{
							}
							if (num8 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
							num7++;
						}
						if (num7 < 1)
						{
							throw new EarlyExitException(4, (IIntStream)(object)base.input);
						}
					}
					finally
					{
					}
					int num10 = 2;
					try
					{
						try
						{
							int num11 = ((IIntStream)base.input).LA(1);
							if (num11 == 69 || num11 == 101)
							{
								num10 = 1;
							}
						}
						finally
						{
						}
						if (num10 == 1)
						{
							mEXPONENT();
						}
					}
					finally
					{
					}
					break;
				}
				case 2:
				{
					int num12 = 0;
					try
					{
						while (true)
						{
							int num13 = 2;
							try
							{
								int num14 = ((IIntStream)base.input).LA(1);
								if (num14 >= 48 && num14 <= 57)
								{
									num13 = 1;
								}
							}
							finally
							{
							}
							if (num13 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
							num12++;
						}
						if (num12 < 1)
						{
							throw new EarlyExitException(6, (IIntStream)(object)base.input);
						}
					}
					finally
					{
					}
					((Lexer)this).Match(46);
					try
					{
						while (true)
						{
							int num15 = 2;
							try
							{
								int num16 = ((IIntStream)base.input).LA(1);
								if (num16 >= 48 && num16 <= 57)
								{
									num15 = 1;
								}
							}
							finally
							{
							}
							if (num15 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
						}
					}
					finally
					{
					}
					int num17 = 2;
					try
					{
						try
						{
							int num18 = ((IIntStream)base.input).LA(1);
							if (num18 == 69 || num18 == 101)
							{
								num17 = 1;
							}
						}
						finally
						{
						}
						if (num17 == 1)
						{
							mEXPONENT();
						}
					}
					finally
					{
					}
					break;
				}
				case 3:
				{
					int num2 = 0;
					try
					{
						while (true)
						{
							int num3 = 2;
							try
							{
								int num4 = ((IIntStream)base.input).LA(1);
								if (num4 >= 48 && num4 <= 57)
								{
									num3 = 1;
								}
							}
							finally
							{
							}
							if (num3 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
							num2++;
						}
						if (num2 < 1)
						{
							throw new EarlyExitException(9, (IIntStream)(object)base.input);
						}
					}
					finally
					{
					}
					mEXPONENT();
					break;
				}
				}
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("STRING")]
		private void mSTRING()
		{
			try
			{
				int type = 37;
				int channel = 0;
				((Lexer)this).Match(39);
				try
				{
					while (true)
					{
						int num = 3;
						try
						{
							int num2 = ((IIntStream)base.input).LA(1);
							switch (num2)
							{
							case 92:
								num = 1;
								goto end_IL_000f;
							default:
								if ((num2 >= 40 && num2 <= 91) || (num2 >= 93 && num2 <= 65535))
								{
									break;
								}
								goto end_IL_000f;
							case 32:
							case 33:
							case 34:
							case 35:
							case 36:
							case 37:
							case 38:
								break;
							}
							num = 2;
							end_IL_000f:;
						}
						finally
						{
						}
						switch (num)
						{
						case 1:
							mEscapeSequence();
							continue;
						case 2:
							((IIntStream)base.input).Consume();
							continue;
						}
						break;
					}
				}
				finally
				{
				}
				((Lexer)this).Match(39);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("DATETIME")]
		private void mDATETIME()
		{
			try
			{
				int type = 9;
				int channel = 0;
				((Lexer)this).Match(35);
				try
				{
					while (true)
					{
						int num = 2;
						try
						{
							int num2 = ((IIntStream)base.input).LA(1);
							if ((num2 >= 0 && num2 <= 34) || (num2 >= 36 && num2 <= 65535))
							{
								num = 1;
							}
						}
						finally
						{
						}
						if (num != 1)
						{
							break;
						}
						((IIntStream)base.input).Consume();
					}
				}
				finally
				{
				}
				((Lexer)this).Match(35);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("NAME")]
		private void mNAME()
		{
			try
			{
				int type = 29;
				int channel = 0;
				((Lexer)this).Match(91);
				try
				{
					while (true)
					{
						int num = 2;
						try
						{
							int num2 = ((IIntStream)base.input).LA(1);
							if ((num2 >= 0 && num2 <= 92) || (num2 >= 94 && num2 <= 65535))
							{
								num = 1;
							}
						}
						finally
						{
						}
						if (num != 1)
						{
							break;
						}
						((IIntStream)base.input).Consume();
					}
				}
				finally
				{
				}
				((Lexer)this).Match(93);
				((BaseRecognizer)this).state.type = type;
				((BaseRecognizer)this).state.channel = channel;
			}
			finally
			{
			}
		}

		[GrammarRule("EXPONENT")]
		private void mEXPONENT()
		{
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				int type = 12;
				int channel = 0;
				if (((IIntStream)base.input).LA(1) == 69 || ((IIntStream)base.input).LA(1) == 101)
				{
					((IIntStream)base.input).Consume();
					int num = 2;
					try
					{
						try
						{
							int num2 = ((IIntStream)base.input).LA(1);
							if (num2 == 43 || num2 == 45)
							{
								num = 1;
							}
						}
						finally
						{
						}
						if (num == 1)
						{
							((IIntStream)base.input).Consume();
						}
					}
					finally
					{
					}
					int num3 = 0;
					try
					{
						while (true)
						{
							int num4 = 2;
							try
							{
								int num5 = ((IIntStream)base.input).LA(1);
								if (num5 >= 48 && num5 <= 57)
								{
									num4 = 1;
								}
							}
							finally
							{
							}
							if (num4 != 1)
							{
								break;
							}
							((IIntStream)base.input).Consume();
							num3++;
						}
						if (num3 < 1)
						{
							throw new EarlyExitException(15, (IIntStream)(object)base.input);
						}
					}
					finally
					{
					}
					((BaseRecognizer)this).state.type = type;
					((BaseRecognizer)this).state.channel = channel;
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("LETTER")]
		private void mLETTER()
		{
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Expected O, but got Unknown
			try
			{
				if ((((IIntStream)base.input).LA(1) >= 65 && ((IIntStream)base.input).LA(1) <= 90) || ((IIntStream)base.input).LA(1) == 95 || (((IIntStream)base.input).LA(1) >= 97 && ((IIntStream)base.input).LA(1) <= 122))
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("DIGIT")]
		private void mDIGIT()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) >= 48 && ((IIntStream)base.input).LA(1) <= 57)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("EscapeSequence")]
		private void mEscapeSequence()
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				((Lexer)this).Match(92);
				int num = 6;
				try
				{
					try
					{
						num = ((IIntStream)base.input).LA(1) switch
						{
							110 => 1, 
							114 => 2, 
							116 => 3, 
							39 => 4, 
							92 => 5, 
							117 => 6, 
							_ => throw new NoViableAltException("", 16, 0, (IIntStream)(object)base.input, 1), 
						};
					}
					finally
					{
					}
					switch (num)
					{
					case 1:
						((Lexer)this).Match(110);
						break;
					case 2:
						((Lexer)this).Match(114);
						break;
					case 3:
						((Lexer)this).Match(116);
						break;
					case 4:
						((Lexer)this).Match(39);
						break;
					case 5:
						((Lexer)this).Match(92);
						break;
					case 6:
						mUnicodeEscape();
						break;
					}
				}
				finally
				{
				}
			}
			finally
			{
			}
		}

		[GrammarRule("HexDigit")]
		private void mHexDigit()
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Expected O, but got Unknown
			try
			{
				if ((((IIntStream)base.input).LA(1) >= 48 && ((IIntStream)base.input).LA(1) <= 57) || (((IIntStream)base.input).LA(1) >= 65 && ((IIntStream)base.input).LA(1) <= 70) || (((IIntStream)base.input).LA(1) >= 97 && ((IIntStream)base.input).LA(1) <= 102))
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("UnicodeEscape")]
		private void mUnicodeEscape()
		{
			try
			{
				((Lexer)this).Match(117);
				mHexDigit();
				mHexDigit();
				mHexDigit();
				mHexDigit();
			}
			finally
			{
			}
		}

		[GrammarRule("WS")]
		private void mWS()
		{
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Expected O, but got Unknown
			try
			{
				int type = 44;
				int num = 0;
				if ((((IIntStream)base.input).LA(1) >= 9 && ((IIntStream)base.input).LA(1) <= 10) || (((IIntStream)base.input).LA(1) >= 12 && ((IIntStream)base.input).LA(1) <= 13) || ((IIntStream)base.input).LA(1) == 32)
				{
					((IIntStream)base.input).Consume();
					num = 99;
					((BaseRecognizer)this).state.type = type;
					((BaseRecognizer)this).state.channel = num;
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("A")]
		private void mA()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 65 || ((IIntStream)base.input).LA(1) == 97)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("B")]
		private void mB()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 66 || ((IIntStream)base.input).LA(1) == 98)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("C")]
		private void mC()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 67 || ((IIntStream)base.input).LA(1) == 99)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("D")]
		private void mD()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 68 || ((IIntStream)base.input).LA(1) == 100)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("E")]
		private void mE()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 69 || ((IIntStream)base.input).LA(1) == 101)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("F")]
		private void mF()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 70 || ((IIntStream)base.input).LA(1) == 102)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("G")]
		private void mG()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 71 || ((IIntStream)base.input).LA(1) == 103)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("H")]
		private void mH()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 72 || ((IIntStream)base.input).LA(1) == 104)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("I")]
		private void mI()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 73 || ((IIntStream)base.input).LA(1) == 105)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("J")]
		private void mJ()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 74 || ((IIntStream)base.input).LA(1) == 106)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("K")]
		private void mK()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 75 || ((IIntStream)base.input).LA(1) == 107)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("L")]
		private void mL()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 76 || ((IIntStream)base.input).LA(1) == 108)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("M")]
		private void mM()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 77 || ((IIntStream)base.input).LA(1) == 109)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("N")]
		private void mN()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 78 || ((IIntStream)base.input).LA(1) == 110)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("O")]
		private void mO()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 79 || ((IIntStream)base.input).LA(1) == 111)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("P")]
		private void mP()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 80 || ((IIntStream)base.input).LA(1) == 112)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("Q")]
		private void mQ()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 81 || ((IIntStream)base.input).LA(1) == 113)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("R")]
		private void mR()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 82 || ((IIntStream)base.input).LA(1) == 114)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("S")]
		private void mS()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 83 || ((IIntStream)base.input).LA(1) == 115)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("T")]
		private void mT()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 84 || ((IIntStream)base.input).LA(1) == 116)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("U")]
		private void mU()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 85 || ((IIntStream)base.input).LA(1) == 117)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("V")]
		private void mV()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 86 || ((IIntStream)base.input).LA(1) == 118)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("W")]
		private void mW()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 87 || ((IIntStream)base.input).LA(1) == 119)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("X")]
		private void mX()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 88 || ((IIntStream)base.input).LA(1) == 120)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("Y")]
		private void mY()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 89 || ((IIntStream)base.input).LA(1) == 121)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		[GrammarRule("Z")]
		private void mZ()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			try
			{
				if (((IIntStream)base.input).LA(1) == 90 || ((IIntStream)base.input).LA(1) == 122)
				{
					((IIntStream)base.input).Consume();
					return;
				}
				MismatchedSetException val = new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
				((Lexer)this).Recover((RecognitionException)(object)val);
				throw val;
			}
			finally
			{
			}
		}

		public override void mTokens()
		{
			int num = 41;
			try
			{
				num = ((DFA)dfa17).Predict((IIntStream)(object)base.input);
			}
			catch (NoViableAltException)
			{
				throw;
			}
			finally
			{
			}
			switch (num)
			{
			case 1:
				mT__48();
				break;
			case 2:
				mT__49();
				break;
			case 3:
				mT__50();
				break;
			case 4:
				mT__51();
				break;
			case 5:
				mT__52();
				break;
			case 6:
				mT__53();
				break;
			case 7:
				mT__54();
				break;
			case 8:
				mT__55();
				break;
			case 9:
				mT__56();
				break;
			case 10:
				mT__57();
				break;
			case 11:
				mT__58();
				break;
			case 12:
				mT__59();
				break;
			case 13:
				mT__60();
				break;
			case 14:
				mT__61();
				break;
			case 15:
				mT__62();
				break;
			case 16:
				mT__63();
				break;
			case 17:
				mT__64();
				break;
			case 18:
				mT__65();
				break;
			case 19:
				mT__66();
				break;
			case 20:
				mT__67();
				break;
			case 21:
				mT__68();
				break;
			case 22:
				mT__69();
				break;
			case 23:
				mT__70();
				break;
			case 24:
				mT__71();
				break;
			case 25:
				mT__72();
				break;
			case 26:
				mT__73();
				break;
			case 27:
				mT__74();
				break;
			case 28:
				mT__75();
				break;
			case 29:
				mTRUE();
				break;
			case 30:
				mFALSE();
				break;
			case 31:
				mAND();
				break;
			case 32:
				mOR();
				break;
			case 33:
				mNOT();
				break;
			case 34:
				mID();
				break;
			case 35:
				mINTEGER();
				break;
			case 36:
				mFLOAT();
				break;
			case 37:
				mSTRING();
				break;
			case 38:
				mDATETIME();
				break;
			case 39:
				mNAME();
				break;
			case 40:
				mEXPONENT();
				break;
			case 41:
				mWS();
				break;
			}
		}

		protected override void InitDFAs()
		{
			((BaseRecognizer)this).InitDFAs();
			dfa10 = new DFA10((BaseRecognizer)(object)this);
			dfa17 = new DFA17((BaseRecognizer)(object)this);
		}

		public override void EmitErrorMessage(string msg)
		{
			throw new EvaluationException(msg);
		}
	}
	[GeneratedCode("ANTLR", "3.5.0.2")]
	[CLSCompliant(false)]
	public class NCalcParser : Parser
	{
		private sealed class ncalcExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public ncalcExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class logicalExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public logicalExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class conditionalExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public conditionalExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class booleanAndExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public booleanAndExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class bitwiseOrExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public bitwiseOrExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class bitwiseXOrExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public bitwiseXOrExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class bitwiseAndExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public bitwiseAndExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class equalityExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public equalityExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class relationalExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public relationalExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class shiftExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public shiftExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class additiveExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public additiveExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class multiplicativeExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public multiplicativeExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class unaryExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public unaryExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class exponentialExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public exponentialExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class primaryExpression_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public LogicalExpression value;

			public primaryExpression_return(NCalcParser grammar)
			{
			}
		}

		private sealed class value_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public ValueExpression value;

			public value_return(NCalcParser grammar)
			{
			}
		}

		private sealed class identifier_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public Identifier value;

			public identifier_return(NCalcParser grammar)
			{
			}
		}

		private sealed class expressionList_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public List<LogicalExpression> value;

			public expressionList_return(NCalcParser grammar)
			{
			}
		}

		private sealed class arguments_return : AstParserRuleReturnScope<CommonTree, IToken>
		{
			public List<LogicalExpression> value;

			public arguments_return(NCalcParser grammar)
			{
			}
		}

		private static class Follow
		{
			public static readonly BitSet _logicalExpression_in_ncalcExpression73 = new BitSet(new ulong[1]);

			public static readonly BitSet _EOF_in_ncalcExpression75 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _conditionalExpression_in_logicalExpression95 = new BitSet(new ulong[2] { 2uL, 128uL });

			public static readonly BitSet _71_in_logicalExpression101 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _conditionalExpression_in_logicalExpression105 = new BitSet(new ulong[1] { 2305843009213693952uL });

			public static readonly BitSet _61_in_logicalExpression107 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _conditionalExpression_in_logicalExpression111 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _booleanAndExpression_in_conditionalExpression138 = new BitSet(new ulong[2] { 4294967298uL, 1024uL });

			public static readonly BitSet _set_in_conditionalExpression147 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _conditionalExpression_in_conditionalExpression163 = new BitSet(new ulong[2] { 4294967298uL, 1024uL });

			public static readonly BitSet _bitwiseOrExpression_in_booleanAndExpression197 = new BitSet(new ulong[1] { 2251799813685282uL });

			public static readonly BitSet _set_in_booleanAndExpression206 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _bitwiseOrExpression_in_booleanAndExpression222 = new BitSet(new ulong[1] { 2251799813685282uL });

			public static readonly BitSet _bitwiseXOrExpression_in_bitwiseOrExpression254 = new BitSet(new ulong[2] { 2uL, 512uL });

			public static readonly BitSet _73_in_bitwiseOrExpression263 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _bitwiseOrExpression_in_bitwiseOrExpression273 = new BitSet(new ulong[2] { 2uL, 512uL });

			public static readonly BitSet _bitwiseAndExpression_in_bitwiseXOrExpression307 = new BitSet(new ulong[2] { 2uL, 256uL });

			public static readonly BitSet _72_in_bitwiseXOrExpression316 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _bitwiseAndExpression_in_bitwiseXOrExpression326 = new BitSet(new ulong[2] { 2uL, 256uL });

			public static readonly BitSet _equalityExpression_in_bitwiseAndExpression358 = new BitSet(new ulong[1] { 4503599627370498uL });

			public static readonly BitSet _52_in_bitwiseAndExpression367 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _equalityExpression_in_bitwiseAndExpression377 = new BitSet(new ulong[1] { 4503599627370498uL });

			public static readonly BitSet _relationalExpression_in_equalityExpression411 = new BitSet(new ulong[2] { 562949953421314uL, 14uL });

			public static readonly BitSet _set_in_equalityExpression422 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _set_in_equalityExpression439 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _relationalExpression_in_equalityExpression458 = new BitSet(new ulong[2] { 562949953421314uL, 14uL });

			public static readonly BitSet _shiftExpression_in_relationalExpression491 = new BitSet(new ulong[2] { 4611686018427387906uL, 49uL });

			public static readonly BitSet _62_in_relationalExpression502 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _64_in_relationalExpression512 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _68_in_relationalExpression523 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _69_in_relationalExpression533 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _shiftExpression_in_relationalExpression545 = new BitSet(new ulong[2] { 4611686018427387906uL, 49uL });

			public static readonly BitSet _additiveExpression_in_shiftExpression577 = new BitSet(new ulong[2] { 9223372036854775810uL, 64uL });

			public static readonly BitSet _63_in_shiftExpression588 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _70_in_shiftExpression598 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _additiveExpression_in_shiftExpression610 = new BitSet(new ulong[2] { 9223372036854775810uL, 64uL });

			public static readonly BitSet _multiplicativeExpression_in_additiveExpression642 = new BitSet(new ulong[1] { 720575940379279362uL });

			public static readonly BitSet _57_in_additiveExpression653 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _59_in_additiveExpression663 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _multiplicativeExpression_in_additiveExpression675 = new BitSet(new ulong[1] { 720575940379279362uL });

			public static readonly BitSet _unaryExpression_in_multiplicativeExpression707 = new BitSet(new ulong[1] { 1190076201532653570uL });

			public static readonly BitSet _55_in_multiplicativeExpression718 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _60_in_multiplicativeExpression728 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _50_in_multiplicativeExpression738 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _unaryExpression_in_multiplicativeExpression750 = new BitSet(new ulong[1] { 1190076201532653570uL });

			public static readonly BitSet _exponentialExpression_in_unaryExpression776 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _set_in_unaryExpression786 = new BitSet(new ulong[1] { 9007886992769536uL });

			public static readonly BitSet _exponentialExpression_in_unaryExpression794 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _75_in_unaryExpression805 = new BitSet(new ulong[1] { 9007886992769536uL });

			public static readonly BitSet _exponentialExpression_in_unaryExpression808 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _59_in_unaryExpression818 = new BitSet(new ulong[1] { 9007886992769536uL });

			public static readonly BitSet _exponentialExpression_in_unaryExpression820 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _57_in_unaryExpression830 = new BitSet(new ulong[1] { 9007886992769536uL });

			public static readonly BitSet _exponentialExpression_in_unaryExpression832 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _primaryExpression_in_exponentialExpression857 = new BitSet(new ulong[1] { 72057594037927938uL });

			public static readonly BitSet _56_in_exponentialExpression866 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _unaryExpression_in_exponentialExpression870 = new BitSet(new ulong[1] { 72057594037927938uL });

			public static readonly BitSet _53_in_primaryExpression893 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _logicalExpression_in_primaryExpression895 = new BitSet(new ulong[1] { 18014398509481984uL });

			public static readonly BitSet _54_in_primaryExpression897 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _value_in_primaryExpression907 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _identifier_in_primaryExpression915 = new BitSet(new ulong[1] { 9007199254740994uL });

			public static readonly BitSet _arguments_in_primaryExpression920 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _INTEGER_in_value940 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _FLOAT_in_value948 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _STRING_in_value956 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _DATETIME_in_value965 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _TRUE_in_value972 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _FALSE_in_value980 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _ID_in_identifier998 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _NAME_in_identifier1006 = new BitSet(new ulong[1] { 2uL });

			public static readonly BitSet _logicalExpression_in_expressionList1030 = new BitSet(new ulong[1] { 288230376151711746uL });

			public static readonly BitSet _58_in_expressionList1037 = new BitSet(new ulong[2] { 729865303422501376uL, 2048uL });

			public static readonly BitSet _logicalExpression_in_expressionList1041 = new BitSet(new ulong[1] { 288230376151711746uL });

			public static readonly BitSet _53_in_arguments1070 = new BitSet(new ulong[2] { 747879701931983360uL, 2048uL });

			public static readonly BitSet _expressionList_in_arguments1074 = new BitSet(new ulong[1] { 18014398509481984uL });

			public static readonly BitSet _54_in_arguments1081 = new BitSet(new ulong[1] { 2uL });
		}

		internal static readonly string[] tokenNames = new string[76]
		{
			"<invalid>", "<EOR>", "<DOWN>", "<UP>", "A", "AND", "B", "C", "D", "DATETIME",
			"DIGIT", "E", "EXPONENT", "EscapeSequence", "F", "FALSE", "FLOAT", "G", "H", "HexDigit",
			"I", "ID", "INTEGER", "J", "K", "L", "LETTER", "M", "N", "NAME",
			"NOT", "O", "OR", "P", "Q", "R", "S", "STRING", "T", "TRUE",
			"U", "UnicodeEscape", "V", "W", "WS", "X", "Y", "Z", "'!'", "'!='",
			"'%'", "'&&'", "'&'", "'('", "')'", "'*'", "'**'", "'+'", "','", "'-'",
			"'/'", "':'", "'<'", "'<<'", "'<='", "'<>'", "'='", "'=='", "'>'", "'>='",
			"'>>'", "'?'", "'^'", "'|'", "'||'", "'~'"
		};

		public const int EOF = -1;

		public const int A = 4;

		public const int AND = 5;

		public const int B = 6;

		public const int C = 7;

		public const int D = 8;

		public const int DATETIME = 9;

		public const int DIGIT = 10;

		public const int E = 11;

		public const int EXPONENT = 12;

		public const int EscapeSequence = 13;

		public const int F = 14;

		public const int FALSE = 15;

		public const int FLOAT = 16;

		public const int G = 17;

		public const int H = 18;

		public const int HexDigit = 19;

		public const int I = 20;

		public const int ID = 21;

		public const int INTEGER = 22;

		public const int J = 23;

		public const int K = 24;

		public const int L = 25;

		public const int LETTER = 26;

		public const int M = 27;

		public const int N = 28;

		public const int NAME = 29;

		public const int NOT = 30;

		public const int O = 31;

		public const int OR = 32;

		public const int P = 33;

		public const int Q = 34;

		public const int R = 35;

		public const int S = 36;

		public const int STRING = 37;

		public const int T = 38;

		public const int TRUE = 39;

		public const int U = 40;

		public const int UnicodeEscape = 41;

		public const int V = 42;

		public const int W = 43;

		public const int WS = 44;

		public const int X = 45;

		public const int Y = 46;

		public const int Z = 47;

		public const int T__48 = 48;

		public const int T__49 = 49;

		public const int T__50 = 50;

		public const int T__51 = 51;

		public const int T__52 = 52;

		public const int T__53 = 53;

		public const int T__54 = 54;

		public const int T__55 = 55;

		public const int T__56 = 56;

		public const int T__57 = 57;

		public const int T__58 = 58;

		public const int T__59 = 59;

		public const int T__60 = 60;

		public const int T__61 = 61;

		public const int T__62 = 62;

		public const int T__63 = 63;

		public const int T__64 = 64;

		public const int T__65 = 65;

		public const int T__66 = 66;

		public const int T__67 = 67;

		public const int T__68 = 68;

		public const int T__69 = 69;

		public const int T__70 = 70;

		public const int T__71 = 71;

		public const int T__72 = 72;

		public const int T__73 = 73;

		public const int T__74 = 74;

		public const int T__75 = 75;

		private ITreeAdaptor adaptor;

		private const char BS = '\\';

		private static NumberFormatInfo numberFormatInfo = new NumberFormatInfo();

		public ITreeAdaptor TreeAdaptor
		{
			get
			{
				return adaptor;
			}
			set
			{
				adaptor = value;
			}
		}

		public override string[] TokenNames => tokenNames;

		public override string GrammarFileName => "NCalc.g";

		public List<string> Errors { get; private set; }

		public NCalcParser(ITokenStream input)
			: this(input, new RecognizerSharedState())
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_000c: Expected O, but got Unknown


		public NCalcParser(ITokenStream input, RecognizerSharedState state)
			: base(input, state)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			ITreeAdaptor val = null;
			TreeAdaptor = (ITreeAdaptor)(((object)val) ?? ((object)new CommonTreeAdaptor()));
		}

		private string extractString(string text)
		{
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder(text);
			int startIndex = 1;
			int num = -1;
			while ((num = stringBuilder.ToString().IndexOf('\\', startIndex)) != -1)
			{
				char c = stringBuilder[num + 1];
				switch (c)
				{
				case 'u':
				{
					string text2 = string.Concat(stringBuilder[num + 4], stringBuilder[num + 5]);
					string text3 = string.Concat(stringBuilder[num + 2], stringBuilder[num + 3]);
					char c2 = Encoding.Unicode.GetChars(new byte[2]
					{
						Convert.ToByte(text2, 16),
						Convert.ToByte(text3, 16)
					})[0];
					stringBuilder.Remove(num, 6).Insert(num, c2);
					break;
				}
				case 'n':
					stringBuilder.Remove(num, 2).Insert(num, '\n');
					break;
				case 'r':
					stringBuilder.Remove(num, 2).Insert(num, '\r');
					break;
				case 't':
					stringBuilder.Remove(num, 2).Insert(num, '\t');
					break;
				case '\'':
					stringBuilder.Remove(num, 2).Insert(num, '\'');
					break;
				case '\\':
					stringBuilder.Remove(num, 2).Insert(num, '\\');
					break;
				default:
					throw new RecognitionException("Unvalid escape sequence: \\" + c);
				}
				startIndex = num + 1;
			}
			stringBuilder.Remove(0, 1);
			stringBuilder.Remove(stringBuilder.Length - 1, 1);
			return stringBuilder.ToString();
		}

		public override void DisplayRecognitionError(string[] tokenNames, RecognitionException e)
		{
			((BaseRecognizer)this).DisplayRecognitionError(tokenNames, e);
			if (Errors == null)
			{
				Errors = new List<string>();
			}
			string errorHeader = ((BaseRecognizer)this).GetErrorHeader(e);
			string errorMessage = ((BaseRecognizer)this).GetErrorMessage(e, tokenNames);
			Errors.Add(errorMessage + " at " + errorHeader);
		}

		public LogicalExpression GetExpression()
		{
			return ncalcExpression().value;
		}

		[GrammarRule("ncalcExpression")]
		private ncalcExpression_return ncalcExpression()
		{
			//IL_00d0: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_006a: 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_00b0: Expected O, but got Unknown
			ncalcExpression_return ncalcExpression_return = new ncalcExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)ncalcExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			AstParserRuleReturnScope<CommonTree, IToken> val2 = null;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._logicalExpression_in_ncalcExpression73);
					val2 = logicalExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val2.Tree);
					_ = (IToken)((BaseRecognizer)this).Match((IIntStream)(object)base.input, -1, Follow._EOF_in_ncalcExpression75);
					ncalcExpression_return.value = ((val2 != null) ? ((logicalExpression_return)val2).value : null);
					((ParserRuleReturnScope<IToken>)(object)ncalcExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)ncalcExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)ncalcExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)ncalcExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)ncalcExpression_return).Stop);
				}
				catch (RecognitionException val3)
				{
					RecognitionException val4 = val3;
					((BaseRecognizer)this).ReportError(val4);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val4);
					((AstParserRuleReturnScope<CommonTree, IToken>)ncalcExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)ncalcExpression_return).Start, base.input.LT(-1), val4);
				}
				finally
				{
				}
			}
			finally
			{
			}
			return ncalcExpression_return;
		}

		[GrammarRule("logicalExpression")]
		private logicalExpression_return logicalExpression()
		{
			//IL_0202: Expected O, but got Unknown
			//IL_023e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0248: Expected O, but got Unknown
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			//IL_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Expected O, but got Unknown
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Expected O, but got Unknown
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Expected O, but got Unknown
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Expected O, but got Unknown
			logicalExpression_return logicalExpression_return = new logicalExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)logicalExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			IToken val2 = null;
			IToken val3 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val4 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val5 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val6 = null;
			CommonTree val7 = null;
			CommonTree val8 = null;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._conditionalExpression_in_logicalExpression95);
					val4 = conditionalExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val4.Tree);
					logicalExpression_return.value = ((val4 != null) ? ((conditionalExpression_return)val4).value : null);
					int num = 2;
					try
					{
						try
						{
							if (((IIntStream)base.input).LA(1) == 71)
							{
								num = 1;
							}
						}
						finally
						{
						}
						if (num == 1)
						{
							val2 = (IToken)((BaseRecognizer)this).Match((IIntStream)(object)base.input, 71, Follow._71_in_logicalExpression101);
							val7 = (CommonTree)adaptor.Create(val2);
							adaptor.AddChild((object)val, (object)val7);
							((BaseRecognizer)this).PushFollow(Follow._conditionalExpression_in_logicalExpression105);
							val5 = conditionalExpression();
							((BaseRecognizer)this).PopFollow();
							adaptor.AddChild((object)val, (object)val5.Tree);
							val3 = (IToken)((BaseRecognizer)this).Match((IIntStream)(object)base.input, 61, Follow._61_in_logicalExpression107);
							val8 = (CommonTree)adaptor.Create(val3);
							adaptor.AddChild((object)val, (object)val8);
							((BaseRecognizer)this).PushFollow(Follow._conditionalExpression_in_logicalExpression111);
							val6 = conditionalExpression();
							((BaseRecognizer)this).PopFollow();
							adaptor.AddChild((object)val, (object)val6.Tree);
							logicalExpression_return.value = new TernaryExpression((val4 != null) ? ((conditionalExpression_return)val4).value : null, (val5 != null) ? ((conditionalExpression_return)val5).value : null, (val6 != null) ? ((conditionalExpression_return)val6).value : null);
						}
					}
					finally
					{
					}
					((ParserRuleReturnScope<IToken>)(object)logicalExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)logicalExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)logicalExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)logicalExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)logicalExpression_return).Stop);
				}
				catch (RecognitionException val9)
				{
					RecognitionException val10 = val9;
					((BaseRecognizer)this).ReportError(val10);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val10);
					((AstParserRuleReturnScope<CommonTree, IToken>)logicalExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)logicalExpression_return).Start, base.input.LT(-1), val10);
				}
				finally
				{
				}
			}
			finally
			{
			}
			return logicalExpression_return;
		}

		[GrammarRule("conditionalExpression")]
		private conditionalExpression_return conditionalExpression()
		{
			//IL_01ba: Expected O, but got Unknown
			//IL_01f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0200: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Expected O, but got Unknown
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			conditionalExpression_return conditionalExpression_return = new conditionalExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)conditionalExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			IToken val2 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val3 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val4 = null;
			BinaryExpressionType binaryExpressionType = BinaryExpressionType.Unknown;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._booleanAndExpression_in_conditionalExpression138);
					val3 = booleanAndExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val3.Tree);
					conditionalExpression_return.value = ((val3 != null) ? ((booleanAndExpression_return)val3).value : null);
					try
					{
						while (true)
						{
							int num = 2;
							try
							{
								int num2 = ((IIntStream)base.input).LA(1);
								if (num2 == 32 || num2 == 74)
								{
									num = 1;
								}
							}
							finally
							{
							}
							if (num == 1)
							{
								val2 = base.input.LT(1);
								if (((IIntStream)base.input).LA(1) == 32 || ((IIntStream)base.input).LA(1) == 74)
								{
									((IIntStream)base.input).Consume();
									adaptor.AddChild((object)val, (object)(CommonTree)adaptor.Create(val2));
									((BaseRecognizer)this).state.errorRecovery = false;
									binaryExpressionType = BinaryExpressionType.Or;
									((BaseRecognizer)this).PushFollow(Follow._conditionalExpression_in_conditionalExpression163);
									val4 = conditionalExpression();
									((BaseRecognizer)this).PopFollow();
									adaptor.AddChild((object)val, (object)val4.Tree);
									conditionalExpression_return.value = new BinaryExpression(binaryExpressionType, conditionalExpression_return.value, (val4 != null) ? ((conditionalExpression_return)val4).value : null);
									continue;
								}
								throw new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
							}
							break;
						}
					}
					finally
					{
					}
					((ParserRuleReturnScope<IToken>)(object)conditionalExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)conditionalExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)conditionalExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)conditionalExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)conditionalExpression_return).Stop);
				}
				catch (RecognitionException val5)
				{
					RecognitionException val6 = val5;
					((BaseRecognizer)this).ReportError(val6);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val6);
					((AstParserRuleReturnScope<CommonTree, IToken>)conditionalExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)conditionalExpression_return).Start, base.input.LT(-1), val6);
				}
				finally
				{
				}
			}
			finally
			{
			}
			return conditionalExpression_return;
		}

		[GrammarRule("booleanAndExpression")]
		private booleanAndExpression_return booleanAndExpression()
		{
			//IL_01b8: Expected O, but got Unknown
			//IL_01f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: Expected O, but got Unknown
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Expected O, but got Unknown
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			booleanAndExpression_return booleanAndExpression_return = new booleanAndExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)booleanAndExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			IToken val2 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val3 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val4 = null;
			BinaryExpressionType binaryExpressionType = BinaryExpressionType.Unknown;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._bitwiseOrExpression_in_booleanAndExpression197);
					val3 = bitwiseOrExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val3.Tree);
					booleanAndExpression_return.value = ((val3 != null) ? ((bitwiseOrExpression_return)val3).value : null);
					try
					{
						while (true)
						{
							int num = 2;
							try
							{
								int num2 = ((IIntStream)base.input).LA(1);
								if (num2 == 5 || num2 == 51)
								{
									num = 1;
								}
							}
							finally
							{
							}
							if (num == 1)
							{
								val2 = base.input.LT(1);
								if (((IIntStream)base.input).LA(1) == 5 || ((IIntStream)base.input).LA(1) == 51)
								{
									((IIntStream)base.input).Consume();
									adaptor.AddChild((object)val, (object)(CommonTree)adaptor.Create(val2));
									((BaseRecognizer)this).state.errorRecovery = false;
									binaryExpressionType = BinaryExpressionType.And;
									((BaseRecognizer)this).PushFollow(Follow._bitwiseOrExpression_in_booleanAndExpression222);
									val4 = bitwiseOrExpression();
									((BaseRecognizer)this).PopFollow();
									adaptor.AddChild((object)val, (object)val4.Tree);
									booleanAndExpression_return.value = new BinaryExpression(binaryExpressionType, booleanAndExpression_return.value, (val4 != null) ? ((bitwiseOrExpression_return)val4).value : null);
									continue;
								}
								throw new MismatchedSetException((BitSet)null, (IIntStream)(object)base.input);
							}
							break;
						}
					}
					finally
					{
					}
					((ParserRuleReturnScope<IToken>)(object)booleanAndExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)booleanAndExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)booleanAndExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)booleanAndExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)booleanAndExpression_return).Stop);
				}
				catch (RecognitionException val5)
				{
					RecognitionException val6 = val5;
					((BaseRecognizer)this).ReportError(val6);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val6);
					((AstParserRuleReturnScope<CommonTree, IToken>)booleanAndExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)booleanAndExpression_return).Start, base.input.LT(-1), val6);
				}
				finally
				{
				}
			}
			finally
			{
			}
			return booleanAndExpression_return;
		}

		[GrammarRule("bitwiseOrExpression")]
		private bitwiseOrExpression_return bitwiseOrExpression()
		{
			//IL_017e: Expected O, but got Unknown
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			bitwiseOrExpression_return bitwiseOrExpression_return = new bitwiseOrExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)bitwiseOrExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			IToken val2 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val3 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val4 = null;
			CommonTree val5 = null;
			BinaryExpressionType binaryExpressionType = BinaryExpressionType.Unknown;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._bitwiseXOrExpression_in_bitwiseOrExpression254);
					val3 = bitwiseXOrExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val3.Tree);
					bitwiseOrExpression_return.value = ((val3 != null) ? ((bitwiseXOrExpression_return)val3).value : null);
					try
					{
						while (true)
						{
							int num = 2;
							try
							{
								if (((IIntStream)base.input).LA(1) == 73)
								{
									num = 1;
								}
							}
							finally
							{
							}
							if (num == 1)
							{
								val2 = (IToken)((BaseRecognizer)this).Match((IIntStream)(object)base.input, 73, Follow._73_in_bitwiseOrExpression263);
								val5 = (CommonTree)adaptor.Create(val2);
								adaptor.AddChild((object)val, (object)val5);
								binaryExpressionType = BinaryExpressionType.BitwiseOr;
								((BaseRecognizer)this).PushFollow(Follow._bitwiseOrExpression_in_bitwiseOrExpression273);
								val4 = bitwiseOrExpression();
								((BaseRecognizer)this).PopFollow();
								adaptor.AddChild((object)val, (object)val4.Tree);
								bitwiseOrExpression_return.value = new BinaryExpression(binaryExpressionType, bitwiseOrExpression_return.value, (val4 != null) ? ((bitwiseOrExpression_return)val4).value : null);
								continue;
							}
							break;
						}
					}
					finally
					{
					}
					((ParserRuleReturnScope<IToken>)(object)bitwiseOrExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseOrExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseOrExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)bitwiseOrExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)bitwiseOrExpression_return).Stop);
				}
				catch (RecognitionException val6)
				{
					RecognitionException val7 = val6;
					((BaseRecognizer)this).ReportError(val7);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val7);
					((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseOrExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)bitwiseOrExpression_return).Start, base.input.LT(-1), val7);
				}
				finally
				{
				}
			}
			finally
			{
			}
			return bitwiseOrExpression_return;
		}

		[GrammarRule("bitwiseXOrExpression")]
		private bitwiseXOrExpression_return bitwiseXOrExpression()
		{
			//IL_017e: Expected O, but got Unknown
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c4: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_015d: Expected O, but got Unknown
			bitwiseXOrExpression_return bitwiseXOrExpression_return = new bitwiseXOrExpression_return(this);
			((ParserRuleReturnScope<IToken>)(object)bitwiseXOrExpression_return).Start = base.input.LT(1);
			CommonTree val = null;
			IToken val2 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val3 = null;
			AstParserRuleReturnScope<CommonTree, IToken> val4 = null;
			CommonTree val5 = null;
			BinaryExpressionType binaryExpressionType = BinaryExpressionType.Unknown;
			try
			{
				try
				{
					val = (CommonTree)adaptor.Nil();
					((BaseRecognizer)this).PushFollow(Follow._bitwiseAndExpression_in_bitwiseXOrExpression307);
					val3 = bitwiseAndExpression();
					((BaseRecognizer)this).PopFollow();
					adaptor.AddChild((object)val, (object)val3.Tree);
					bitwiseXOrExpression_return.value = ((val3 != null) ? ((bitwiseAndExpression_return)val3).value : null);
					try
					{
						while (true)
						{
							int num = 2;
							try
							{
								if (((IIntStream)base.input).LA(1) == 72)
								{
									num = 1;
								}
							}
							finally
							{
							}
							if (num == 1)
							{
								val2 = (IToken)((BaseRecognizer)this).Match((IIntStream)(object)base.input, 72, Follow._72_in_bitwiseXOrExpression316);
								val5 = (CommonTree)adaptor.Create(val2);
								adaptor.AddChild((object)val, (object)val5);
								binaryExpressionType = BinaryExpressionType.BitwiseXOr;
								((BaseRecognizer)this).PushFollow(Follow._bitwiseAndExpression_in_bitwiseXOrExpression326);
								val4 = bitwiseAndExpression();
								((BaseRecognizer)this).PopFollow();
								adaptor.AddChild((object)val, (object)val4.Tree);
								bitwiseXOrExpression_return.value = new BinaryExpression(binaryExpressionType, bitwiseXOrExpression_return.value, (val4 != null) ? ((bitwiseAndExpression_return)val4).value : null);
								continue;
							}
							break;
						}
					}
					finally
					{
					}
					((ParserRuleReturnScope<IToken>)(object)bitwiseXOrExpression_return).Stop = base.input.LT(-1);
					((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseXOrExpression_return).Tree = (CommonTree)adaptor.RulePostProcessing((object)val);
					adaptor.SetTokenBoundaries((object)((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseXOrExpression_return).Tree, ((ParserRuleReturnScope<IToken>)(object)bitwiseXOrExpression_return).Start, ((ParserRuleReturnScope<IToken>)(object)bitwiseXOrExpression_return).Stop);
				}
				catch (RecognitionException val6)
				{
					RecognitionException val7 = val6;
					((BaseRecognizer)this).ReportError(val7);
					((BaseRecognizer)this).Recover((IIntStream)(object)base.input, val7);
					((AstParserRuleReturnScope<CommonTree, IToken>)bitwiseXOrExpression_return).Tree = (CommonTree)adaptor.ErrorNode(base.input, ((ParserRuleReturnScope<IToken>)(object)bit

plugins/Libs/PanoramicData.NCalcExtensions.dll

Decompiled 4 months ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using NCalc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PanoramicData.NCalcExtensions.Exceptions;
using PanoramicData.NCalcExtensions.Extensions;
using PanoramicData.NCalcExtensions.Helpers;
using TimeZoneConverter;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("1.20.127.34203")]
[assembly: AssemblyInformationalVersion("1.20.127+859b0ed46e")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Panoramic Data Limited")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Panoramic Data Limited 2019-2023")]
[assembly: AssemblyDescription("Extensions for NCalc")]
[assembly: AssemblyProduct("PanoramicData.NCalcExtensions")]
[assembly: AssemblyTitle("PanoramicData.NCalcExtensions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/panoramicdata/PanoramicData.NCalcExtensions")]
[assembly: InternalsVisibleTo("PanoramicData.NCalcExtensions.Test")]
[assembly: AssemblyVersion("1.20.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.5.119.9565")]
[ExcludeFromCodeCoverage]
internal static class ThisAssembly
{
	internal const string AssemblyConfiguration = "Release";

	internal const string AssemblyFileVersion = "1.20.127.34203";

	internal const string AssemblyInformationalVersion = "1.20.127+859b0ed46e";

	internal const string AssemblyName = "PanoramicData.NCalcExtensions";

	internal const string AssemblyTitle = "PanoramicData.NCalcExtensions";

	internal const string AssemblyVersion = "1.20.0.0";

	internal static readonly DateTime GitCommitDate = new DateTime(638332475000000000L, DateTimeKind.Utc);

	internal const string GitCommitId = "859b0ed46eb79975f879772d7edd6b08e2ec9a3c";

	internal const bool IsPrerelease = false;

	internal const bool IsPublicRelease = true;

	internal const string RootNamespace = "PanoramicData.NCalcExtensions";
}
namespace PanoramicData.NCalcExtensions
{
	public class ExtendedExpression : Expression
	{
		private readonly Dictionary<string, object?> _storageDictionary = new Dictionary<string, object>();

		internal const string StorageDictionaryParameterName = "__storageDictionary";

		public ExtendedExpression(string expression)
			: base(expression)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			((Expression)this).Parameters["__storageDictionary"] = _storageDictionary;
			((Expression)this).EvaluateFunction += new EvaluateFunctionHandler(Extend);
			Expression.CacheEnabled = false;
			if (((Expression)this).Parameters.ContainsKey("null"))
			{
				throw new InvalidOperationException("You may not set a parameter called 'null', as it is a reserved keyword.");
			}
			((Expression)this).Parameters["null"] = null;
			if (((Expression)this).Parameters.ContainsKey("True"))
			{
				throw new InvalidOperationException("You may not set a parameter called 'True', as it is a reserved keyword.");
			}
			((Expression)this).Parameters["True"] = true;
			if (((Expression)this).Parameters.ContainsKey("False"))
			{
				throw new InvalidOperationException("You may not set a parameter called 'False', as it is a reserved keyword.");
			}
			((Expression)this).Parameters["False"] = false;
		}

		internal static void CheckParameterCount(string functionName, FunctionArgs functionArgs, int? minPropertyCount, int? maxPropertyCount)
		{
			if (minPropertyCount.HasValue && functionArgs.Parameters.Length < minPropertyCount)
			{
				throw new FormatException(string.Format("{0}: At least {1} parameter{2} required.", functionName, minPropertyCount, (minPropertyCount == 1) ? "" : "s"));
			}
			if (maxPropertyCount.HasValue && functionArgs.Parameters.Length > maxPropertyCount)
			{
				throw new FormatException(string.Format("{0}: No more than {1} parameter{2} permitted.", functionName, maxPropertyCount, (maxPropertyCount == 1) ? "" : "s"));
			}
		}

		internal void Extend(string functionName, FunctionArgs functionArgs)
		{
			if (functionArgs == null)
			{
				throw new ArgumentNullException("functionArgs");
			}
			if (functionName == null)
			{
				return;
			}
			switch (functionName.Length)
			{
			case 3:
				switch (functionName[1])
				{
				case 'l':
					if (functionName == "all")
					{
						All.Evaluate(functionArgs);
					}
					break;
				case 'n':
					if (functionName == "any")
					{
						Any.Evaluate(functionArgs);
					}
					break;
				case 'a':
					if (functionName == "max")
					{
						Max.Evaluate(functionArgs);
					}
					break;
				case 'i':
					if (functionName == "min")
					{
						Min.Evaluate(functionArgs);
					}
					break;
				case 'u':
					if (functionName == "sum")
					{
						Sum.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "try")
					{
						Try.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 11:
				switch (functionName[0])
				{
				case 'c':
					if (functionName == "canEvaluate")
					{
						CanEvaluate.Evaluate(functionArgs);
					}
					break;
				case 'g':
					if (functionName == "getProperty")
					{
						GetProperty.Evaluate(functionArgs);
					}
					break;
				case 'i':
					if (functionName == "itemAtIndex")
					{
						ItemAtIndex.Evaluate(functionArgs);
					}
					break;
				case 'l':
					if (functionName == "lastIndexOf")
					{
						LastIndexOf.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 10:
				switch (functionName[0])
				{
				case 'c':
					if (functionName == "capitalise" || functionName == "capitalize")
					{
						Capitalize.Evaluate(functionArgs);
					}
					break;
				case 'd':
					if (functionName == "dictionary")
					{
						Dictionary.Evaluate(functionArgs);
					}
					break;
				case 'i':
					if (functionName == "isInfinite")
					{
						IsInfinite.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "regexGroup")
					{
						RegexGroup.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (functionName == "startsWith")
					{
						StartsWith.Evaluate(functionArgs);
					}
					break;
				case 't':
					if (functionName == "toDateTime")
					{
						ToDateTime.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 4:
				switch (functionName[0])
				{
				case 'c':
					if (functionName == "cast")
					{
						Cast.Evaluate(functionArgs);
					}
					break;
				case 'j':
					if (functionName == "join")
					{
						Join.Evaluate(functionArgs);
					}
					break;
				case 'l':
					if (functionName == "list")
					{
						List.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (!(functionName == "skip"))
					{
						if (functionName == "sort")
						{
							Sort.Evaluate(functionArgs);
						}
					}
					else
					{
						Skip.Evaluate(functionArgs);
					}
					break;
				case 't':
					if (functionName == "take")
					{
						Take.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 14:
				switch (functionName[0])
				{
				case 'c':
					if (functionName == "changeTimeZone")
					{
						ChangeTimeZone.Evaluate(functionArgs);
					}
					break;
				case 'f':
					if (functionName == "firstOrDefault")
					{
						FirstOrDefault.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (functionName == "selectDistinct")
					{
						SelectDistinct.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 6:
				switch (functionName[2])
				{
				case 'n':
					if (!(functionName == "concat"))
					{
						if (functionName == "length")
						{
							Length.Evaluate(functionArgs);
						}
					}
					else
					{
						Concat.Evaluate(functionArgs);
					}
					break;
				case 't':
					if (functionName == "extend")
					{
						ExtendObject.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "format")
					{
						Format.Evaluate(functionArgs);
					}
					break;
				case 'G':
					if (functionName == "isGuid")
					{
						IsGuid.Evaluate(functionArgs);
					}
					break;
				case 'N':
					if (functionName == "isNull")
					{
						IsNull.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (functionName == "listOf")
					{
						ListOf.Evaluate(functionArgs);
					}
					break;
				case 'l':
					if (functionName == "select")
					{
						Select.Evaluate(functionArgs);
					}
					break;
				case 'i':
					if (functionName == "switch")
					{
						PanoramicData.NCalcExtensions.Extensions.Switch.Evaluate(functionArgs);
					}
					break;
				case 'p':
					if (functionName == "typeOf")
					{
						TypeOf.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 8:
				switch (functionName[2])
				{
				case 'n':
					if (!(functionName == "contains"))
					{
						if (functionName == "minValue")
						{
							MinValue.Evaluate(functionArgs);
						}
					}
					else
					{
						Contains.Evaluate(functionArgs);
					}
					break;
				case 't':
					if (!(functionName == "dateTime"))
					{
						if (functionName == "retrieve")
						{
							Retrieve.Evaluate(functionArgs);
						}
					}
					else
					{
						DateTimeMethods.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (functionName == "distinct")
					{
						Distinct.Evaluate(functionArgs);
					}
					break;
				case 'd':
					if (functionName == "endsWith")
					{
						EndsWith.Evaluate(functionArgs);
					}
					break;
				case 'm':
					switch (functionName)
					{
					case "humanise":
					case "humanize":
						Humanize.Evaluate(functionArgs);
						break;
					case "timespan":
					case "timeSpan":
						PanoramicData.NCalcExtensions.Extensions.TimeSpan.Evaluate(functionArgs);
						break;
					}
					break;
				case 'x':
					if (functionName == "maxValue")
					{
						MaxValue.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "parseInt")
					{
						ParseInt.Evaluate(functionArgs);
					}
					break;
				case 'S':
					if (functionName == "toString")
					{
						ToString.Evaluate(functionArgs);
					}
					break;
				case 'y':
					if (functionName == "tryParse")
					{
						TryParse.Evaluate(functionArgs, _storageDictionary);
					}
					break;
				}
				break;
			case 7:
				switch (functionName[0])
				{
				case 'c':
					if (functionName == "convert")
					{
						ConvertFunction.Evaluate(functionArgs);
					}
					break;
				case 'i':
					if (functionName == "indexOf")
					{
						IndexOf.Evaluate(functionArgs);
					}
					break;
				case 'j':
					if (functionName == "jObject")
					{
						NewJObject.Evaluate(functionArgs);
					}
					break;
				case 'o':
					if (functionName == "orderBy")
					{
						OrderBy.Evaluate(functionArgs);
					}
					break;
				case 'p':
					if (functionName == "padLeft")
					{
						PadLeft.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "replace")
					{
						Replace.Evaluate(functionArgs);
					}
					break;
				case 't':
					if (!(functionName == "toLower"))
					{
						if (functionName == "toUpper")
						{
							ToUpper.Evaluate(functionArgs);
						}
					}
					else
					{
						ToLower.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 5:
				switch (functionName[2])
				{
				case 'u':
					if (functionName == "count")
					{
						Count.Evaluate(functionArgs);
					}
					break;
				case 'r':
					switch (functionName)
					{
					case "first":
						First.Evaluate(functionArgs);
						break;
					case "parse":
						Parse.Evaluate(functionArgs);
						break;
					case "throw":
						throw Throw.Evaluate(functionArgs);
					}
					break;
				case 'N':
					if (functionName == "isNaN")
					{
						IsNaN.Evaluate(functionArgs);
					}
					break;
				case 'S':
					if (functionName == "isSet")
					{
						IsSet.Evaluate(functionArgs);
					}
					break;
				case 'a':
					if (functionName == "jPath")
					{
						JPath.Evaluate(functionArgs);
					}
					break;
				case 'l':
					if (functionName == "split")
					{
						Split.Evaluate(functionArgs);
					}
					break;
				case 'o':
					if (functionName == "store")
					{
						Store.Evaluate(functionArgs);
					}
					break;
				case 'e':
					if (functionName == "where")
					{
						Where.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 2:
				switch (functionName[1])
				{
				case 'n':
					if (functionName == "in")
					{
						In.Evaluate(functionArgs);
					}
					break;
				case 'f':
					if (functionName == "if")
					{
						If.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 13:
				switch (functionName[0])
				{
				case 'i':
					if (functionName == "isNullOrEmpty")
					{
						IsNullOrEmpty.Evaluate(functionArgs);
					}
					break;
				case 's':
					if (functionName == "setProperties")
					{
						SetProperties.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 12:
				switch (functionName[0])
				{
				case 'n':
					if (functionName == "nullCoalesce")
					{
						NullCoalesce.Evaluate(functionArgs);
					}
					break;
				case 'r':
					if (functionName == "regexIsMatch")
					{
						RegexIsMatch.Evaluate(functionArgs);
					}
					break;
				}
				break;
			case 17:
				if (functionName == "dateTimeAsEpochMs")
				{
					DateTimeAsEpochMs.Evaluate(functionArgs);
				}
				break;
			case 18:
				if (functionName == "isNullOrWhiteSpace")
				{
					IsNullOrWhiteSpace.Evaluate(functionArgs);
				}
				break;
			case 9:
				if (functionName == "substring")
				{
					Substring.Evaluate(functionArgs);
				}
				break;
			case 15:
			case 16:
				break;
			}
		}
	}
	public static class ExtensionFunction
	{
		public const string All = "all";

		public const string Any = "any";

		public const string CanEvaluate = "canEvaluate";

		public const string Capitalise = "capitalise";

		public const string Capitalize = "capitalize";

		public const string Cast = "cast";

		public const string ChangeTimeZone = "changeTimeZone";

		public const string Concat = "concat";

		public const string Contains = "contains";

		public const string Convert = "convert";

		public const string Count = "count";

		public const string DateTime = "dateTime";

		public const string DateTimeAsEpochMs = "dateTimeAsEpochMs";

		public const string Dictionary = "dictionary";

		public const string Distinct = "distinct";

		public const string EndsWith = "endsWith";

		public const string Extend = "extend";

		public const string First = "first";

		public const string FirstOrDefault = "firstOrDefault";

		public const string Format = "format";

		public const string GetProperty = "getProperty";

		public const string Humanise = "humanise";

		public const string Humanize = "humanize";

		public const string If = "if";

		public const string In = "in";

		public const string IndexOf = "indexOf";

		public const string IsGuid = "isGuid";

		public const string IsInfinite = "isInfinite";

		public const string IsNaN = "isNaN";

		public const string IsNull = "isNull";

		public const string IsNullOrWhiteSpace = "isNullOrWhiteSpace";

		public const string IsNullOrEmpty = "isNullOrEmpty";

		public const string IsSet = "isSet";

		public const string ItemAtIndex = "itemAtIndex";

		public const string Join = "join";

		public const string JPath = "jPath";

		public const string LastIndexOf = "lastIndexOf";

		public const string Length = "length";

		public const string List = "list";

		public const string ListOf = "listOf";

		public const string Max = "max";

		public const string MaxValue = "maxValue";

		public const string Min = "min";

		public const string MinValue = "minValue";

		public const string NewJObject = "jObject";

		public const string NullCoalesce = "nullCoalesce";

		public const string OrderBy = "orderBy";

		public const string PadLeft = "padLeft";

		public const string Parse = "parse";

		public const string ParseInt = "parseInt";

		public const string RegexGroup = "regexGroup";

		public const string RegexIsMatch = "regexIsMatch";

		public const string Replace = "replace";

		public const string Retrieve = "retrieve";

		public const string Select = "select";

		public const string SelectDistinct = "selectDistinct";

		public const string SetProperties = "setProperties";

		public const string Skip = "skip";

		public const string Sort = "sort";

		public const string Split = "split";

		public const string StartsWith = "startsWith";

		public const string Store = "store";

		public const string Substring = "substring";

		public const string Sum = "sum";

		public const string Switch = "switch";

		public const string Take = "take";

		public const string Throw = "throw";

		public const string TimeSpan = "timespan";

		public const string TimeSpanCamel = "timeSpan";

		public const string ToDateTime = "toDateTime";

		public const string ToLower = "toLower";

		public new const string ToString = "toString";

		public const string ToUpper = "toUpper";

		public const string Try = "try";

		public const string TryParse = "tryParse";

		public const string TypeOf = "typeOf";

		public const string Where = "where";
	}
	public class Lambda
	{
		private readonly string predicate;

		private readonly string nCalcString;

		private readonly Dictionary<string, object?> parameters;

		public Lambda(string predicate, string nCalcString, Dictionary<string, object?> parameters)
		{
			this.predicate = predicate;
			this.nCalcString = nCalcString;
			this.parameters = parameters;
		}

		public object? Evaluate<T>(T value)
		{
			parameters.Remove(predicate);
			parameters.Add(predicate, value);
			ExtendedExpression extendedExpression = new ExtendedExpression(nCalcString);
			((Expression)extendedExpression).Parameters = parameters;
			ExtendedExpression extendedExpression2 = extendedExpression;
			return ((Expression)extendedExpression2).Evaluate();
		}
	}
	public static class NCalcExtensions
	{
	}
	public enum TimeUnit
	{
		Milliseconds,
		Seconds,
		Minutes,
		Hours,
		Days,
		Weeks,
		Years
	}
}
namespace PanoramicData.NCalcExtensions.Helpers
{
	internal static class StringExtensions
	{
		internal static string UpperCaseFirst(this string s)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			return s.Substring(0, 1).ToUpperInvariant() + s.Substring(1);
		}
	}
	internal static class TimeSpanExtensions
	{
		internal static string Humanise(this System.TimeSpan t)
		{
			string text = ((t.Days >= 1) ? string.Format("{0} day{1}", t.Days, (t.Days > 1) ? "s" : "") : "");
			if (t.Hours >= 1)
			{
				text += string.Format(" {0} hour{1}", t.Hours, (t.Hours > 1) ? "s" : "");
			}
			if (t.Minutes >= 1)
			{
				text += string.Format(" {0} minute{1}", t.Minutes, (t.Minutes > 1) ? "s" : "");
			}
			if (t.Seconds >= 1)
			{
				text += string.Format(" {0} second{1}", t.Seconds, (t.Seconds > 1) ? "s" : "");
			}
			return text.Trim();
		}
	}
	internal static class TypeHelper
	{
		internal static string AsHumanString<T>()
		{
			if (typeof(T).IsGenericType)
			{
				return typeof(T).GetGenericTypeDefinition().Name + "<" + string.Join(",", from t in typeof(T).GetGenericArguments()
					select t.Name) + ">";
			}
			return typeof(T).Name;
		}
	}
}
namespace PanoramicData.NCalcExtensions.Extensions
{
	internal static class All
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IEnumerable<object> source = (functionArgs.Parameters[0].Evaluate() as IEnumerable<object>) ?? throw new FormatException("First all parameter must be an IEnumerable.");
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second all parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third all parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			functionArgs.Result = source.All((object value) => lambda.Evaluate(value) as bool? == true);
		}
	}
	internal static class Any
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IEnumerable<object> source = (functionArgs.Parameters[0].Evaluate() as IEnumerable<object>) ?? throw new FormatException("First any parameter must be an IEnumerable.");
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second any parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third any parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			functionArgs.Result = source.Any((object value) => lambda.Evaluate(value) as bool? == true);
		}
	}
	internal static class CanEvaluate
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				Expression[] parameters = functionArgs.Parameters;
				foreach (Expression val in parameters)
				{
					val.Evaluate();
				}
				functionArgs.Result = true;
			}
			catch
			{
				functionArgs.Result = false;
			}
		}
	}
	internal static class Capitalize
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			string text;
			try
			{
				text = (string)functionArgs.Parameters[0].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("capitalize function -  requires one string parameter.");
			}
			functionArgs.Result = text.ToLowerInvariant().UpperCaseFirst();
		}
	}
	internal static class Cast
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 2)
			{
				throw new ArgumentException(string.Format("{0} function - Expected {1} arguments", "cast", 2));
			}
			object value = functionArgs.Parameters[0].Evaluate();
			if (!(functionArgs.Parameters[1].Evaluate() is string typeName))
			{
				throw new ArgumentException("cast function - Expected second argument to be a string.");
			}
			Type conversionType = Type.GetType(typeName) ?? throw new ArgumentException("cast function - Expected second argument to be a valid .NET type e.g. System.Decimal.");
			object result = Convert.ChangeType(value, conversionType, CultureInfo.InvariantCulture);
			functionArgs.Result = result;
		}
	}
	internal static class ChangeTimeZone
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 3)
			{
				throw new ArgumentException("changeTimeZone function - Expected 3 arguments");
			}
			DateTime parsedDateTime = (functionArgs.Parameters[0].Evaluate() as DateTime?) ?? throw new ArgumentException("changeTimeZone function - parameter 1 should be a DateTime");
			string sourceTimeZoneName = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new ArgumentException("changeTimeZone function - parameter 2 should be a string");
			string destinationTimeZoneName = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new ArgumentException("changeTimeZone function - parameter 3 should be a string");
			functionArgs.Result = ToDateTime.ConvertTimeZone(parsedDateTime, sourceTimeZoneName, destinationTimeZoneName);
		}
	}
	internal static class Concat
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			List<object> list = new List<object>();
			Expression[] parameters = functionArgs.Parameters;
			foreach (Expression val in parameters)
			{
				object obj = val.Evaluate();
				if (obj is IList list2)
				{
					foreach (object item in list2)
					{
						list.Add(item);
					}
				}
				else
				{
					list.Add(obj);
				}
			}
			functionArgs.Result = list;
		}
	}
	internal static class Contains
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string text = (string)functionArgs.Parameters[0].Evaluate();
				string value = (string)functionArgs.Parameters[1].Evaluate();
				functionArgs.Result = text.IndexOf(value, StringComparison.InvariantCulture) >= 0;
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("contains() requires two string parameters.");
			}
		}
	}
	internal static class ConvertFunction
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 2)
			{
				throw new FormatException("convert() requires two parameters.");
			}
			object value = functionArgs.Parameters[0].Evaluate();
			functionArgs.Parameters[1].Parameters["value"] = value;
			functionArgs.Result = functionArgs.Parameters[1].Evaluate();
		}
	}
	internal static class Count
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			IEnumerable<object> enumerable = obj as IEnumerable<object>;
			if (functionArgs.Parameters.Length == 1)
			{
				if (obj is string text)
				{
					functionArgs.Result = text.Length;
					return;
				}
				if (enumerable == null)
				{
					throw new FormatException("count() requires IEnumerable parameter.");
				}
				functionArgs.Result = enumerable.Count();
				return;
			}
			if (enumerable == null)
			{
				throw new FormatException("count() requires IEnumerable parameter.");
			}
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second count parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third count parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			functionArgs.Result = enumerable.Count((object value) => lambda.Evaluate(value) as bool? == true);
		}
	}
	internal static class DateTimeAsEpochMs
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			functionArgs.Result = DateTimeOffset.ParseExact(functionArgs.Parameters[0].Evaluate() as string, functionArgs.Parameters[1].Evaluate() as string, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal).ToUnixTimeMilliseconds();
		}
	}
	internal static class DateTimeMethods
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 0)
			{
				if (!(functionArgs.Parameters[0].Evaluate() is string text))
				{
					throw new FormatException("dateTime function - The first argument should be a string, e.g. 'UTC'");
				}
				if (text != "UTC")
				{
					throw new FormatException("dateTime function - Only UTC timeZone is currently supported.");
				}
			}
			string text2 = ((functionArgs.Parameters.Length > 1) ? (functionArgs.Parameters[1].Evaluate() as string) : "yyyy-MM-dd HH:mm:ss");
			double days = 0.0;
			if (functionArgs.Parameters.Length > 2)
			{
				double? nullableDouble = GetNullableDouble(functionArgs.Parameters[2]);
				if (!nullableDouble.HasValue)
				{
					throw new FormatException("dateTime function - Days to add must be a number.");
				}
				days = nullableDouble.Value;
			}
			double hours = 0.0;
			if (functionArgs.Parameters.Length > 3)
			{
				double? nullableDouble2 = GetNullableDouble(functionArgs.Parameters[3]);
				if (!nullableDouble2.HasValue)
				{
					throw new FormatException("dateTime function - Hours to add must be a number.");
				}
				hours = nullableDouble2.Value;
			}
			double minutes = 0.0;
			if (functionArgs.Parameters.Length > 4)
			{
				double? nullableDouble3 = GetNullableDouble(functionArgs.Parameters[4]);
				if (!nullableDouble3.HasValue)
				{
					throw new FormatException("dateTime function - Minutes to add must be a number.");
				}
				minutes = nullableDouble3.Value;
			}
			double seconds = 0.0;
			if (functionArgs.Parameters.Length > 5)
			{
				double? nullableDouble4 = GetNullableDouble(functionArgs.Parameters[5]);
				if (!nullableDouble4.HasValue)
				{
					throw new FormatException("dateTime function - Seconds to add must be a number.");
				}
				seconds = nullableDouble4.Value;
			}
			functionArgs.Result = DateTimeOffset.UtcNow.AddDays(days).AddHours(hours).AddMinutes(minutes)
				.AddSeconds(seconds)
				.ToString(text2, CultureInfo.InvariantCulture);
		}

		private static double? GetNullableDouble(Expression expression)
		{
			object obj = expression.Evaluate();
			if (!(obj is double value))
			{
				if (obj is int num)
				{
					return num;
				}
				return null;
			}
			return value;
		}

		internal static string BetterToString(this DateTime dateTime, string format)
		{
			return format switch
			{
				"dayOfYear" => dateTime.DayOfYear.ToString(), 
				"weekOfMonth" => dateTime.WeekOfMonth().ToString(), 
				"weekOfMonthText" => GetWeekText(dateTime.WeekOfMonth()), 
				"weekDayOfMonth" => dateTime.WeekDayOfMonth().ToString(), 
				"weekDayOfMonthText" => GetWeekText(dateTime.WeekDayOfMonth()), 
				_ => dateTime.ToString(format, CultureInfo.InvariantCulture), 
			};
		}

		private static string GetWeekText(int weekOfMonth)
		{
			return weekOfMonth switch
			{
				1 => "first", 
				2 => "second", 
				3 => "third", 
				4 => "fourth", 
				_ => "last", 
			};
		}

		public static int WeekOfMonth(this DateTime dateTime)
		{
			DateTime date = dateTime.Date;
			DateTime dateTime2 = new DateTime(date.Year, date.Month, 1);
			return (date - dateTime2.AddDays(0 - dateTime2.DayOfWeek)).Days / 7 + 1;
		}

		public static int WeekDayOfMonth(this DateTime dateTime)
		{
			return (dateTime.Day - 1) / 7 + 1;
		}

		internal static string ToDateTimeInTargetTimeZone(this DateTime dateTime, string formatFormat, string timeZoneString)
		{
			TimeZoneInfo timeZoneInfo = TZConvert.GetTimeZoneInfo(timeZoneString);
			return new DateTimeOffset(dateTime, -timeZoneInfo.GetUtcOffset(dateTime)).UtcDateTime.BetterToString(formatFormat);
		}
	}
	internal static class Dictionary
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			ExtendedExpression.CheckParameterCount("dictionary", functionArgs, 2, 2147483646);
			if (functionArgs.Parameters.Length % 2 != 0)
			{
				throw new FormatException("dictionary: An even number of parameters must be provided.");
			}
			string key = null;
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			for (int i = 0; i < functionArgs.Parameters.Length; i++)
			{
				object obj = functionArgs.Parameters[i].Evaluate();
				if (i % 2 == 0)
				{
					if (!(obj is string))
					{
						throw new FormatException(string.Format("{0}: parameter {1} must be a string.", "dictionary", i));
					}
					key = (string)obj;
				}
				else
				{
					dictionary[key] = obj;
				}
			}
			functionArgs.Result = dictionary;
		}
	}
	internal static class Distinct
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IEnumerable<object> source = (functionArgs.Parameters[0].Evaluate() as IEnumerable<object>) ?? throw new FormatException("First distinct parameter must be an IEnumerable.");
			functionArgs.Result = source.Distinct().ToList();
		}
	}
	internal static class EndsWith
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string text = (string)functionArgs.Parameters[0].Evaluate();
				string value = (string)functionArgs.Parameters[1].Evaluate();
				functionArgs.Result = text.EndsWith(value, StringComparison.InvariantCulture);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("endsWith function requires two string parameters.");
			}
		}
	}
	internal static class ExtendObject
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			var (obj2, list2) = Parameters.GetParameters<object, List<object>>(functionArgs, "Evaluate");
			if (list2.Count % 2 != 0)
			{
				throw new FormatException("Extension object list must have an even number of parameters, in the form string propertyName1, object value1, propertyName2, object value2, ...");
			}
			JObject val = JObject.FromObject(obj2);
			for (int i = 0; i < list2.Count; i += 2)
			{
				string text = (list2[i] as string) ?? throw new FormatException("Property name must be a string");
				object obj3 = list2[i + 1];
				val[text] = JToken.FromObject(obj3);
			}
			functionArgs.Result = val;
		}
	}
	internal static class First
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IList list = (functionArgs.Parameters[0].Evaluate() as IList) ?? throw new FormatException("First first parameter must be an IEnumerable.");
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second first parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third first parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			foreach (object item in list)
			{
				if (lambda.Evaluate(item) as bool? == true)
				{
					functionArgs.Result = item;
					return;
				}
			}
			throw new FormatException("No matching element found.");
		}
	}
	internal static class FirstOrDefault
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IList list = (functionArgs.Parameters[0].Evaluate() as IList) ?? throw new FormatException("First firstOrDefault parameter must be an IEnumerable.");
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second firstOrDefault parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third firstOrDefault parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			foreach (object item in list)
			{
				if (lambda.Evaluate(item) as bool? == true)
				{
					functionArgs.Result = item;
					return;
				}
			}
			functionArgs.Result = null;
		}
	}
	internal static class Format
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length < 2 || functionArgs.Parameters.Length > 3)
			{
				throw new ArgumentException(string.Format("{0} function - expected between {1} and {2} arguments", "format", 2, 3));
			}
			object obj = functionArgs.Parameters[0].Evaluate();
			if (!(functionArgs.Parameters[1].Evaluate() is string text))
			{
				throw new ArgumentException("format function - expected second argument to be a format string");
			}
			int num = functionArgs.Parameters.Length;
			object result;
			if (obj is int num2)
			{
				if (num != 2)
				{
					goto IL_013f;
				}
				result = num2.ToString(text, CultureInfo.InvariantCulture);
			}
			else if (obj is double num3)
			{
				if (num != 2)
				{
					goto IL_013f;
				}
				result = num3.ToString(text, CultureInfo.InvariantCulture);
			}
			else if (obj is DateTime dateTime)
			{
				if (num != 2)
				{
					if (num != 3)
					{
						goto IL_013f;
					}
					DateTime dateTime2 = dateTime;
					result = dateTime2.ToDateTimeInTargetTimeZone(text, (functionArgs.Parameters[2].Evaluate() as string) ?? throw new ArgumentException("format function - expected third argument to be a TimeZone string"));
				}
				else
				{
					result = dateTime.BetterToString(text);
				}
			}
			else
			{
				if (!(obj is string inputString) || num != 2)
				{
					goto IL_013f;
				}
				result = GetThing(inputString, text);
			}
			functionArgs.Result = result;
			return;
			IL_013f:
			throw new NotSupportedException("Unsupported input type " + obj.GetType().Name + " or incorrect number of parameters.");
		}

		private static object GetThing(string inputString, string formatFormat)
		{
			if (long.TryParse(inputString, out var result))
			{
				return result.ToString(formatFormat, CultureInfo.InvariantCulture);
			}
			if (double.TryParse(inputString, out var result2))
			{
				return result2.ToString(formatFormat, CultureInfo.InvariantCulture);
			}
			if (DateTimeOffset.TryParse(inputString, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal, out var result3))
			{
				return result3.UtcDateTime.BetterToString(formatFormat);
			}
			throw new FormatException("Could not parse '" + inputString + "' as a number or date.");
		}
	}
	internal static class GetProperty
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected I4, but got Unknown
			//IL_017e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			object obj;
			string text;
			try
			{
				obj = functionArgs.Parameters[0].Evaluate();
				text = (string)functionArgs.Parameters[1].Evaluate();
			}
			catch (Exception innerException)
			{
				throw new FormatException("getProperty() requires two parameters.", innerException);
			}
			JObject val = (JObject)((obj is JObject) ? obj : null);
			if (val != null)
			{
				JToken val2 = val[text];
				object result;
				switch ((val2 != null) ? new JTokenType?(val2.Type) : null)
				{
				case null:
				case 9L:
				case 10L:
					result = null;
					break;
				case 0L:
					result = val2.ToObject<JObject>();
					break;
				case 1L:
					result = val2.ToObject<JArray>();
					break;
				case 2L:
					result = val2.ToObject<JConstructor>();
					break;
				case 3L:
					result = val2.ToObject<JProperty>();
					break;
				case 4L:
					result = val2.ToObject<JValue>();
					break;
				case 5L:
					result = val2.ToObject<int>();
					break;
				case 6L:
					result = val2.ToObject<float>();
					break;
				case 7L:
					result = val2.ToObject<string>();
					break;
				case 8L:
					result = val2.ToObject<bool>();
					break;
				case 11L:
					result = val2.ToObject<DateTime>();
					break;
				case 12L:
				case 13L:
					result = val2.ToObject<JValue>();
					break;
				case 14L:
					result = val2.ToObject<Guid>();
					break;
				default:
				{
					JTokenType type = val2.Type;
					throw new NotSupportedException("Unsupported JTokenType: " + ((object)(JTokenType)(ref type)).ToString());
				}
				}
				functionArgs.Result = result;
			}
			else
			{
				Type type2 = obj.GetType();
				PropertyInfo propertyInfo = type2.GetProperty(text) ?? throw new FormatException("Could not find property " + text + " on type " + type2.Name);
				functionArgs.Result = propertyInfo.GetValue(obj);
			}
		}
	}
	internal static class Humanize
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			double param1Double;
			string value;
			try
			{
				if (!double.TryParse(functionArgs.Parameters[0].Evaluate().ToString(), out var result))
				{
					throw new Exception();
				}
				param1Double = result;
				value = (string)functionArgs.Parameters[1].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("humanize function - The first number should be a valid floating-point number and the second should be a time unit (" + string.Join(", ", Enum.GetNames(typeof(TimeUnit))) + ").");
			}
			if (!Enum.TryParse<TimeUnit>(value, ignoreCase: true, out var result2))
			{
				throw new FormatException("humanize function - Parameter 2 must be a time unit - one of " + string.Join(", ", from n in Enum.GetNames(typeof(TimeUnit))
					select "'" + n + "'") + ".");
			}
			functionArgs.Result = Humanise(param1Double, result2);
		}

		private static string Humanise(double param1Double, TimeUnit timeUnit)
		{
			try
			{
				return timeUnit switch
				{
					TimeUnit.Milliseconds => System.TimeSpan.FromMilliseconds(param1Double).Humanise(), 
					TimeUnit.Seconds => System.TimeSpan.FromSeconds(param1Double).Humanise(), 
					TimeUnit.Minutes => System.TimeSpan.FromMinutes(param1Double).Humanise(), 
					TimeUnit.Hours => System.TimeSpan.FromHours(param1Double).Humanise(), 
					TimeUnit.Days => System.TimeSpan.FromDays(param1Double).Humanise(), 
					TimeUnit.Weeks => System.TimeSpan.FromDays(param1Double * 7.0).Humanise(), 
					TimeUnit.Years => System.TimeSpan.FromDays(param1Double * 365.25).Humanise(), 
					_ => throw new FormatException($"{timeUnit} is not a supported time unit for humanization."), 
				};
			}
			catch (OverflowException)
			{
				throw new FormatException("The value is too big to use humanize. It must be a double (a 64-bit, floating point number)");
			}
		}
	}
	internal static class If
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 3)
			{
				throw new FormatException("if() requires three parameters.");
			}
			bool flag;
			try
			{
				flag = (bool)functionArgs.Parameters[0].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(string.Format("Could not evaluate {0} function parameter 1 '{1}'.", "if", functionArgs.Parameters[0].ParsedExpression));
			}
			if (flag)
			{
				try
				{
					functionArgs.Result = functionArgs.Parameters[1].Evaluate();
					return;
				}
				catch (Exception ex2) when (!(ex2 is NCalcExtensionsException))
				{
					throw new FormatException(string.Format("Could not evaluate {0} function parameter 2 '{1}' due to {2}.", "if", functionArgs.Parameters[1].ParsedExpression, ex2.Message), ex2);
				}
			}
			try
			{
				functionArgs.Result = functionArgs.Parameters[2].Evaluate();
			}
			catch (Exception ex3) when (!(ex3 is NCalcExtensionsException))
			{
				throw new FormatException(string.Format("Could not evaluate {0} function parameter 3 '{1}' due to {2}.", "if", functionArgs.Parameters[2].ParsedExpression, ex3.Message), ex3);
			}
		}
	}
	internal static class In
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length < 2)
			{
				throw new FormatException("in() requires at least two parameters.");
			}
			try
			{
				object item = functionArgs.Parameters[0].Evaluate();
				List<object> list = (from p in functionArgs.Parameters.Skip(1)
					select p.Evaluate()).ToList();
				functionArgs.Result = list.Contains(item);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("in() parameters malformed.");
			}
		}
	}
	internal static class IndexOf
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string text = (string)functionArgs.Parameters[0].Evaluate();
				string value = (string)functionArgs.Parameters[1].Evaluate();
				functionArgs.Result = text.IndexOf(value, StringComparison.InvariantCulture);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("indexOf() requires two string parameters.");
			}
		}
	}
	internal static class IsGuid
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isGuid() requires one parameter.");
			}
			object obj = functionArgs.Parameters[0].Evaluate();
			functionArgs.Result = obj is Guid || (obj is string && Guid.TryParse(obj.ToString(), out var _));
		}
	}
	internal static class IsInfinite
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isInfinite() requires one parameter.");
			}
			try
			{
				functionArgs.Result = functionArgs.Parameters[0].Evaluate() is double d && (double.IsPositiveInfinity(d) || double.IsNegativeInfinity(d));
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(ex.Message);
			}
		}
	}
	internal static class IsNaN
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isNaN() requires one parameter.");
			}
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				bool flag = ((obj is double d) ? double.IsNaN(d) : ((obj is float f) ? float.IsNaN(f) : ((!(obj is int) && !(obj is long) && !(obj is short) && !(obj is byte) && !(obj is sbyte) && !(obj is uint) && !(obj is ulong) && !(obj is ushort) && !(obj is decimal)) ? true : false)));
				functionArgs.Result = flag;
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(ex.Message);
			}
		}
	}
	internal static class IsNull
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Invalid comparison between Unknown and I4
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isNull() requires one parameter.");
			}
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				int num;
				if (obj != null)
				{
					JToken val = (JToken)((obj is JToken) ? obj : null);
					num = ((val != null && (int)val.Type == 10) ? 1 : 0);
				}
				else
				{
					num = 1;
				}
				functionArgs.Result = (byte)num != 0;
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(ex.Message);
			}
		}
	}
	internal static class IsNullOrEmpty
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Invalid comparison between Unknown and I4
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isNullOrEmpty() requires one parameter.");
			}
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				int num;
				if (obj != null)
				{
					JToken val = (JToken)((obj is JToken) ? obj : null);
					if (val == null || (int)val.Type != 10)
					{
						num = ((obj is string text && text == string.Empty) ? 1 : 0);
						goto IL_0058;
					}
				}
				num = 1;
				goto IL_0058;
				IL_0058:
				functionArgs.Result = (byte)num != 0;
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(ex.Message);
			}
		}
	}
	internal static class IsNullOrWhiteSpace
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Invalid comparison between Unknown and I4
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("isNullOrWhiteSpace() requires one parameter.");
			}
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				int num;
				if (obj != null)
				{
					JToken val = (JToken)((obj is JToken) ? obj : null);
					if (val == null || (int)val.Type != 10)
					{
						num = ((obj is string value && string.IsNullOrWhiteSpace(value)) ? 1 : 0);
						goto IL_0053;
					}
				}
				num = 1;
				goto IL_0053;
				IL_0053:
				functionArgs.Result = (byte)num != 0;
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException(ex.Message);
			}
		}
	}
	internal static class IsSet
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			FunctionArgs functionArgs2 = functionArgs;
			if (functionArgs2.Parameters.Length != 1)
			{
				throw new FormatException("isSet() requires one parameter.");
			}
			functionArgs2.Result = functionArgs2.Parameters[0].Parameters.Keys.Any((string p) => p == functionArgs2.Parameters[0].Evaluate() as string);
		}
	}
	internal static class ItemAtIndex
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IList list;
			int num;
			try
			{
				list = (IList)functionArgs.Parameters[0].Evaluate();
				num = (int)functionArgs.Parameters[1].Evaluate();
				if (num < 0)
				{
					throw new Exception();
				}
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("itemAtIndex() requires two parameters.  The first should be an IList and the second should be a non-negative integer.");
			}
			functionArgs.Result = list[num];
		}
	}
	internal static class Join
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			List<string> values;
			string separator;
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				values = ((obj == null) ? new List<string>() : ((!(obj is List<object> source)) ? (obj as IEnumerable<string>).ToList() : source.Select((object u) => u?.ToString() ?? string.Empty).ToList()));
				separator = (string)functionArgs.Parameters[1].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("join() requires that the first parameter is a list or enumerable and that the second parameter is a string.");
			}
			functionArgs.Result = string.Join(separator, values);
		}
	}
	internal static class JPath
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			bool flag = false;
			if (functionArgs.Parameters.Length > 3)
			{
				throw new FormatException("jPath function - first parameter should be an object capable of being converted to a JObject and second a string jPath expression with optional third parameter returnNullIfNotFound.");
			}
			JObject val2;
			string text;
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate() ?? throw new NCalcExtensionsException("jPath function - parameter 1 should not be null.");
				JObject val = (JObject)((obj is JObject) ? obj : null);
				val2 = ((val == null) ? JObject.FromObject(obj) : val);
				text = (string)functionArgs.Parameters[1].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("jPath function - first parameter should be an object capable of being converted to a JObject and second a string jPath expression with optional third parameter returnNullIfNotFound. ... " + ex.Message);
			}
			if (functionArgs.Parameters.Length >= 3)
			{
				try
				{
					flag = (bool)functionArgs.Parameters[2].Evaluate();
				}
				catch (Exception)
				{
					throw new FormatException("jPath function - parameter 3 should be a bool.");
				}
			}
			JToken val3;
			try
			{
				val3 = ((JToken)val2).SelectToken(text);
			}
			catch (Exception ex3)
			{
				throw new NCalcExtensionsException("jPath function - An unknown issue occurred while trying to select jPathExpression value: " + ex3.Message);
			}
			if (val3 == null)
			{
				if (flag)
				{
					functionArgs.Result = null;
					return;
				}
				throw new NCalcExtensionsException("jPath function - jPath expression did not result in a match.");
			}
			JValue val4 = (JValue)(object)((val3 is JValue) ? val3 : null);
			object result;
			if (val4 == null)
			{
				JArray val5 = (JArray)(object)((val3 is JArray) ? val3 : null);
				result = ((val5 == null) ? ((object)JObject.FromObject((object)val3)) : ((object)val5));
			}
			else
			{
				result = val4.Value;
			}
			functionArgs.Result = result;
		}
	}
	internal static class LambdaFunction
	{
		internal static void Evaluate(FunctionArgs functionArgs, Dictionary<string, object?> storageDictionary)
		{
			string predicate;
			string nCalcString;
			try
			{
				predicate = (string)functionArgs.Parameters[0].Evaluate();
				nCalcString = (string)functionArgs.Parameters[1].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("store() requires two parameters.");
			}
			functionArgs.Result = new Lambda(predicate, nCalcString, storageDictionary);
		}
	}
	internal static class LastIndexOf
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string text = (string)functionArgs.Parameters[0].Evaluate();
				string value = (string)functionArgs.Parameters[1].Evaluate();
				functionArgs.Result = text.LastIndexOf(value, StringComparison.InvariantCulture);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("lastIndexOf() requires two string parameters.");
			}
		}
	}
	internal static class Length
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				object obj = functionArgs.Parameters[0].Evaluate();
				if (obj is string text)
				{
					functionArgs.Result = text.Length;
				}
				else
				{
					functionArgs.Result = GetLength(obj);
				}
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("length() requires one string or IList parameter.");
			}
		}

		private static int GetLength(object value)
		{
			if (value is IList list)
			{
				return list.Count;
			}
			throw new FormatException("length() requires one string or IList parameter.");
		}
	}
	internal static class List
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			functionArgs.Result = functionArgs.Parameters.Select((Expression p) => p.Evaluate()).ToList();
		}
	}
	internal static class ListHelpers
	{
		internal static List<object?> Collapse(this List<object?> value)
		{
			while (value.All((object v) => v?.GetType() == typeof(List<object>)))
			{
				if (value.Count == 0)
				{
					return new List<object>();
				}
				value = value.SelectMany((object v) => v as List<object>).ToList();
			}
			return value;
		}
	}
	internal static class ListOf
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			string text = (functionArgs.Parameters[0].Evaluate() as string) ?? throw new FormatException("First listOf parameter must be a string.");
			Expression[] remainingParameters = functionArgs.Parameters.Skip(1).ToArray();
			switch (text)
			{
			case "byte":
				functionArgs.Result = GetListOf<byte>(remainingParameters);
				break;
			case "byte?":
				functionArgs.Result = GetListOf<byte?>(remainingParameters);
				break;
			case "short":
				functionArgs.Result = GetListOf<short>(remainingParameters);
				break;
			case "short?":
				functionArgs.Result = GetListOf<short?>(remainingParameters);
				break;
			case "int":
				functionArgs.Result = GetListOf<int>(remainingParameters);
				break;
			case "int?":
				functionArgs.Result = GetListOf<int?>(remainingParameters);
				break;
			case "long":
				functionArgs.Result = GetListOf<long>(remainingParameters);
				break;
			case "long?":
				functionArgs.Result = GetListOf<long?>(remainingParameters);
				break;
			case "float":
				functionArgs.Result = GetListOf<float>(remainingParameters);
				break;
			case "float?":
				functionArgs.Result = GetListOf<float?>(remainingParameters);
				break;
			case "double":
				functionArgs.Result = GetListOf<double>(remainingParameters);
				break;
			case "double?":
				functionArgs.Result = GetListOf<double?>(remainingParameters);
				break;
			case "decimal":
				functionArgs.Result = GetListOf<decimal>(remainingParameters);
				break;
			case "decimal?":
				functionArgs.Result = GetListOf<decimal?>(remainingParameters);
				break;
			case "string":
				functionArgs.Result = GetListOf<string>(remainingParameters);
				break;
			case "string?":
				functionArgs.Result = GetListOf<string>(remainingParameters);
				break;
			case "object":
				functionArgs.Result = GetListOf<object>(remainingParameters);
				break;
			case "object?":
				functionArgs.Result = GetListOf<object>(remainingParameters);
				break;
			default:
				throw new FormatException("First listOf parameter must be a string of a numeric or string type.");
			}
		}

		private static List<T> GetListOf<T>(Expression[] remainingParameters)
		{
			List<T> list = new List<T>();
			foreach (Expression val in remainingParameters)
			{
				object obj = val.Evaluate();
				if (typeof(T) == typeof(object))
				{
					list.Add((T)obj);
				}
				else if (Nullable.GetUnderlyingType(typeof(T)) != null && obj == null)
				{
					list.Add(default(T));
				}
				else if (Nullable.GetUnderlyingType(typeof(T)) != null && obj != null)
				{
					Type underlyingType = Nullable.GetUnderlyingType(typeof(T));
					if (underlyingType != null)
					{
						object obj2 = Convert.ChangeType(obj, underlyingType);
						list.Add((T)obj2);
					}
				}
				else if (obj is T item)
				{
					list.Add(item);
				}
				else
				{
					if (!(Convert.ChangeType(obj, typeof(T)) is T item2))
					{
						throw new FormatException("Parameter must be of type " + TypeHelper.AsHumanString<T>() + ".");
					}
					list.Add(item2);
				}
			}
			return list;
		}
	}
	internal static class Max
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			object result;
			if (functionArgs.Parameters.Length == 1)
			{
				object obj2 = obj;
				if (obj2 != null)
				{
					if (!(obj2 is IEnumerable<byte> source))
					{
						if (!(obj2 is IEnumerable<byte?> source2))
						{
							if (!(obj2 is IEnumerable<short> source3))
							{
								if (!(obj2 is IEnumerable<short?> source4))
								{
									if (!(obj2 is IEnumerable<int> source5))
									{
										if (!(obj2 is IEnumerable<int?> source6))
										{
											if (!(obj2 is IEnumerable<long> source7))
											{
												if (!(obj2 is IEnumerable<long?> source8))
												{
													if (!(obj2 is IEnumerable<float> source9))
													{
														if (!(obj2 is IEnumerable<float?> source10))
														{
															if (!(obj2 is IEnumerable<double> source11))
															{
																if (!(obj2 is IEnumerable<double?> source12))
																{
																	if (!(obj2 is IEnumerable<decimal> source13))
																	{
																		if (!(obj2 is IEnumerable<decimal?> source14))
																		{
																			if (!(obj2 is IEnumerable<string> source15))
																			{
																				if (!(obj2 is IEnumerable<object> enumerable))
																				{
																					throw new FormatException("First max parameter must be an IEnumerable of a numeric or string type if only on parameter is present.");
																				}
																				if (enumerable.All((object x) => (x is string || x == null) ? true : false))
																				{
																					result = enumerable.DefaultIfEmpty(null).Max((object x) => x as string);
																				}
																				else
																				{
																					IEnumerable<object> objectList = enumerable;
																					result = GetMax(objectList);
																				}
																			}
																			else
																			{
																				result = source15.DefaultIfEmpty(null).Max();
																			}
																		}
																		else
																		{
																			result = source14.DefaultIfEmpty(null).Max();
																		}
																	}
																	else
																	{
																		result = source13.Max();
																	}
																}
																else
																{
																	result = source12.DefaultIfEmpty(null).Max();
																}
															}
															else
															{
																result = source11.Max();
															}
														}
														else
														{
															result = source10.DefaultIfEmpty(null).Max();
														}
													}
													else
													{
														result = source9.Max();
													}
												}
												else
												{
													result = source8.DefaultIfEmpty(null).Max();
												}
											}
											else
											{
												result = source7.Max();
											}
										}
										else
										{
											result = source6.DefaultIfEmpty(null).Max();
										}
									}
									else
									{
										result = source5.Max();
									}
								}
								else
								{
									result = source4.DefaultIfEmpty(null).Max();
								}
							}
							else
							{
								result = source3.Cast<int>().Max();
							}
						}
						else
						{
							result = source2.DefaultIfEmpty(null).Max();
						}
					}
					else
					{
						result = source.Cast<int>().Max();
					}
				}
				else
				{
					result = null;
				}
				functionArgs.Result = result;
				return;
			}
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second max parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third max parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			if (!(obj is IEnumerable<byte> source16))
			{
				if (!(obj is IEnumerable<byte?> source17))
				{
					if (!(obj is IEnumerable<short> source18))
					{
						if (!(obj is IEnumerable<short?> source19))
						{
							if (!(obj is IEnumerable<int> source20))
							{
								if (!(obj is IEnumerable<int?> source21))
								{
									if (!(obj is IEnumerable<long> source22))
									{
										if (!(obj is IEnumerable<long?> source23))
										{
											if (!(obj is IEnumerable<float> source24))
											{
												if (!(obj is IEnumerable<float?> source25))
												{
													if (!(obj is IEnumerable<double> source26))
													{
														if (!(obj is IEnumerable<double?> source27))
														{
															if (!(obj is IEnumerable<decimal> source28))
															{
																if (!(obj is IEnumerable<decimal?> source29))
																{
																	if (!(obj is IEnumerable<string> source30))
																	{
																		throw new FormatException("First max parameter must be an IEnumerable of a numeric type.");
																	}
																	result = source30.Max((string value) => (string)lambda.Evaluate(value));
																}
																else
																{
																	result = source29.Max((decimal? value) => (decimal?)lambda.Evaluate(value));
																}
															}
															else
															{
																result = source28.Max((decimal value) => (decimal?)lambda.Evaluate(value));
															}
														}
														else
														{
															result = source27.Max((double? value) => (double?)lambda.Evaluate(value));
														}
													}
													else
													{
														result = source26.Max((double value) => (double?)lambda.Evaluate(value));
													}
												}
												else
												{
													result = source25.Max((float? value) => (float?)lambda.Evaluate(value));
												}
											}
											else
											{
												result = source24.Max((float value) => (float?)lambda.Evaluate(value));
											}
										}
										else
										{
											result = source23.Max((long? value) => (long?)lambda.Evaluate(value));
										}
									}
									else
									{
										result = source22.Max((long value) => (long?)lambda.Evaluate(value));
									}
								}
								else
								{
									result = source21.Max((int? value) => (int?)lambda.Evaluate(value));
								}
							}
							else
							{
								result = source20.Max((int value) => (int?)lambda.Evaluate(value));
							}
						}
						else
						{
							result = source19.Cast<int>().Max((int value) => (int?)lambda.Evaluate(value));
						}
					}
					else
					{
						result = source18.Cast<int>().Max((int value) => (int?)lambda.Evaluate(value));
					}
				}
				else
				{
					result = source17.Cast<int>().Max((int value) => (int?)lambda.Evaluate(value));
				}
			}
			else
			{
				result = source16.Cast<int>().Max((int value) => (int?)lambda.Evaluate(value));
			}
			functionArgs.Result = result;
		}

		private static double GetMax(IEnumerable<object?> objectList)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Invalid comparison between Unknown and I4
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Invalid comparison between Unknown and I4
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			double num = 0.0;
			foreach (object @object in objectList)
			{
				double num8;
				if (!(@object is byte b))
				{
					if (!(@object is short num2))
					{
						if (!(@object is int num3))
						{
							if (!(@object is long num4))
							{
								if (!(@object is float num5))
								{
									if (!(@object is double num6))
									{
										if (!(@object is decimal num7))
										{
											JValue val = (JValue)((@object is JValue) ? @object : null);
											if (val == null)
											{
												if (@object != null)
												{
													throw new FormatException("Found unsupported type '" + @object?.GetType().Name + "' when completing sum.");
												}
												num8 = 0.0;
											}
											else
											{
												JTokenType type = ((JToken)val).Type;
												float num9;
												if ((int)type != 6)
												{
													if ((int)type != 7)
													{
														throw new FormatException($"Found unsupported JToken type '{((JToken)val).Type}' when completing sum.");
													}
													num9 = Extensions.Value<float>((IEnumerable<JToken>)val);
												}
												else
												{
													num9 = Extensions.Value<int>((IEnumerable<JToken>)val);
												}
												num8 = num9;
											}
										}
										else
										{
											num8 = (double)num7;
										}
									}
									else
									{
										num8 = num6;
									}
								}
								else
								{
									num8 = num5;
								}
							}
							else
							{
								num8 = num4;
							}
						}
						else
						{
							num8 = num3;
						}
					}
					else
					{
						num8 = num2;
					}
				}
				else
				{
					num8 = (int)b;
				}
				double num10 = num8;
				if (num10 < num)
				{
					num = num10;
				}
			}
			return num;
		}
	}
	internal static class MaxValue
	{
		private const string ErrorMessage = "maxValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'.";

		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("maxValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'.");
			}
			functionArgs.Result = (obj as string) switch
			{
				"sbyte" => sbyte.MaxValue, 
				"byte" => byte.MaxValue, 
				"short" => short.MaxValue, 
				"ushort" => ushort.MaxValue, 
				"int" => int.MaxValue, 
				"uint" => uint.MaxValue, 
				"long" => long.MaxValue, 
				"ulong" => ulong.MaxValue, 
				"float" => float.MaxValue, 
				"double" => double.MaxValue, 
				"decimal" => decimal.MaxValue, 
				_ => throw new FormatException("maxValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'."), 
			};
		}
	}
	internal static class Min
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			object result;
			if (functionArgs.Parameters.Length == 1)
			{
				object obj2 = obj;
				if (obj2 != null)
				{
					if (!(obj2 is IEnumerable<byte> source))
					{
						if (!(obj2 is IEnumerable<byte?> source2))
						{
							if (!(obj2 is IEnumerable<short> source3))
							{
								if (!(obj2 is IEnumerable<short?> source4))
								{
									if (!(obj2 is IEnumerable<int> source5))
									{
										if (!(obj2 is IEnumerable<int?> source6))
										{
											if (!(obj2 is IEnumerable<long> source7))
											{
												if (!(obj2 is IEnumerable<long?> source8))
												{
													if (!(obj2 is IEnumerable<float> source9))
													{
														if (!(obj2 is IEnumerable<float?> source10))
														{
															if (!(obj2 is IEnumerable<double> source11))
															{
																if (!(obj2 is IEnumerable<double?> source12))
																{
																	if (!(obj2 is IEnumerable<decimal> source13))
																	{
																		if (!(obj2 is IEnumerable<decimal?> source14))
																		{
																			if (!(obj2 is IEnumerable<string> source15))
																			{
																				if (!(obj2 is IEnumerable<object> enumerable))
																				{
																					throw new FormatException("First min parameter must be an IEnumerable of a numeric or string type if only one parameter is present.");
																				}
																				if (enumerable.All((object x) => (x is string || x == null) ? true : false))
																				{
																					result = enumerable.DefaultIfEmpty(null).Min((object x) => x as string);
																				}
																				else
																				{
																					IEnumerable<object> objectList = enumerable;
																					result = GetMin(objectList);
																				}
																			}
																			else
																			{
																				result = source15.DefaultIfEmpty(null).Min();
																			}
																		}
																		else
																		{
																			result = source14.DefaultIfEmpty(null).Min();
																		}
																	}
																	else
																	{
																		result = source13.Min();
																	}
																}
																else
																{
																	result = source12.DefaultIfEmpty(null).Min();
																}
															}
															else
															{
																result = source11.Min();
															}
														}
														else
														{
															result = source10.DefaultIfEmpty(null).Min();
														}
													}
													else
													{
														result = source9.Min();
													}
												}
												else
												{
													result = source8.DefaultIfEmpty(null).Min();
												}
											}
											else
											{
												result = source7.Min();
											}
										}
										else
										{
											result = source6.DefaultIfEmpty(null).Min();
										}
									}
									else
									{
										result = source5.Min();
									}
								}
								else
								{
									result = source4.DefaultIfEmpty(null).Min();
								}
							}
							else
							{
								result = source3.Cast<int>().Min();
							}
						}
						else
						{
							result = source2.DefaultIfEmpty(null).Min();
						}
					}
					else
					{
						result = source.Cast<int>().Min();
					}
				}
				else
				{
					result = null;
				}
				functionArgs.Result = result;
				return;
			}
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second min parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third min parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			if (!(obj is IEnumerable<byte> source16))
			{
				if (!(obj is IEnumerable<byte?> source17))
				{
					if (!(obj is IEnumerable<short> source18))
					{
						if (!(obj is IEnumerable<short?> source19))
						{
							if (!(obj is IEnumerable<int> source20))
							{
								if (!(obj is IEnumerable<int?> source21))
								{
									if (!(obj is IEnumerable<long> source22))
									{
										if (!(obj is IEnumerable<long?> source23))
										{
											if (!(obj is IEnumerable<float> source24))
											{
												if (!(obj is IEnumerable<float?> source25))
												{
													if (!(obj is IEnumerable<double> source26))
													{
														if (!(obj is IEnumerable<double?> source27))
														{
															if (!(obj is IEnumerable<decimal> source28))
															{
																if (!(obj is IEnumerable<decimal?> source29))
																{
																	if (!(obj is IEnumerable<string> source30))
																	{
																		throw new FormatException("First min parameter must be an IEnumerable of a numeric type.");
																	}
																	result = source30.Min((string value) => (string)lambda.Evaluate(value));
																}
																else
																{
																	result = source29.Min((decimal? value) => (decimal?)lambda.Evaluate(value));
																}
															}
															else
															{
																result = source28.Min((decimal value) => (decimal?)lambda.Evaluate(value));
															}
														}
														else
														{
															result = source27.Min((double? value) => (double?)lambda.Evaluate(value));
														}
													}
													else
													{
														result = source26.Min((double value) => (double?)lambda.Evaluate(value));
													}
												}
												else
												{
													result = source25.Min((float? value) => (float?)lambda.Evaluate(value));
												}
											}
											else
											{
												result = source24.Min((float value) => (float?)lambda.Evaluate(value));
											}
										}
										else
										{
											result = source23.Min((long? value) => (long?)lambda.Evaluate(value));
										}
									}
									else
									{
										result = source22.Min((long value) => (long?)lambda.Evaluate(value));
									}
								}
								else
								{
									result = source21.Min((int? value) => (int?)lambda.Evaluate(value));
								}
							}
							else
							{
								result = source20.Min((int value) => (int?)lambda.Evaluate(value));
							}
						}
						else
						{
							result = source19.Cast<int>().Min((int value) => (int?)lambda.Evaluate(value));
						}
					}
					else
					{
						result = source18.Cast<int>().Min((int value) => (int?)lambda.Evaluate(value));
					}
				}
				else
				{
					result = source17.Cast<int>().Min((int value) => (int?)lambda.Evaluate(value));
				}
			}
			else
			{
				result = source16.Cast<int>().Min((int value) => (int?)lambda.Evaluate(value));
			}
			functionArgs.Result = result;
		}

		private static double GetMin(IEnumerable<object?> objectList)
		{
			//IL_0101: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Invalid comparison between Unknown and I4
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Invalid comparison between Unknown and I4
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			double num = 0.0;
			foreach (object @object in objectList)
			{
				double num8;
				if (!(@object is byte b))
				{
					if (!(@object is short num2))
					{
						if (!(@object is int num3))
						{
							if (!(@object is long num4))
							{
								if (!(@object is float num5))
								{
									if (!(@object is double num6))
									{
										if (!(@object is decimal num7))
										{
											JValue val = (JValue)((@object is JValue) ? @object : null);
											if (val == null)
											{
												if (@object != null)
												{
													throw new FormatException("Found unsupported type '" + @object?.GetType().Name + "' when completing sum.");
												}
												num8 = 0.0;
											}
											else
											{
												JTokenType type = ((JToken)val).Type;
												float num9;
												if ((int)type != 6)
												{
													if ((int)type != 7)
													{
														throw new FormatException($"Found unsupported JToken type '{((JToken)val).Type}' when completing sum.");
													}
													num9 = Extensions.Value<float>((IEnumerable<JToken>)val);
												}
												else
												{
													num9 = Extensions.Value<int>((IEnumerable<JToken>)val);
												}
												num8 = num9;
											}
										}
										else
										{
											num8 = (double)num7;
										}
									}
									else
									{
										num8 = num6;
									}
								}
								else
								{
									num8 = num5;
								}
							}
							else
							{
								num8 = num4;
							}
						}
						else
						{
							num8 = num3;
						}
					}
					else
					{
						num8 = num2;
					}
				}
				else
				{
					num8 = (int)b;
				}
				double num10 = num8;
				if (num10 < num)
				{
					num = num10;
				}
			}
			return num;
		}
	}
	internal static class MinValue
	{
		private const string ErrorMessage = "minValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'.";

		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("minValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'.");
			}
			functionArgs.Result = (obj as string) switch
			{
				"sbyte" => sbyte.MinValue, 
				"byte" => (byte)0, 
				"short" => short.MinValue, 
				"ushort" => (ushort)0, 
				"int" => int.MinValue, 
				"uint" => 0u, 
				"long" => long.MinValue, 
				"ulong" => 0uL, 
				"float" => float.MinValue, 
				"double" => double.MinValue, 
				"decimal" => decimal.MinValue, 
				_ => throw new FormatException("minValue takes exactly one string parameter, which must be one of 'sbyte', 'byte', 'short', 'ushort', 'int', 'uint', 'long', 'ulong', 'float', 'double' or 'decimal'."), 
			};
		}
	}
	internal static class NewJObject
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Expected O, but got Unknown
			if (functionArgs.Parameters.Length % 2 != 0)
			{
				throw new FormatException("jObject() requires an even number of parameters.");
			}
			int num = 0;
			JObject val = new JObject();
			while (num < functionArgs.Parameters.Length)
			{
				if (!(functionArgs.Parameters[num++].Evaluate() is string text))
				{
					throw new FormatException("jObject() requires a string key.");
				}
				if (val.ContainsKey(text))
				{
					throw new FormatException("jObject() can only define property " + text + " once.");
				}
				object obj = functionArgs.Parameters[num++].Evaluate();
				val.Add(text, (JToken)((obj == null) ? ((object)JValue.CreateNull()) : ((object)JToken.FromObject(obj))));
			}
			functionArgs.Result = val;
		}
	}
	internal static class SetProperties
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length % 2 != 1)
			{
				throw new FormatException("setProperties() requires an odd number of parameters.");
			}
			int num = 0;
			object obj = functionArgs.Parameters[num++].Evaluate();
			JObject val = (JObject)((obj is JObject) ? obj : null);
			JObject val2 = ((val == null) ? JObject.FromObject(obj) : val);
			while (num < functionArgs.Parameters.Length)
			{
				if (!(functionArgs.Parameters[num++].Evaluate() is string text))
				{
					throw new FormatException("setProperties() requires a string key.");
				}
				if (val2.ContainsKey(text))
				{
					throw new FormatException("setProperties() can only define property " + text + " once.");
				}
				object obj2 = functionArgs.Parameters[num++].Evaluate();
				val2.Add(text, (JToken)((obj2 == null) ? ((object)JValue.CreateNull()) : ((object)JToken.FromObject(obj2))));
			}
			functionArgs.Result = val2;
		}
	}
	internal static class NullCoalesce
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			Expression[] parameters = functionArgs.Parameters;
			foreach (Expression val in parameters)
			{
				object obj = val.Evaluate();
				if (obj != null)
				{
					functionArgs.Result = obj;
					return;
				}
			}
			functionArgs.Result = null;
		}
	}
	internal static class OrderBy
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			int num = 0;
			IEnumerable<object> source = (functionArgs.Parameters[num++].Evaluate() as IEnumerable<object>) ?? throw new FormatException("First orderBy parameter must be an IEnumerable.");
			string predicate = (functionArgs.Parameters[num++].Evaluate() as string) ?? throw new FormatException("Second orderBy parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[num++].Evaluate() as string) ?? throw new FormatException("Third orderBy parameter must be a string.");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			IOrderedEnumerable<object> source2 = source.OrderBy((object value) => lambda.Evaluate(value));
			int num2 = functionArgs.Parameters.Length;
			while (num < num2)
			{
				nCalcString = (functionArgs.Parameters[num++].Evaluate() as string) ?? throw new FormatException(string.Format("{0} parameter {1} must be a string.", "orderBy", num + 1));
				lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
				source2 = source2.ThenBy((object value) => lambda.Evaluate(value));
			}
			functionArgs.Result = source2.ToList();
		}
	}
	internal static class PadLeft
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			string text;
			int num;
			char paddingChar;
			try
			{
				text = (string)functionArgs.Parameters[0].Evaluate();
				num = (int)functionArgs.Parameters[1].Evaluate();
				if (num < 1)
				{
					throw new NCalcExtensionsException("padLeft() requires a DesiredStringLength for parameter 2 that is >= 1.");
				}
				string text2 = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new NCalcExtensionsException("padLeft() requires that parameter 3 be a string.");
				if (text2.Length != 1)
				{
					throw new NCalcExtensionsException("padLeft() requires a single character string for parameter 3.");
				}
				paddingChar = text2[0];
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("padLeft() requires a string Input, an integer DesiredStringLength, and a single Padding character.");
			}
			functionArgs.Result = text.PadLeft(num, paddingChar);
		}
	}
	internal static class Parameters
	{
		internal static T1 GetParameter<T1>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(1, 1, args.Parameters, callerName);
			T1 val = (T1)args.Parameters[0].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " argument should be a " + typeof(T1).Name + ".");
			}
			return val;
		}

		internal static Tuple<T1, T2> GetParameters<T1, T2>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(2, 2, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			return new Tuple<T1, T2>(val, val2);
		}

		internal static Tuple<T1, T2, T3> GetParameters<T1, T2, T3>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(3, 3, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			T3 val3 = (T3)args.Parameters[num++].Evaluate();
			if (val3 == null)
			{
				throw new FormatException(callerName + " third argument should be a " + typeof(T3).Name + ".");
			}
			return new Tuple<T1, T2, T3>(val, val2, val3);
		}

		internal static Tuple<T1, T2, T3, T4> GetParameters<T1, T2, T3, T4>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(4, 4, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			T3 val3 = (T3)args.Parameters[num++].Evaluate();
			if (val3 == null)
			{
				throw new FormatException(callerName + " third argument should be a " + typeof(T3).Name + ".");
			}
			T4 val4 = (T4)args.Parameters[num++].Evaluate();
			if (val4 == null)
			{
				throw new FormatException(callerName + " fourth argument should be a " + typeof(T4).Name + ".");
			}
			return new Tuple<T1, T2, T3, T4>(val, val2, val3, val4);
		}

		internal static Tuple<T1, T2, T3, T4, T5> GetParameters<T1, T2, T3, T4, T5>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(5, 5, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			T3 val3 = (T3)args.Parameters[num++].Evaluate();
			if (val3 == null)
			{
				throw new FormatException(callerName + " third argument should be a " + typeof(T3).Name + ".");
			}
			T4 val4 = (T4)args.Parameters[num++].Evaluate();
			if (val4 == null)
			{
				throw new FormatException(callerName + " fourth argument should be a " + typeof(T4).Name + ".");
			}
			T5 val5 = (T5)args.Parameters[num++].Evaluate();
			if (val5 == null)
			{
				throw new FormatException(callerName + " fifth argument should be a " + typeof(T5).Name + ".");
			}
			return new Tuple<T1, T2, T3, T4, T5>(val, val2, val3, val4, val5);
		}

		internal static Tuple<T1, T2, T3, T4, T5, T6> GetParameters<T1, T2, T3, T4, T5, T6>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(6, 6, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			T3 val3 = (T3)args.Parameters[num++].Evaluate();
			if (val3 == null)
			{
				throw new FormatException(callerName + " third argument should be a " + typeof(T3).Name + ".");
			}
			T4 val4 = (T4)args.Parameters[num++].Evaluate();
			if (val4 == null)
			{
				throw new FormatException(callerName + " fourth argument should be a " + typeof(T4).Name + ".");
			}
			T5 val5 = (T5)args.Parameters[num++].Evaluate();
			if (val5 == null)
			{
				throw new FormatException(callerName + " fifth argument should be a " + typeof(T5).Name + ".");
			}
			T6 val6 = (T6)args.Parameters[num++].Evaluate();
			if (val6 == null)
			{
				throw new FormatException(callerName + " sixth argument should be a " + typeof(T6).Name + ".");
			}
			return new Tuple<T1, T2, T3, T4, T5, T6>(val, val2, val3, val4, val5, val6);
		}

		internal static Tuple<T1, T2, T3, T4, T5, T6, T7> GetParameters<T1, T2, T3, T4, T5, T6, T7>(FunctionArgs args, [CallerMemberName] string callerName = "")
		{
			CheckParameterCount(7, 7, args.Parameters, callerName);
			int num = 0;
			T1 val = (T1)args.Parameters[num++].Evaluate();
			if (val == null)
			{
				throw new FormatException(callerName + " first argument should be a " + typeof(T1).Name + ".");
			}
			T2 val2 = (T2)args.Parameters[num++].Evaluate();
			if (val2 == null)
			{
				throw new FormatException(callerName + " second argument should be a " + typeof(T2).Name + ".");
			}
			T3 val3 = (T3)args.Parameters[num++].Evaluate();
			if (val3 == null)
			{
				throw new FormatException(callerName + " third argument should be a " + typeof(T3).Name + ".");
			}
			T4 val4 = (T4)args.Parameters[num++].Evaluate();
			if (val4 == null)
			{
				throw new FormatException(callerName + " fourth argument should be a " + typeof(T4).Name + ".");
			}
			T5 val5 = (T5)args.Parameters[num++].Evaluate();
			if (val5 == null)
			{
				throw new FormatException(callerName + " fifth argument should be a " + typeof(T5).Name + ".");
			}
			T6 val6 = (T6)args.Parameters[num++].Evaluate();
			if (val6 == null)
			{
				throw new FormatException(callerName + " sixth argument should be a " + typeof(T6).Name + ".");
			}
			T7 val7 = (T7)args.Parameters[num++].Evaluate();
			if (val7 == null)
			{
				throw new FormatException(callerName + " seventh argument should be a " + typeof(T7).Name + ".");
			}
			return new Tuple<T1, T2, T3, T4, T5, T6, T7>(val, val2, val3, val4, val5, val6, val7);
		}

		internal static void CheckParameterCount(int? minCount, int? maxCount, Expression[] parameters, [CallerMemberName] string callerName = "")
		{
			if (minCount.HasValue && parameters.Length < minCount.Value)
			{
				throw new FormatException($"{callerName} requires at least {minCount} parameters.");
			}
			if (maxCount.HasValue && parameters.Length > maxCount.Value)
			{
				throw new FormatException($"{callerName} requires at most {maxCount} parameters.");
			}
		}
	}
	internal static class Parse
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length < 2)
			{
				throw new FormatException("parse function - requires at least two string parameters.");
			}
			int num = 0;
			string text = (functionArgs.Parameters[num++].Evaluate() as string) ?? throw new FormatException("parse function - first parameter should be a string.");
			string text2 = (functionArgs.Parameters[num++].Evaluate() as string) ?? throw new FormatException("parse function - second parameter should be a string.");
			try
			{
				object result;
				switch (text)
				{
				case "bool":
				{
					if (!bool.TryParse(text2, out var result12))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result12;
					break;
				}
				case "sbyte":
				{
					if (!sbyte.TryParse(text2, out var result7))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result7;
					break;
				}
				case "byte":
				{
					if (!byte.TryParse(text2, out var result13))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result13;
					break;
				}
				case "short":
				{
					if (!short.TryParse(text2, out var result4))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result4;
					break;
				}
				case "ushort":
				{
					if (!ushort.TryParse(text2, out var result9))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result9;
					break;
				}
				case "int":
				{
					if (!int.TryParse(text2, out var result3))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result3;
					break;
				}
				case "uint":
				{
					if (!uint.TryParse(text2, out var result10))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result10;
					break;
				}
				case "long":
				{
					if (!long.TryParse(text2, out var result6))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result6;
					break;
				}
				case "ulong":
				{
					if (!ulong.TryParse(text2, out var result14))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result14;
					break;
				}
				case "double":
				{
					if (!double.TryParse(text2, out var result11))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result11;
					break;
				}
				case "float":
				{
					if (!float.TryParse(text2, out var result8))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result8;
					break;
				}
				case "decimal":
				{
					if (!decimal.TryParse(text2, out var result5))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result5;
					break;
				}
				case "Guid":
				{
					if (!Guid.TryParse(text2, out var result2))
					{
						throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.");
					}
					result = result2;
					break;
				}
				case "JObject":
				case "jObject":
					result = ParseJObject(text2);
					break;
				case "jArray":
				case "JArray":
					result = ParseJArray(text2);
					break;
				default:
					throw new FormatException("type '" + text + "' not supported.");
				}
				functionArgs.Result = result;
			}
			catch (FormatException innerException)
			{
				if (functionArgs.Parameters.Length >= 3)
				{
					functionArgs.Result = functionArgs.Parameters[num].Evaluate();
					return;
				}
				throw new FormatException("parse function - parameter '" + text2 + "' could not be parsed to type '" + text + "'.", innerException);
			}
		}

		private static JObject ParseJObject(string text)
		{
			try
			{
				return JObject.Parse(text);
			}
			catch (JsonReaderException)
			{
				throw new FormatException("parse function - parameter '" + text + "' could not be parsed to type 'JObject'.");
			}
		}

		private static JArray ParseJArray(string text)
		{
			try
			{
				return JArray.Parse(text);
			}
			catch (JsonReaderException)
			{
				throw new FormatException("parse function - parameter '" + text + "' could not be parsed to type 'JArray'.");
			}
		}
	}
	internal static class ParseInt
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			if (functionArgs.Parameters.Length != 1)
			{
				throw new FormatException("parseInt function - requires one string parameter.");
			}
			string s = (functionArgs.Parameters[0].Evaluate() as string) ?? throw new FormatException("parseInt function - requires one string parameter.");
			if (!int.TryParse(s, out var result))
			{
				throw new FormatException("parseInt function - parameter could not be parsed to an integer.");
			}
			functionArgs.Result = result;
		}
	}
	internal static class RegexGroup
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string input = (string)functionArgs.Parameters[0].Evaluate();
				string pattern = (string)functionArgs.Parameters[1].Evaluate();
				int num = ((functionArgs.Parameters.Length == 3) ? ((int)functionArgs.Parameters[2].Evaluate()) : 0);
				Regex regex = new Regex(pattern);
				if (!regex.IsMatch(input))
				{
					functionArgs.Result = null;
					return;
				}
				Group group = regex.Match(input).Groups[1];
				functionArgs.Result = ((num >= group.Captures.Count) ? null : group.Captures[num].Value);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("replace() requires three string parameters.");
			}
		}
	}
	internal static class RegexIsMatch
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			object obj = functionArgs.Parameters[0].Evaluate();
			object obj2 = functionArgs.Parameters[1].Evaluate();
			if (!(obj is string input))
			{
				throw new FormatException("regexIsMatch function - first parameter should be a string.");
			}
			if (!(obj2 is string pattern))
			{
				throw new FormatException("regexIsMatch function - second parameter should be a string.");
			}
			Regex regex = new Regex(pattern);
			functionArgs.Result = regex.IsMatch(input);
		}
	}
	internal static class Replace
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			try
			{
				string text = (string)functionArgs.Parameters[0].Evaluate();
				string oldValue = (string)functionArgs.Parameters[1].Evaluate();
				string newValue = (string)functionArgs.Parameters[2].Evaluate();
				functionArgs.Result = text.Replace(oldValue, newValue);
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("replace() requires three string parameters.");
			}
		}
	}
	internal static class Retrieve
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			string key;
			try
			{
				key = (string)functionArgs.Parameters[0].Evaluate();
			}
			catch (Exception ex) when (!(ex is NCalcExtensionsException))
			{
				throw new FormatException("retrieve() requires one string parameter.");
			}
			Dictionary<string, object> dictionary = (functionArgs.Parameters[0].Parameters["__storageDictionary"] as Dictionary<string, object>) ?? throw new FormatException("retrieve() requires a storage dictionary.");
			if (!dictionary.TryGetValue(key, out var value))
			{
				throw new FormatException("Key not found");
			}
			functionArgs.Result = value;
		}
	}
	internal static class Select
	{
		internal static void Evaluate(FunctionArgs functionArgs)
		{
			IList list = (functionArgs.Parameters[0].Evaluate() as IList) ?? throw new FormatException("First select parameter must be an IList.");
			string predicate = (functionArgs.Parameters[1].Evaluate() as string) ?? throw new FormatException("Second select parameter must be a string.");
			string nCalcString = (functionArgs.Parameters[2].Evaluate() as string) ?? throw new FormatException("Third select parameter must be a string.");
			string text = ((functionArgs.Parameters.Length == 4) ? ((functionArgs.Parameters[3].Evaluate() as string) ?? throw new FormatException("Fourth select parameter must be a string.")) : "object");
			Lambda lambda = new Lambda(predicate, nCalcString, functionArgs.Parameters[0].Parameters);
			if (!(text == "object"))
			{
				if (text == "JObject")
				{
					List<JObject> list2 = new List<JObject>();
					foreach (object item2 in list)
					{
						object obj = lambda.Evaluate(item2);
						JObject val2;
						if (obj != null)
						{
							JObject val = (JObject)((obj is JObject) ? obj : null);
							val2 = ((val == null) ? JObject.FromObject(item2) : val);
						}
						else
						{
							val2 = null;
						}
						JObject item = val2;
						list2.Add(item);
					}
					functionArgs.Result = list2;
					return;
				}
				throw new FormatException("Fourth select parameter must be either 'object' (default) or 'JObject'.");
			}
			List<object> list3 = new List<object>();
			foreach (object i