Decompiled source of AtlyssLua v0.1.0

plugins/Lua.dll

Decompiled 3 months ago
#define DEBUG
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Lua.CodeAnalysis;
using Lua.CodeAnalysis.Compilation;
using Lua.CodeAnalysis.Syntax;
using Lua.CodeAnalysis.Syntax.Nodes;
using Lua.IO;
using Lua.Internal;
using Lua.Internal.CompilerServices;
using Lua.Platforms;
using Lua.Runtime;
using Lua.Standard.Internal;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: InternalsVisibleTo("Lua.Tests")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Annulus Games")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyCopyright("© Annulus Games")]
[assembly: AssemblyDescription("High performance Lua interpreter implemented in C# for .NET and Unity")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+053738b3b7d364b8059b0ff33a2edb1193b0f542")]
[assembly: AssemblyProduct("Lua")]
[assembly: AssemblyTitle("Lua")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AnnulusGames/Lua-CSharp")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	[ExcludeFromCodeCoverage]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SetsRequiredMembersAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object?[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = new object[0];
		}

		public StringSyntaxAttribute(string syntax, params object?[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class UnscopedRefAttribute : Attribute
	{
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[]? _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				Debug.Assert(value >= 0);
				Debug.Assert(value <= _chars.Length);
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index]
		{
			get
			{
				Debug.Assert(index < _pos);
				return ref _chars[index];
			}
		}

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			Debug.Assert(capacity >= 0);
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string? s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string? s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			int pos = _pos;
			if (pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			Debug.Assert(additionalCapacityBeyondPos > 0);
			Debug.Assert(_pos > _chars.Length - additionalCapacityBeyondPos, "Grow called incorrectly, no resize is needed.");
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresPreviewFeaturesAttribute : Attribute
	{
		public string? Message { get; }

		public string? Url { get; set; }

		public RequiresPreviewFeaturesAttribute()
		{
		}

		public RequiresPreviewFeaturesAttribute(string? message)
		{
			Message = message;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class AsyncMethodBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public AsyncMethodBuilderAttribute(Type builderType)
		{
			BuilderType = builderType;
			base..ctor();
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CollectionBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public string MethodName { get; }

		public CollectionBuilderAttribute(Type builderType, string methodName)
		{
			BuilderType = builderType;
			MethodName = methodName;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class CompilerFeatureRequiredAttribute : Attribute
	{
		public const string RefStructs = "RefStructs";

		public const string RequiredMembers = "RequiredMembers";

		public string FeatureName { get; }

		public bool IsOptional { get; set; }

		public CompilerFeatureRequiredAttribute(string featureName)
		{
			FeatureName = featureName;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerArgumentAttribute : Attribute
	{
		public string[] Arguments { get; }

		public InterpolatedStringHandlerArgumentAttribute(string argument)
		{
			Arguments = new string[1] { argument };
		}

		public InterpolatedStringHandlerArgumentAttribute(params string[] arguments)
		{
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class InterpolatedStringHandlerAttribute : Attribute
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class ModuleInitializerAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiredMemberAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[ExcludeFromCodeCoverage]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)]
	[ExcludeFromCodeCoverage]
	internal sealed class SkipLocalsInitAttribute : Attribute
	{
	}
}
namespace System.Threading
{
	internal static class CancellationTokenExtensions
	{
		public static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object?> callback, object? state)
		{
			return cancellationToken.Register(callback, state, useSynchronizationContext: false);
		}
	}
}
namespace Lua
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class LuaObjectAttribute : Attribute
	{
		public string? Name { get; }

		public LuaObjectAttribute()
		{
		}

		public LuaObjectAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class LuaMemberAttribute : Attribute
	{
		public string? Name { get; }

		public LuaMemberAttribute()
		{
		}

		public LuaMemberAttribute(string name)
		{
			Name = name;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class LuaMetamethodAttribute : Attribute
	{
		public LuaObjectMetamethod Metamethod { get; }

		public LuaMetamethodAttribute(LuaObjectMetamethod metamethod)
		{
			Metamethod = metamethod;
			base..ctor();
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field)]
	public sealed class LuaIgnoreMemberAttribute : Attribute
	{
	}
	public class LuaParseException : Exception
	{
		public string? ChunkName { get; }

		public SourcePosition Position { get; }

		public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";

		public LuaParseException(string? chunkName, SourcePosition position, string message)
		{
			ChunkName = chunkName;
			Position = position;
			base..ctor(message);
		}

		public static void UnexpectedToken(string? chunkName, SourcePosition position, SyntaxToken token)
		{
			throw new LuaParseException(chunkName, position, $"unexpected symbol <{token.Type}> near '{token.Text}'");
		}

		public static void ExpectedToken(string? chunkName, SourcePosition position, SyntaxTokenType token)
		{
			throw new LuaParseException(chunkName, position, $"'{token}' expected");
		}

		public static void UnfinishedLongComment(string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, $"unfinished long comment (starting at line {position.Line})");
		}

		public static void SyntaxError(string? chunkName, SourcePosition position, SyntaxToken? token)
		{
			throw new LuaParseException(chunkName, position, "syntax error " + ((!token.HasValue) ? "" : $"near '{token.Value.Text}'"));
		}

		public static void NoVisibleLabel(string label, string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, "no visible label '" + label + "' for <goto>");
		}

		public static void BreakNotInsideALoop(string? chunkName, SourcePosition position)
		{
			throw new LuaParseException(chunkName, position, "<break> not inside a loop");
		}
	}
	public class LuaCompileException : Exception
	{
		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private SourcePosition <position>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string <message>P;

		[CompilerGenerated]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string? <nearToken>P;

		public string ChunkName { get; }

		public int OffSet { get; }

		public SourcePosition Position => <position>P;

		public string MainMessage => <message>P;

		public string? NearToken => <nearToken>P;

		public string MessageWithNearToken => base.Message;

		public override string Message => $"{ChunkName}:{Position.Line}: {base.Message}";

		public LuaCompileException(string chunkName, SourcePosition position, int offset, string message, string? nearToken)
		{
			<position>P = position;
			<message>P = message;
			<nearToken>P = nearToken;
			ChunkName = chunkName;
			OffSet = offset;
			base..ctor(GetMessageWithNearToken(<message>P, <nearToken>P));
		}

		private static string GetMessageWithNearToken(string message, string? nearToken)
		{
			if (string.IsNullOrEmpty(nearToken))
			{
				return message;
			}
			return message + " near " + nearToken;
		}
	}
	public class LuaUnDumpException : Exception
	{
		public LuaUnDumpException(string message)
			: base(message)
		{
		}
	}
	internal class LuaStackOverflowException : Exception
	{
		public LuaStackOverflowException()
			: base("stack overflow")
		{
		}

		public override string ToString()
		{
			return "stack overflow";
		}
	}
	internal interface ILuaTracebackBuildable
	{
		Traceback? BuildOrGet();
	}
	public class LuaRuntimeException : Exception, ILuaTracebackBuildable
	{
		private int level = 1;

		private Traceback? luaTraceback;

		public Traceback? LuaTraceback
		{
			get
			{
				if (luaTraceback == null)
				{
					((ILuaTracebackBuildable)this).BuildOrGet();
				}
				return luaTraceback;
			}
		}

		internal LuaState? State { get; private set; } = null;


		public LuaValue ErrorObject { get; }

		public override string Message
		{
			get
			{
				if (base.InnerException != null)
				{
					return base.InnerException.Message;
				}
				if (LuaTraceback == null)
				{
					return ErrorObject.ToString();
				}
				return CreateMessage(LuaTraceback, ErrorObject, level);
			}
		}

		public LuaRuntimeException(LuaState? state, Exception innerException)
			: base(innerException.Message, innerException)
		{
			if (state != null)
			{
				state.CurrentException?.BuildOrGet();
				state.ExceptionTrace.Clear();
				state.CurrentException = this;
			}
			State = state;
		}

		public LuaRuntimeException(LuaState? state, LuaValue errorObject, int level = 1)
		{
			if (state != null)
			{
				state.CurrentException?.BuildOrGet();
				state.ExceptionTrace.Clear();
				state.CurrentException = this;
			}
			State = state;
			ErrorObject = errorObject;
			this.level = level;
		}

		public static void AttemptInvalidOperation(LuaState? state, string op, LuaValue a, LuaValue b)
		{
			string text = a.TypeToString();
			string text2 = b.TypeToString();
			if (text == text2)
			{
				throw new LuaRuntimeException(state, "attempt to " + op + " two " + text + " values");
			}
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + text + " value with a " + text2 + " value");
		}

		public static void AttemptInvalidOperation(LuaState? state, string op, LuaValue a)
		{
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + a.TypeToString() + " value");
		}

		internal static void AttemptInvalidOperationOnLuaStack(LuaState state, string op, int lastPc, int regA, int regB)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			LuaValue luaValue = ((regA < 255) ? state.Stack[currentFrame.Base + regA] : ((LuaClosure)currentFrame.Function).Proto.Constants[regA - 256]);
			LuaValue luaValue2 = ((regB < 255) ? state.Stack[currentFrame.Base + regB] : ((LuaClosure)currentFrame.Function).Proto.Constants[regB - 256]);
			LuaFunction function = currentFrame.Function;
			string name;
			string name2 = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regA, out name);
			string name3;
			string name4 = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, regB, out name3);
			using PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			pooledList.AddRange("attempt to ");
			pooledList.AddRange(op);
			pooledList.AddRange(" a ");
			pooledList.AddRange(luaValue.TypeToString());
			pooledList.AddRange(" value");
			if (name2 != null && name != null)
			{
				pooledList.AddRange(" (" + name2 + " '" + name + "')");
			}
			pooledList.AddRange(" with a ");
			pooledList.AddRange(luaValue2.TypeToString());
			pooledList.AddRange(" value");
			if (name4 != null && name3 != null)
			{
				pooledList.AddRange(" (" + name4 + " '" + name3 + "')");
			}
			throw new LuaRuntimeException(state, pooledList.AsSpan().ToString());
		}

		internal static void AttemptInvalidOperationOnLuaStack(LuaState state, string op, int lastPc, int reg)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			LuaValue luaValue = ((reg < 255) ? state.Stack[currentFrame.Base + reg] : ((LuaClosure)currentFrame.Function).Proto.Constants[reg - 256]);
			LuaFunction function = currentFrame.Function;
			string name;
			string name2 = LuaDebug.GetName(((LuaClosure)function).Proto, lastPc, reg, out name);
			using PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			pooledList.AddRange("attempt to ");
			pooledList.AddRange(op);
			pooledList.AddRange(" a ");
			pooledList.AddRange(luaValue.TypeToString());
			pooledList.AddRange(" value");
			if (name2 != null && name != null)
			{
				pooledList.AddRange(" (" + name2 + " '" + name + "')");
			}
			throw new LuaRuntimeException(state, pooledList.AsSpan().ToString());
		}

		internal static void AttemptInvalidOperationOnUpValues(LuaState state, string op, int reg)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			LuaClosure luaClosure = (LuaClosure)currentFrame.Function;
			Prototype proto = luaClosure.Proto;
			UpValueDesc upValueDesc = proto.UpValues[reg];
			LuaValue value = luaClosure.UpValues[upValueDesc.Index].GetValue();
			string name = upValueDesc.Name;
			throw new LuaRuntimeException(state, "attempt to " + op + " a " + value.TypeToString() + " value (upvalue '" + name + "')");
		}

		internal static (string NameWhat, string Name) GetCurrentFunctionName(LuaState state)
		{
			CallStackFrame currentFrame = state.GetCurrentFrame();
			int pc = currentFrame.CallerInstructionIndex;
			LuaFunction luaFunction;
			if (currentFrame.IsTailCall)
			{
				pc = state.LastPc;
				luaFunction = state.LastCallerFunction;
			}
			else
			{
				ReadOnlySpan<CallStackFrame> callStackFrames = state.GetCallStackFrames();
				CallStackFrame callStackFrame = callStackFrames[callStackFrames.Length - 2];
				luaFunction = callStackFrame.Function;
			}
			if (!(luaFunction is LuaClosure luaClosure))
			{
				return ("function", currentFrame.Function.Name);
			}
			string name;
			return (LuaDebug.GetFuncName(luaClosure.Proto, pc, out name) ?? "", name ?? currentFrame.Function.Name);
		}

		public static void BadArgument(LuaState state, int argumentId)
		{
			BadArgument(state, argumentId, "value expected");
		}

		public static void BadArgument(LuaState state, int argumentId, LuaValueType expected, LuaValueType actual)
		{
			BadArgument(state, argumentId, LuaValue.ToString(expected) + " expected, got " + LuaValue.ToString(actual) + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, LuaValueType[] expected, LuaValueType actual)
		{
			BadArgument(state, argumentId, "(" + string.Join(" or ", expected.Select(LuaValue.ToString)) + " expected, got " + LuaValue.ToString(actual) + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string expected, string actual)
		{
			BadArgument(state, argumentId, "(" + expected + " expected, got " + actual + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string[] expected, string actual)
		{
			if (expected.Length == 0)
			{
				throw new ArgumentException("Expected array must not be empty", "expected");
			}
			BadArgument(state, argumentId, "(" + string.Join(" or ", expected) + " expected, got " + actual + ")");
		}

		public static void BadArgument(LuaState state, int argumentId, string message)
		{
			var (text, text2) = GetCurrentFunctionName(state);
			if (text == "method")
			{
				argumentId--;
				if (argumentId == 0)
				{
					throw new LuaRuntimeException(state, "calling '" + text2 + "' on bad self (" + message + ")");
				}
			}
			throw new LuaRuntimeException(state, $"bad argument #{argumentId} to '{text2}' ({message})");
		}

		public static void BadArgumentNumberIsNotInteger(LuaState state, int argumentId)
		{
			BadArgument(state, argumentId, "number has no integer representation");
		}

		public static void ThrowBadArgumentIfNumberIsNotInteger(LuaState state, int argumentId, double value)
		{
			if (!MathEx.IsInteger(value))
			{
				BadArgumentNumberIsNotInteger(state, argumentId);
			}
		}

		private static string CreateMessage(Traceback traceback, LuaValue errorObject, int level)
		{
			PooledList<char> list = new PooledList<char>(64);
			list.Clear();
			try
			{
				list.AddRange("Lua-CSharp: ");
				traceback.WriteLastLuaTrace(ref list, level);
				list.AddRange($"{errorObject}");
				return list.AsSpan().ToString();
			}
			finally
			{
				list.Dispose();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		Traceback? ILuaTracebackBuildable.BuildOrGet()
		{
			if (luaTraceback != null)
			{
				return luaTraceback;
			}
			if (State != null)
			{
				Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
				if (span.IsEmpty)
				{
					return null;
				}
				luaTraceback = new Traceback(State, span);
				State.ExceptionTrace.Clear();
				State = null;
			}
			return luaTraceback;
		}

		internal void Forget()
		{
			State?.ExceptionTrace.Clear();
			State = null;
		}

		internal string MinimalMessage()
		{
			string text = base.InnerException?.ToString() ?? ErrorObject.ToString();
			if (level <= 0)
			{
				return text;
			}
			if (luaTraceback == null)
			{
				if (State != null)
				{
					Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
					level = Math.Min(level, span.Length + 1);
					int num = level - 1;
					span = span.Slice(0, span.Length - num);
					if (span.IsEmpty)
					{
						return ErrorObject.ToString();
					}
					PooledList<char> list = new PooledList<char>(64);
					list.Clear();
					try
					{
						Traceback.WriteLastLuaTrace(span, ref list);
						list.AddRange(text);
						return list.AsSpan().ToString();
					}
					finally
					{
						list.Dispose();
					}
				}
				return text;
			}
			PooledList<char> list2 = new PooledList<char>(64);
			list2.Clear();
			try
			{
				luaTraceback.WriteLastLuaTrace(ref list2, level);
				list2.AddRange(text);
				return list2.AsSpan().ToString();
			}
			finally
			{
				list2.Dispose();
			}
		}

		public override string ToString()
		{
			if (LuaTraceback == null)
			{
				return base.ToString();
			}
			PooledList<char> pooledList = new PooledList<char>(64);
			pooledList.Clear();
			try
			{
				pooledList.AddRange(Message);
				char item = '\n';
				pooledList.Add(in item);
				pooledList.AddRange(LuaTraceback.ToString());
				item = '\n';
				pooledList.Add(in item);
				pooledList.AddRange(StackTrace);
				return pooledList.AsSpan().ToString();
			}
			finally
			{
				pooledList.Dispose();
			}
		}
	}
	public class LuaAssertionException : LuaRuntimeException
	{
		public LuaAssertionException(LuaState? traceback, string message)
			: base(traceback, message)
		{
		}
	}
	public class LuaModuleNotFoundException : Exception
	{
		public LuaModuleNotFoundException(string moduleName)
			: base("module '" + moduleName + "' not found")
		{
		}
	}
	public sealed class LuaCanceledException : OperationCanceledException, ILuaTracebackBuildable
	{
		private Traceback? luaTraceback;

		public Traceback? LuaTraceback
		{
			get
			{
				if (luaTraceback == null)
				{
					((ILuaTracebackBuildable)this).BuildOrGet();
				}
				return luaTraceback;
			}
		}

		internal LuaState? State { get; private set; }

		internal LuaCanceledException(LuaState state, CancellationToken cancellationToken, Exception? innerException = null)
			: base("The operation was cancelled during execution on Lua.", innerException, cancellationToken)
		{
			state.CurrentException?.BuildOrGet();
			state.ExceptionTrace.Clear();
			state.CurrentException = this;
			State = state;
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		Traceback? ILuaTracebackBuildable.BuildOrGet()
		{
			if (luaTraceback != null)
			{
				return luaTraceback;
			}
			if (State != null)
			{
				Span<CallStackFrame> span = State.ExceptionTrace.AsSpan();
				if (span.IsEmpty)
				{
					return null;
				}
				luaTraceback = new Traceback(State, span);
				State.ExceptionTrace.Clear();
				State = null;
			}
			return luaTraceback;
		}
	}
	public interface ILuaModuleLoader
	{
		bool Exists(string moduleName);

		ValueTask<LuaModule> LoadAsync(string moduleName, CancellationToken cancellationToken = default(CancellationToken));
	}
	internal static class EnumerableEx
	{
		[CompilerGenerated]
		private sealed class <GroupConsecutiveBy>d__0<T, TKey> : IEnumerable<IEnumerable<T>>, IEnumerable, IEnumerator<IEnumerable<T>>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private IEnumerable<T> <>2__current;

			private int <>l__initialThreadId;

			private IEnumerable<T> source;

			public IEnumerable<T> <>3__source;

			private Func<T, TKey> keySelector;

			public Func<T, TKey> <>3__keySelector;

			private IEnumerator<T> <enumerator>5__1;

			private List<T> <group>5__2;

			private TKey <previousKey>5__3;

			private TKey <currentKey>5__4;

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

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || (uint)(num - 1) <= 1u)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<enumerator>5__1 = null;
				<group>5__2 = null;
				<previousKey>5__3 = default(TKey);
				<currentKey>5__4 = default(TKey);
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				bool result;
				try
				{
					switch (<>1__state)
					{
					default:
						result = false;
						goto end_IL_0000;
					case 0:
						<>1__state = -1;
						if (source == null)
						{
							throw new ArgumentNullException("source");
						}
						if (keySelector == null)
						{
							throw new ArgumentNullException("keySelector");
						}
						<enumerator>5__1 = source.GetEnumerator();
						<>1__state = -3;
						if (!<enumerator>5__1.MoveNext())
						{
							result = false;
							break;
						}
						<group>5__2 = new List<T> { <enumerator>5__1.Current };
						<previousKey>5__3 = keySelector(<enumerator>5__1.Current);
						goto IL_0174;
					case 1:
						<>1__state = -3;
						<group>5__2 = new List<T>();
						goto IL_0144;
					case 2:
						{
							<>1__state = -3;
							result = false;
							break;
						}
						IL_0174:
						if (<enumerator>5__1.MoveNext())
						{
							<currentKey>5__4 = keySelector(<enumerator>5__1.Current);
							if (EqualityComparer<TKey>.Default.Equals(<previousKey>5__3, <currentKey>5__4))
							{
								goto IL_0144;
							}
							<>2__current = <group>5__2;
							<>1__state = 1;
							result = true;
						}
						else
						{
							<>2__current = <group>5__2;
							<>1__state = 2;
							result = true;
						}
						goto end_IL_0000;
						IL_0144:
						<group>5__2.Add(<enumerator>5__1.Current);
						<previousKey>5__3 = <currentKey>5__4;
						<currentKey>5__4 = default(TKey);
						goto IL_0174;
					}
					<>m__Finally1();
					end_IL_0000:;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
				return result;
			}

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

			private void <>m__Finally1()
			{
				<>1__state = -1;
				if (<enumerator>5__1 != null)
				{
					<enumerator>5__1.Dispose();
				}
			}

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

			[DebuggerHidden]
			IEnumerator<IEnumerable<T>> IEnumerable<IEnumerable<T>>.GetEnumerator()
			{
				<GroupConsecutiveBy>d__0<T, TKey> <GroupConsecutiveBy>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<GroupConsecutiveBy>d__ = this;
				}
				else
				{
					<GroupConsecutiveBy>d__ = new <GroupConsecutiveBy>d__0<T, TKey>(0);
				}
				<GroupConsecutiveBy>d__.source = <>3__source;
				<GroupConsecutiveBy>d__.keySelector = <>3__keySelector;
				return <GroupConsecutiveBy>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<IEnumerable<T>>)this).GetEnumerator();
			}
		}

		[IteratorStateMachine(typeof(<GroupConsecutiveBy>d__0<, >))]
		public static IEnumerable<IEnumerable<T>> GroupConsecutiveBy<T, TKey>(this IEnumerable<T> source, Func<T, TKey> keySelector)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GroupConsecutiveBy>d__0<T, TKey>(-2)
			{
				<>3__source = source,
				<>3__keySelector = keySelector
			};
		}
	}
	internal static class FarmHash
	{
		private struct Pair
		{
			public ulong first;

			public ulong second;

			public Pair(ulong first, ulong second)
			{
				this.first = first;
				this.second = second;
			}
		}

		private const ulong k0 = 14097894508562428199uL;

		private const ulong k1 = 13011662864482103923uL;

		private const ulong k2 = 11160318154034397263uL;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static ulong Hash64(byte[] bytes, int offset, int count)
		{
			fixed (byte* s = &bytes[offset])
			{
				return Hash64(s, (uint)count);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe static ulong Hash64(ReadOnlySpan<byte> bytes)
		{
			fixed (byte* s = &MemoryMarshal.GetReference(bytes))
			{
				return Hash64(s, (uint)bytes.Length);
			}
		}

		private unsafe static uint Fetch32(byte* p)
		{
			return *(uint*)p;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static Pair make_pair(ulong first, ulong second)
		{
			return new Pair(first, second);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void swap(ref ulong x, ref ulong z)
		{
			ulong num = z;
			z = x;
			x = num;
		}

		private unsafe static ulong Fetch64(byte* p)
		{
			return *(ulong*)p;
		}

		private static ulong Rotate64(ulong val, int shift)
		{
			return (shift == 0) ? val : ((val >> shift) | (val << 64 - shift));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong ShiftMix(ulong val)
		{
			return val ^ (val >> 47);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong HashLen16(ulong u, ulong v, ulong mul)
		{
			ulong num = (u ^ v) * mul;
			num ^= num >> 47;
			ulong num2 = (v ^ num) * mul;
			num2 ^= num2 >> 47;
			return num2 * mul;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64(byte* s, uint len)
		{
			if (len <= 16)
			{
				return HashLen0to16(s, len);
			}
			if (len <= 32)
			{
				return HashLen17to32(s, len);
			}
			if (len <= 64)
			{
				return HashLen33to64(s, len);
			}
			if (len <= 96)
			{
				return HashLen65to96(s, len);
			}
			if (len <= 256)
			{
				return Hash64NA(s, len);
			}
			return Hash64UO(s, len);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen0to16(byte* s, uint len)
		{
			switch (len)
			{
			default:
			{
				ulong num7 = (ulong)(-7286425919675154353L + len * 2);
				ulong num8 = Fetch64(s) + 11160318154034397263uL;
				ulong num9 = Fetch64(s + len - 8);
				ulong u = Rotate64(num9, 37) * num7 + num8;
				ulong v = (Rotate64(num8, 25) + num9) * num7;
				return HashLen16(u, v, num7);
			}
			case 4u:
			case 5u:
			case 6u:
			case 7u:
			{
				ulong mul = (ulong)(-7286425919675154353L + len * 2);
				ulong num6 = Fetch32(s);
				return HashLen16(len + (num6 << 3), Fetch32(s + len - 4), mul);
			}
			case 1u:
			case 2u:
			case 3u:
			{
				ushort num = *s;
				ushort num2 = s[len >> 1];
				ushort num3 = s[len - 1];
				uint num4 = (uint)(num + (num2 << 8));
				uint num5 = len + (uint)(num3 << 2);
				return ShiftMix((ulong)((num4 * -7286425919675154353L) ^ (num5 * -4348849565147123417L))) * 11160318154034397263uL;
			}
			case 0u:
				return 11160318154034397263uL;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen17to32(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154353L + len * 2);
			ulong num2 = Fetch64(s) * 13011662864482103923uL;
			ulong num3 = Fetch64(s + 8);
			ulong num4 = Fetch64(s + len - 8) * num;
			ulong num5 = Fetch64(s + len - 16) * 11160318154034397263uL;
			return HashLen16(Rotate64(num2 + num3, 43) + Rotate64(num4, 30) + num5, num2 + Rotate64(num3 + 11160318154034397263uL, 18) + num4, num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong H32(byte* s, uint len, ulong mul, ulong seed0 = 0uL, ulong seed1 = 0uL)
		{
			ulong num = Fetch64(s) * 13011662864482103923uL;
			ulong num2 = Fetch64(s + 8);
			ulong num3 = Fetch64(s + len - 8) * mul;
			ulong num4 = Fetch64(s + len - 16) * 11160318154034397263uL;
			ulong num5 = Rotate64(num + num2, 43) + Rotate64(num3, 30) + num4 + seed0;
			ulong num6 = num + Rotate64(num2 + 11160318154034397263uL, 18) + num3 + seed1;
			num = ShiftMix((num5 ^ num6) * mul);
			return ShiftMix((num6 ^ num) * mul);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen33to64(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154383L + 2 * len);
			ulong num2 = H32(s, 32u, 11160318154034397233uL, 0uL, 0uL);
			ulong num3 = H32(s + len - 32, 32u, num, 0uL, 0uL);
			return (num3 * num + num2) * num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong HashLen65to96(byte* s, uint len)
		{
			ulong num = (ulong)(-7286425919675154467L + 2 * len);
			ulong num2 = H32(s, 32u, 11160318154034397149uL, 0uL, 0uL);
			ulong num3 = H32(s + 32, 32u, num, 0uL, 0uL);
			ulong num4 = H32(s + len - 32, 32u, num, num2, num3);
			return (num4 * 9 + (num2 >> 17) + (num3 >> 21)) * num;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static Pair WeakHashLen32WithSeeds(ulong w, ulong x, ulong y, ulong z, ulong a, ulong b)
		{
			a += w;
			b = Rotate64(b + a + z, 21);
			ulong num = a;
			a += x;
			a += y;
			b += Rotate64(a, 44);
			return make_pair(a + z, b + num);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static Pair WeakHashLen32WithSeeds(byte* s, ulong a, ulong b)
		{
			return WeakHashLen32WithSeeds(Fetch64(s), Fetch64(s + 8), Fetch64(s + 16), Fetch64(s + 24), a, b);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64NA(byte* s, uint len)
		{
			ulong num = 81uL;
			ulong num2 = 2480279821605975764uL;
			ulong x = ShiftMix((ulong)((long)num2 * -7286425919675154353L + 113)) * 11160318154034397263uL;
			Pair pair = make_pair(0uL, 0uL);
			Pair pair2 = make_pair(0uL, 0uL);
			num = (ulong)((long)num * -7286425919675154353L) + Fetch64(s);
			byte* ptr = s + (len - 1) / 64 * 64;
			byte* ptr2 = ptr + ((len - 1) & 0x3F) - 63;
			do
			{
				num = Rotate64(num + num2 + pair.first + Fetch64(s + 8), 37) * 13011662864482103923uL;
				num2 = Rotate64(num2 + pair.second + Fetch64(s + 48), 42) * 13011662864482103923uL;
				num ^= pair2.second;
				num2 += pair.first + Fetch64(s + 40);
				x = Rotate64(x + pair2.first, 33) * 13011662864482103923uL;
				pair = WeakHashLen32WithSeeds(s, pair.second * 13011662864482103923uL, num + pair2.first);
				pair2 = WeakHashLen32WithSeeds(s + 32, x + pair2.second, num2 + Fetch64(s + 16));
				swap(ref x, ref num);
				s += 64;
			}
			while (s != ptr);
			ulong num3 = 13011662864482103923uL + ((x & 0xFF) << 1);
			s = ptr2;
			pair2.first += (len - 1) & 0x3F;
			pair.first += pair2.first;
			pair2.first += pair.first;
			num = Rotate64(num + num2 + pair.first + Fetch64(s + 8), 37) * num3;
			num2 = Rotate64(num2 + pair.second + Fetch64(s + 48), 42) * num3;
			num ^= pair2.second * 9;
			num2 += pair.first * 9 + Fetch64(s + 40);
			x = Rotate64(x + pair2.first, 33) * num3;
			pair = WeakHashLen32WithSeeds(s, pair.second * num3, num + pair2.first);
			pair2 = WeakHashLen32WithSeeds(s + 32, x + pair2.second, num2 + Fetch64(s + 16));
			swap(ref x, ref num);
			return HashLen16((ulong)((long)HashLen16(pair.first, pair2.first, num3) + (long)ShiftMix(num2) * -4348849565147123417L) + x, HashLen16(pair.second, pair2.second, num3) + num, num3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static ulong H(ulong x, ulong y, ulong mul, int r)
		{
			ulong num = (x ^ y) * mul;
			num ^= num >> 47;
			ulong val = (y ^ num) * mul;
			return Rotate64(val, r) * mul;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private unsafe static ulong Hash64UO(byte* s, uint len)
		{
			ulong num = 81uL;
			ulong num2 = 113uL;
			ulong z = ShiftMix(num2 * 11160318154034397263uL) * 11160318154034397263uL;
			Pair pair = make_pair(81uL, 0uL);
			Pair pair2 = make_pair(0uL, 0uL);
			ulong x = num - z;
			num *= 11160318154034397263uL;
			ulong num3 = 11160318154034397263uL + (x & 0x82);
			byte* ptr = s + (len - 1) / 64 * 64;
			byte* ptr2 = ptr + ((len - 1) & 0x3F) - 63;
			do
			{
				ulong num4 = Fetch64(s);
				ulong num5 = Fetch64(s + 8);
				ulong num6 = Fetch64(s + 16);
				ulong num7 = Fetch64(s + 24);
				ulong num8 = Fetch64(s + 32);
				ulong num9 = Fetch64(s + 40);
				ulong num10 = Fetch64(s + 48);
				ulong num11 = Fetch64(s + 56);
				num += num4 + num5;
				num2 += num6;
				z += num7;
				pair.first += num8;
				pair.second += num9 + num5;
				pair2.first += num10;
				pair2.second += num11;
				num = Rotate64(num, 26);
				num *= 9;
				num2 = Rotate64(num2, 29);
				z *= num3;
				pair.first = Rotate64(pair.first, 33);
				pair.second = Rotate64(pair.second, 30);
				pair2.first ^= num;
				pair2.first *= 9uL;
				z = Rotate64(z, 32);
				z += pair2.second;
				pair2.second += z;
				z *= 9;
				swap(ref x, ref num2);
				z += num4 + num10;
				pair.first += num6;
				pair.second += num7;
				pair2.first += num8;
				pair2.second += num9 + num10;
				num += num5;
				num2 += num11;
				num2 += pair.first;
				pair.first += num - num2;
				pair.second += pair2.first;
				pair2.first += pair.second;
				pair2.second += num - num2;
				num += pair2.second;
				pair2.second = Rotate64(pair2.second, 34);
				swap(ref x, ref z);
				s += 64;
			}
			while (s != ptr);
			s = ptr2;
			x *= 9;
			pair.second = Rotate64(pair.second, 28);
			pair.first = Rotate64(pair.first, 20);
			pair2.first += (len - 1) & 0x3F;
			x += num2;
			num2 += x;
			num = Rotate64(num2 - num + pair.first + Fetch64(s + 8), 37) * num3;
			num2 = Rotate64(num2 ^ pair.second ^ Fetch64(s + 48), 42) * num3;
			num ^= pair2.second * 9;
			num2 += pair.first + Fetch64(s + 40);
			z = Rotate64(z + pair2.first, 33) * num3;
			pair = WeakHashLen32WithSeeds(s, pair.second * num3, num + pair2.first);
			pair2 = WeakHashLen32WithSeeds(s + 32, z + pair2.second, num2 + Fetch64(s + 16));
			return H(HashLen16(pair.first + num, pair2.first ^ num2, num3) + z - x, H(pair.second + num2, pair2.second + z, 11160318154034397263uL, 30) ^ num, 11160318154034397263uL, 31);
		}
	}
	internal sealed class LuaGlobalState
	{
		private readonly LuaState mainState;

		private FastStackCore<LuaState> stateStack;

		private readonly LuaTable environment;

		private readonly LuaTable registry = new LuaTable();

		private readonly UpValue envUpValue;

		private FastStackCore<LuaDebug.LuaDebugBuffer> debugBufferPool;

		private LuaTable? nilMetatable;

		private LuaTable? numberMetatable;

		private LuaTable? stringMetatable;

		private LuaTable? booleanMetatable;

		private LuaTable? functionMetatable;

		private LuaTable? stateMetatable;

		internal UpValue EnvUpValue => envUpValue;

		internal ref FastStackCore<LuaState> ThreadStack => ref stateStack;

		internal ref FastStackCore<LuaDebug.LuaDebugBuffer> DebugBufferPool => ref debugBufferPool;

		public LuaTable Environment => environment;

		public LuaTable Registry => registry;

		public LuaTable LoadedModules => registry["_LOADED"].Read<LuaTable>();

		public LuaTable PreloadModules => registry["_PRELOAD"].Read<LuaTable>();

		public LuaState MainThread => mainState;

		public LuaPlatform Platform { get; set; }

		public ILuaModuleLoader? ModuleLoader { get; set; }

		public static LuaGlobalState Create(LuaPlatform? platform = null)
		{
			return new LuaGlobalState(platform ?? LuaPlatform.Default);
		}

		private LuaGlobalState(LuaPlatform platform)
		{
			mainState = new LuaState(this);
			environment = new LuaTable();
			envUpValue = UpValue.Closed(environment);
			registry["_LOADED"] = new LuaTable(0, 8);
			registry["_PRELOAD"] = new LuaTable(0, 8);
			Platform = platform;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryGetMetatable(LuaValue value, [NotNullWhen(true)] out LuaTable? result)
		{
			LuaValueType type = value.Type;
			if (1 == 0)
			{
			}
			LuaTable luaTable = type switch
			{
				LuaValueType.Nil => nilMetatable, 
				LuaValueType.Boolean => booleanMetatable, 
				LuaValueType.String => stringMetatable, 
				LuaValueType.Number => numberMetatable, 
				LuaValueType.Function => functionMetatable, 
				LuaValueType.Thread => stateMetatable, 
				LuaValueType.UserData => value.UnsafeRead<ILuaUserData>().Metatable, 
				LuaValueType.Table => value.UnsafeRead<LuaTable>().Metatable, 
				_ => null, 
			};
			if (1 == 0)
			{
			}
			result = luaTable;
			return result != null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void SetMetatable(LuaValue value, LuaTable metatable)
		{
			switch (value.Type)
			{
			case LuaValueType.Nil:
				nilMetatable = metatable;
				break;
			case LuaValueType.Boolean:
				booleanMetatable = metatable;
				break;
			case LuaValueType.String:
				stringMetatable = metatable;
				break;
			case LuaValueType.Number:
				numberMetatable = metatable;
				break;
			case LuaValueType.Function:
				functionMetatable = metatable;
				break;
			case LuaValueType.Thread:
				stateMetatable = metatable;
				break;
			case LuaValueType.UserData:
				value.UnsafeRead<ILuaUserData>().Metatable = metatable;
				break;
			case LuaValueType.Table:
				value.UnsafeRead<LuaTable>().Metatable = metatable;
				break;
			case LuaValueType.LightUserData:
				break;
			}
		}
	}
	internal static class MathEx
	{
		private const ulong PositiveInfinityBits = 9218868437227405312uL;

		public const int ArrayMexLength = 2147483591;

		private const long DBL_EXP_MASK = 9218868437227405312L;

		private const int DBL_MANT_BITS = 52;

		private const long DBL_SGN_MASK = long.MinValue;

		private const long DBL_MANT_MASK = 4503599627370495L;

		private const long DBL_EXP_CLR_MASK = -9218868437227405313L;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsInteger(double d)
		{
			return IsFinite(d) && d == Math.Truncate(d);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsFinite(double d)
		{
			ulong num = BitCast<double, ulong>(d);
			return (~num & 0x7FF0000000000000L) != 0;
		}

		private static TTo BitCast<TFrom, TTo>(TFrom source)
		{
			return Unsafe.ReadUnaligned<TTo>(ref Unsafe.As<TFrom, byte>(ref source));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int NewArrayCapacity(int size)
		{
			int num = size * 2;
			if ((uint)num > 2147483591u)
			{
				num = 2147483591;
			}
			return num;
		}

		public static (double m, int e) Frexp(double d)
		{
			long num = BitConverter.DoubleToInt64Bits(d);
			int num2 = (int)((num & 0x7FF0000000000000L) >> 52);
			int item = 0;
			if (num2 == 2047 || d == 0.0)
			{
				d += d;
			}
			else
			{
				item = num2 - 1022;
				if (num2 == 0)
				{
					d *= BitConverter.Int64BitsToDouble(4850376798678024192L);
					num = BitConverter.DoubleToInt64Bits(d);
					num2 = (int)((num & 0x7FF0000000000000L) >> 52);
					item = num2 - 1022 - 54;
				}
				d = BitConverter.Int64BitsToDouble((num & -9218868437227405313L) | 0x3FE0000000000000L);
			}
			return (d, item);
		}

		public static (int i, double f) Modf(double d)
		{
			return ((int)Math.Truncate(d), d % 1.0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int NextPowerOfTwo(int x)
		{
			if (x <= 0)
			{
				return 0;
			}
			x--;
			x |= x >> 1;
			x |= x >> 2;
			x |= x >> 4;
			x |= x >> 8;
			x |= x >> 16;
			return x + 1;
		}
	}
	public class LuaFunction
	{
		public string Name { get; }

		internal Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> Func { get; }

		public LuaFunction(string name, Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)
		{
			Name = name;
			Func = func;
			base..ctor();
		}

		public LuaFunction(Func<LuaFunctionExecutionContext, CancellationToken, ValueTask<int>> func)
			: this("anonymous", func)
		{
		}
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly record struct LuaFunctionExecutionContext
	{
		internal LuaGlobalState GlobalState => State.GlobalState;

		public LuaState State { get; init; }

		public required int ArgumentCount { get; init; }

		public int FrameBase => State.Stack.Count - ArgumentCount;

		public required int ReturnFrameBase { get; init; }

		public ReadOnlySpan<LuaValue> Arguments
		{
			get
			{
				Span<LuaValue> span = State.Stack.AsSpan();
				return span.Slice(span.Length - ArgumentCount);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool HasArgument(int index)
		{
			return ArgumentCount > index && Arguments[index].Type != LuaValueType.Nil;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public LuaValue GetArgument(int index)
		{
			ThrowIfArgumentNotExists(index);
			return Arguments[index];
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal LuaValue GetArgumentOrDefault(int index, LuaValue defaultValue = default(LuaValue))
		{
			if (ArgumentCount <= index)
			{
				return defaultValue;
			}
			return Arguments[index];
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public T GetArgument<T>(int index)
		{
			ThrowIfArgumentNotExists(index);
			LuaValue luaValue = Arguments[index];
			if (!luaValue.TryRead<T>(out var result))
			{
				Type typeFromHandle = typeof(T);
				LuaValueType result3;
				if ((typeFromHandle == typeof(int) || typeFromHandle == typeof(long)) && luaValue.TryReadNumber(out var _))
				{
					LuaRuntimeException.BadArgumentNumberIsNotInteger(State, index + 1);
				}
				else if (LuaValue.TryGetLuaValueType(typeFromHandle, out result3))
				{
					LuaRuntimeException.BadArgument(State, index + 1, result3, luaValue.Type);
				}
				else
				{
					LuaValueType type = luaValue.Type;
					if (type - 6 <= LuaValueType.Boolean)
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.UnsafeRead<object>()?.GetType().ToString() ?? "userdata: 0");
					}
					else
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.TypeToString());
					}
				}
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal T GetArgumentOrDefault<T>(int index, T defaultValue = default(T))
		{
			if (ArgumentCount <= index)
			{
				return defaultValue;
			}
			LuaValue luaValue = Arguments[index];
			if (luaValue.Type == LuaValueType.Nil)
			{
				return defaultValue;
			}
			if (!luaValue.TryRead<T>(out var result))
			{
				Type typeFromHandle = typeof(T);
				LuaValueType result3;
				if ((typeFromHandle == typeof(int) || typeFromHandle == typeof(long)) && luaValue.TryReadNumber(out var _))
				{
					LuaRuntimeException.BadArgumentNumberIsNotInteger(State, index + 1);
				}
				else if (LuaValue.TryGetLuaValueType(typeFromHandle, out result3))
				{
					LuaRuntimeException.BadArgument(State, index + 1, result3, luaValue.Type);
				}
				else
				{
					LuaValueType type = luaValue.Type;
					if (type - 6 <= LuaValueType.Boolean)
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.UnsafeRead<object>()?.GetType().ToString() ?? "userdata: 0");
					}
					else
					{
						LuaRuntimeException.BadArgument(State, index + 1, typeFromHandle.Name, luaValue.TypeToString());
					}
				}
			}
			return result;
		}

		public int Return()
		{
			State.Stack.PopUntil(ReturnFrameBase);
			return 0;
		}

		public int Return(LuaValue result)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 1);
			stack.FastGet(ReturnFrameBase) = result;
			return 1;
		}

		public int Return(LuaValue result0, LuaValue result1)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 2);
			stack.FastGet(ReturnFrameBase) = result0;
			stack.FastGet(ReturnFrameBase + 1) = result1;
			return 2;
		}

		public int Return(LuaValue result0, LuaValue result1, LuaValue result2)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + 3);
			stack.FastGet(ReturnFrameBase) = result0;
			stack.FastGet(ReturnFrameBase + 1) = result1;
			stack.FastGet(ReturnFrameBase + 2) = result2;
			return 3;
		}

		public int Return(ReadOnlySpan<LuaValue> results)
		{
			LuaStack stack = State.Stack;
			stack.EnsureCapacity(ReturnFrameBase + results.Length);
			Span<LuaValue> buffer = stack.GetBuffer();
			int returnFrameBase = ReturnFrameBase;
			results.CopyTo(buffer.Slice(returnFrameBase, ReturnFrameBase + results.Length - returnFrameBase));
			stack.SetTop(ReturnFrameBase + results.Length);
			return results.Length;
		}

		internal int Return(LuaValue result0, ReadOnlySpan<LuaValue> results)
		{
			LuaStack stack = State.Stack;
			stack.EnsureCapacity(ReturnFrameBase + results.Length);
			stack.SetTop(ReturnFrameBase + results.Length + 1);
			Span<LuaValue> buffer = stack.GetBuffer();
			buffer[ReturnFrameBase] = result0;
			int num = ReturnFrameBase + 1;
			results.CopyTo(buffer.Slice(num, ReturnFrameBase + results.Length + 1 - num));
			return results.Length + 1;
		}

		public Span<LuaValue> GetReturnBuffer(int count)
		{
			LuaStack stack = State.Stack;
			stack.SetTop(ReturnFrameBase + count);
			Span<LuaValue> buffer = stack.GetBuffer();
			int returnFrameBase = ReturnFrameBase;
			return buffer.Slice(returnFrameBase, ReturnFrameBase + count - returnFrameBase);
		}

		public CSharpClosure? GetCsClosure()
		{
			return State.GetCurrentFrame().Function as CSharpClosure;
		}

		internal void ThrowBadArgument(int index, string message)
		{
			LuaRuntimeException.BadArgument(State, index, State.GetCurrentFrame().Function.Name, message);
		}

		private void ThrowIfArgumentNotExists(int index)
		{
			if (ArgumentCount <= index)
			{
				LuaRuntimeException.BadArgument(State, index + 1);
			}
		}

		[CompilerGenerated]
		private bool PrintMembers(StringBuilder builder)
		{
			builder.Append("State = ");
			builder.Append(State);
			builder.Append(", ArgumentCount = ");
			builder.Append(ArgumentCount.ToString());
			builder.Append(", FrameBase = ");
			builder.Append(FrameBase.ToString());
			builder.Append(", ReturnFrameBase = ");
			builder.Append(ReturnFrameBase.ToString());
			builder.Append(", Arguments = ");
			builder.Append(Arguments.ToString());
			return true;
		}
	}
	public enum LuaModuleType
	{
		Text,
		Bytes
	}
	public readonly struct LuaModule
	{
		private readonly string name;

		private readonly LuaModuleType type;

		private readonly ReadOnlyMemory<char> text;

		private readonly ReadOnlyMemory<byte> bytes;

		public string Name => name;

		public LuaModuleType Type => type;

		public LuaModule(string name, ReadOnlyMemory<char> text)
		{
			bytes = default(ReadOnlyMemory<byte>);
			this.name = name;
			type = LuaModuleType.Text;
			this.text = text;
		}

		public LuaModule(string name, ReadOnlyMemory<byte> bytes)
		{
			text = default(ReadOnlyMemory<char>);
			this.name = name;
			type = LuaModuleType.Bytes;
			this.bytes = bytes;
		}

		public LuaModule(string name, string text)
			: this(name, text.AsMemory())
		{
		}

		public LuaModule(string name, byte[] bytes)
			: this(name, new ReadOnlyMemory<byte>(bytes))
		{
		}

		public ReadOnlySpan<char> ReadText()
		{
			if (type != 0)
			{
				throw new Exception();
			}
			return text.Span;
		}

		public ReadOnlySpan<byte> ReadBytes()
		{
			if (type != LuaModuleType.Bytes)
			{
				throw new Exception();
			}
			return bytes.Span;
		}
	}
	public enum LuaObjectMetamethod
	{
		Add,
		Sub,
		Mul,
		Div,
		Mod,
		Pow,
		Unm,
		Len,
		Eq,
		Lt,
		Le,
		Call,
		Concat,
		Pairs,
		IPairs,
		ToString
	}
	public class LuaState : IDisposable
	{
		private class ThreadCoreData : IPoolNode<ThreadCoreData>
		{
			internal readonly LuaStack Stack = new LuaStack();

			internal FastStackCore<CallStackFrame> CallStack;

			private static LinkedPool<ThreadCoreData> pool;

			private ThreadCoreData? nextNode;

			public ref ThreadCoreData? NextNode => ref nextNode;

			private void Clear()
			{
				Stack.Clear();
				CallStack.Clear();
			}

			public static ThreadCoreData Create()
			{
				if (!pool.TryPop(out ThreadCoreData result))
				{
					return new ThreadCoreData();
				}
				return result;
			}

			public void Release()
			{
				Clear();
				pool.TryPush(this);
			}
		}

		private FastListCore<UpValue> openUpValues;

		internal int CallCount;

		private ThreadCoreData? CoreData;

		private CoroutineCore? coroutine;

		internal bool IsLineHookEnabled;

		internal BitFlags2 CallOrReturnHookMask;

		internal bool IsInHook;

		internal long HookCount;

		internal int BaseHookCount;

		internal int LastPc;

		internal ILuaTracebackBuildable? CurrentException;

		internal readonly ReversedStack<CallStackFrame> ExceptionTrace = new ReversedStack<CallStackFrame>();

		internal LuaFunction? LastCallerFunction;

		internal LuaGlobalState GlobalState { get; }

		internal ref FastListCore<UpValue> OpenUpValues => ref openUpValues;

		public bool IsRunning => CallStackFrameCount != 0;

		public bool IsCoroutine => coroutine != null;

		internal LuaFunction? Hook { get; set; }

		public LuaFunction? CoroutineFunction => coroutine?.Function;

		public bool CanResume => GetStatus() == LuaThreadStatus.Suspended;

		public LuaStack Stack => CoreData.Stack;

		internal Traceback? LuaTraceback => coroutine?.Traceback;

		public LuaTable Environment => GlobalState.Environment;

		public LuaTable Registry => GlobalState.Registry;

		public LuaTable LoadedModules => GlobalState.LoadedModules;

		public LuaTable PreloadModules => GlobalState.PreloadModules;

		public LuaState MainThread => GlobalState.MainThread;

		public ILuaModuleLoader? ModuleLoader
		{
			get
			{
				return GlobalState.ModuleLoader;
			}
			set
			{
				GlobalState.ModuleLoader = value;
			}
		}

		public LuaPlatform Platform
		{
			get
			{
				return GlobalState.Platform;
			}
			set
			{
				GlobalState.Platform = value;
			}
		}

		internal bool IsCallHookEnabled
		{
			get
			{
				return CallOrReturnHookMask.Flag0;
			}
			set
			{
				CallOrReturnHookMask.Flag0 = value;
			}
		}

		internal bool IsReturnHookEnabled
		{
			get
			{
				return CallOrReturnHookMask.Flag1;
			}
			set
			{
				CallOrReturnHookMask.Flag1 = value;
			}
		}

		public int CallStackFrameCount => (CoreData != null) ? CoreData.CallStack.Count : 0;

		internal LuaState(LuaGlobalState globalState)
		{
			GlobalState = globalState;
			CoreData = ThreadCoreData.Create();
		}

		internal LuaState(LuaGlobalState globalState, LuaFunction function, bool isProtectedMode)
		{
			GlobalState = globalState;
			CoreData = ThreadCoreData.Create();
			coroutine = new CoroutineCore(this, function, isProtectedMode);
		}

		public static LuaState Create()
		{
			LuaGlobalState luaGlobalState = LuaGlobalState.Create();
			return luaGlobalState.MainThread;
		}

		public static LuaState Create(LuaPlatform platform)
		{
			return LuaGlobalState.Create(platform).MainThread;
		}

		internal static LuaState CreateCoroutine(LuaGlobalState globalState, LuaFunction function, bool isProtectedMode = false)
		{
			return new LuaState(globalState, function, isProtectedMode);
		}

		public LuaState CreateThread()
		{
			return new LuaState(GlobalState);
		}

		public LuaState CreateCoroutine(LuaFunction function, bool isProtectedMode = false)
		{
			return new LuaState(GlobalState, function, isProtectedMode);
		}

		public LuaThreadStatus GetStatus()
		{
			if (coroutine != null)
			{
				return (LuaThreadStatus)coroutine.status;
			}
			return LuaThreadStatus.Running;
		}

		public void UnsafeSetStatus(LuaThreadStatus status)
		{
			if (coroutine != null)
			{
				coroutine.status = (byte)status;
			}
		}

		public ValueTask<int> ResumeAsync(LuaFunctionExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.ResumeAsyncCore(context.State.Stack, context.ArgumentCount, context.ReturnFrameBase, context.State, cancellationToken);
			}
			return new ValueTask<int>(context.Return(false, "cannot resume non-suspended coroutine"));
		}

		public ValueTask<int> ResumeAsync(LuaStack stack, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.ResumeAsyncCore(stack, stack.Count, 0, null, cancellationToken);
			}
			stack.Push(false);
			stack.Push("cannot resume non-suspended coroutine");
			return new ValueTask<int>(2);
		}

		public ValueTask<int> YieldAsync(LuaFunctionExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.YieldAsyncCore(context.State.Stack, context.ArgumentCount, context.ReturnFrameBase, context.State, cancellationToken);
			}
			throw new LuaRuntimeException(context.State, "cannot yield from a non-running coroutine");
		}

		public ValueTask<int> YieldAsync(LuaStack stack, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (coroutine != null)
			{
				return coroutine.YieldAsyncCore(stack, stack.Count, 0, null, cancellationToken);
			}
			throw new LuaRuntimeException(null, "cannot yield from a non-running coroutine");
		}

		public ref readonly CallStackFrame GetCurrentFrame()
		{
			return ref CoreData.CallStack.PeekRef();
		}

		public ReadOnlySpan<LuaValue> GetStackValues()
		{
			return (CoreData == null) ? default(Span<LuaValue>) : CoreData.Stack.AsSpan();
		}

		public ReadOnlySpan<CallStackFrame> GetCallStackFrames()
		{
			return (CoreData == null) ? default(Span<CallStackFrame>) : CoreData.CallStack.AsSpan();
		}

		internal CallStackFrame CreateCallStackFrame(LuaFunction function, int argumentCount, int returnBase, int callerInstructionIndex)
		{
			int num = function.GetVariableArgumentCount(argumentCount);
			if (num != 0)
			{
				if (num < 0)
				{
					Stack.SetTop(Stack.Count - num);
					argumentCount -= num;
					num = 0;
				}
				else
				{
					LuaVirtualMachine.PrepareVariableArgument(Stack, argumentCount, num);
				}
			}
			CallStackFrame callStackFrame = default(CallStackFrame);
			callStackFrame.Base = Stack.Count - argumentCount;
			callStackFrame.VariableArgumentCount = num;
			callStackFrame.Function = function;
			callStackFrame.ReturnBase = returnBase;
			callStackFrame.CallerInstructionIndex = callerInstructionIndex;
			CallStackFrame result = callStackFrame;
			if (IsInHook)
			{
				result.Flags |= CallStackFrameFlags.InHook;
			}
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PushCallStackFrame(in CallStackFrame frame)
		{
			CurrentException?.BuildOrGet();
			CurrentException = null;
			CoreData.CallStack.Push(in frame);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameWithStackPop()
		{
			ThreadCoreData coreData = CoreData;
			CallStackFrame element = coreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
			coreData.Stack.PopUntil(element.ReturnBase);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameWithStackPop(int frameBase)
		{
			ThreadCoreData coreData = CoreData;
			CallStackFrame element = coreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
			coreData.Stack.PopUntil(frameBase);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrame()
		{
			ThreadCoreData coreData = CoreData;
			CallStackFrame element = coreData.CallStack.Pop();
			if (CurrentException != null)
			{
				ExceptionTrace.Push(element);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal void PopCallStackFrameUntil(int top)
		{
			ThreadCoreData coreData = CoreData;
			ref FastStackCore<CallStackFrame> callStack = ref coreData.CallStack;
			if (CurrentException != null)
			{
				ReversedStack<CallStackFrame> exceptionTrace = ExceptionTrace;
				Span<CallStackFrame> span = callStack.AsSpan();
				exceptionTrace.Push(span.Slice(top, span.Length - top));
			}
			callStack.PopUntil(top);
		}

		public void SetHook(LuaFunction? hook, string mask, int count = 0)
		{
			if (hook == null)
			{
				HookCount = 0L;
				BaseHookCount = 0;
				Hook = null;
				IsLineHookEnabled = false;
				IsCallHookEnabled = false;
				IsReturnHookEnabled = false;
				return;
			}
			HookCount = ((count > 0) ? (count + 1) : 0);
			BaseHookCount = count;
			IsLineHookEnabled = mask.Contains('l');
			IsCallHookEnabled = mask.Contains('c');
			IsReturnHookEnabled = mask.Contains('r');
			if (IsLineHookEnabled)
			{
				LastPc = ((CallStackFrameCount > 0) ? GetCurrentFrame().CallerInstructionIndex : (-1));
			}
			Hook = hook;
		}

		internal void DumpStackValues()
		{
			ReadOnlySpan<LuaValue> stackValues = GetStackValues();
			for (int i = 0; i < stackValues.Length; i++)
			{
				Console.WriteLine($"LuaStack [{i}]\t{stackValues[i]}");
			}
		}

		public Traceback GetTraceback()
		{
			return new Traceback(this, GetCallStackFrames());
		}

		public ValueTask<int> RunAsync(LuaFunction function, CancellationToken cancellationToken = default(CancellationToken))
		{
			return RunAsync(function, 0, Stack.Count, cancellationToken);
		}

		public ValueTask<int> RunAsync(LuaFunction function, int argumentCount, CancellationToken cancellationToken = default(CancellationToken))
		{
			return RunAsync(function, argumentCount, Stack.Count - argumentCount, cancellationToken);
		}

		public async ValueTask<int> RunAsync(LuaFunction function, int argumentCount, int returnBase, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (function == null)
			{
				throw new ArgumentNullException("function");
			}
			this.ThrowIfCancellationRequested(cancellationToken);
			LuaState state = this;
			int varArgumentCount = function.GetVariableArgumentCount(argumentCount);
			if (varArgumentCount != 0)
			{
				if (varArgumentCount < 0)
				{
					state.Stack.SetTop(state.Stack.Count - varArgumentCount);
					varArgumentCount = 0;
				}
				else
				{
					LuaVirtualMachine.PrepareVariableArgument(state.Stack, argumentCount, varArgumentCount);
				}
				argumentCount -= varArgumentCount;
			}
			CallStackFrame frame = new CallStackFrame
			{
				Base = state.Stack.Count - argumentCount,
				VariableArgumentCount = varArgumentCount,
				Function = function,
				ReturnBase = returnBase
			};
			if (state.IsInHook)
			{
				frame.Flags |= CallStackFrameFlags.InHook;
			}
			state.PushCallStackFrame(in frame);
			LuaFunctionExecutionContext context = new LuaFunctionExecutionContext
			{
				State = state,
				ArgumentCount = argumentCount,
				ReturnFrameBase = returnBase
			};
			int callStackTop = state.CallStackFrameCount;
			try
			{
				if (CallOrReturnHookMask.Value != 0 && !IsInHook)
				{
					return await LuaVirtualMachine.ExecuteCallHook(context, cancellationToken);
				}
				return await function.Func(context, cancellationToken);
			}
			finally
			{
				PopCallStackFrameUntil(callStackTop - 1);
			}
		}

		public unsafe LuaClosure Load(ReadOnlySpan<char> chunk, string chunkName, LuaTable? environment = null)
		{
			Prototype proto;
			fixed (char* ptr = chunk)
			{
				proto = Lua.CodeAnalysis.Compilation.Parser.Parse(this, new Lua.CodeAnalysis.Compilation.TextReader(ptr, chunk.Length), chunkName);
			}
			return new LuaClosure(this, proto, environment);
		}

		public LuaClosure Load(ReadOnlySpan<byte> chunk, string? chunkName = null, string mode = "bt", LuaTable? environment = null)
		{
			if (chunk.Length > 4 && chunk[0] == 27)
			{
				return new LuaClosure(this, Lua.CodeAnalysis.Compilation.Parser.UnDump(chunk, chunkName), environment);
			}
			chunk = BomUtility.GetEncodingFromBytes(chunk, out Encoding encoding);
			int charCount = encoding.GetCharCount(chunk);
			char[] array = ArrayPool<char>.Shared.Rent(charCount);
			try
			{
				Span<char> span = array.AsSpan(0, charCount);
				encoding.GetChars(chunk, span);
				if (chunkName == null)
				{
					chunkName = span.ToString();
				}
				return Load(span, chunkName, environment);
			}
			finally
			{
				ArrayPool<char>.Shared.Return(array);
			}
		}

		internal UpValue GetOrAddUpValue(int registerIndex)
		{
			Span<UpValue> span = openUpValues.AsSpan();
			for (int i = 0; i < span.Length; i++)
			{
				UpValue upValue = span[i];
				if (upValue.RegisterIndex == registerIndex)
				{
					return upValue;
				}
			}
			UpValue upValue2 = UpValue.Open(this, registerIndex);
			openUpValues.Add(upValue2);
			return upValue2;
		}

		internal void CloseUpValues(int frameBase)
		{
			for (int i = 0; i < openUpValues.Length; i++)
			{
				UpValue upValue = openUpValues[i];
				if (upValue.RegisterIndex >= frameBase)
				{
					upValue.Close();
					openUpValues.RemoveAtSwapBack(i);
					i--;
				}
			}
		}

		public void Dispose()
		{
			if (CoreData.CallStack.Count != 0)
			{
				throw new InvalidOperationException("This state is running! Call stack is not empty!!");
			}
			CoreData.Release();
			CoreData = null;
		}
	}
	public static class LuaStateExtensions
	{
		public static async ValueTask<LuaClosure> LoadFileAsync(this LuaState state, string fileName, string mode, LuaTable? environment, CancellationToken cancellationToken)
		{
			string name = "@" + fileName;
			using ILuaStream stream = await state.GlobalState.Platform.FileSystem.Open(fileName, LuaFileOpenMode.Read, cancellationToken);
			return state.Load(await stream.ReadAllAsync(cancellationToken), name, environment);
		}

		public static ValueTask<int> DoStringAsync(this LuaState state, string source, Memory<LuaValue> results, string? chunkName = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName ?? source);
			return state.ExecuteAsync(closure, results, cancellationToken);
		}

		public static ValueTask<LuaValue[]> DoStringAsync(this LuaState state, string source, string? chunkName = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName ?? source);
			return state.ExecuteAsync(closure, cancellationToken);
		}

		public static ValueTask<int> ExecuteAsync(this LuaState state, ReadOnlySpan<byte> source, Memory<LuaValue> results, string chunkName, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName);
			return state.ExecuteAsync(closure, results, cancellationToken);
		}

		public static ValueTask<LuaValue[]> ExecuteAsync(this LuaState state, ReadOnlySpan<byte> source, string chunkName, CancellationToken cancellationToken = default(CancellationToken))
		{
			LuaClosure closure = state.Load(source, chunkName);
			return state.ExecuteAsync(closure, cancellationToken);
		}

		public static async ValueTask<int> DoFileAsync(this LuaState state, string path, Memory<LuaValue> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			using LuaTopValuesReader results = state.ReadTopValues(await state.RunAsync(await state.LoadFileAsync(path, "bt", null, cancellationToken), 0, cancellationToken));
			results.AsSpan().Slice(0, Math.Min(buffer.Length, results.Length)).CopyTo(buffer.Span);
			return results.Count;
		}

		public static async ValueTask<LuaValue[]> DoFileAsync(this LuaState state, string path, CancellationToken cancellationToken = default(CancellationToken))
		{
			using LuaTopValuesReader results = state.ReadTopValues(await state.RunAsync(await state.LoadFileAsync(path, "bt", null, cancellationToken), 0, cancellationToken));
			return results.AsSpan().ToArray();
		}

		public static async ValueTask<int> ExecuteAsync(this LuaState state, LuaClosure closure, Memory<LuaValue> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			using LuaTopValuesReader results = state.ReadTopValues(await state.RunAsync(closure, 0, cancellationToken));
			results.AsSpan().Slice(0, Math.Min(buffer.Length, results.Length)).CopyTo(buffer.Span);
			return results.Count;
		}

		public static async ValueTask<LuaValue[]> ExecuteAsync(this LuaState state, LuaClosure closure, CancellationToken cancellationToken = default(CancellationToken))
		{
			using LuaTopValuesReader results = state.ReadTopValues(await state.RunAsync(closure, 0, cancellationToken));
			return results.AsSpan().ToArray();
		}

		public static void Push(this LuaState state, LuaValue value)
		{
			state.Stack.Push(value);
		}

		public static void Push(this LuaState state, [ParamCollection] scoped ReadOnlySpan<LuaValue> span)
		{
			state.Stack.PushRange(span);
		}

		public static void Pop(this LuaState state, int count)
		{
			state.Stack.Pop(count);
		}

		public static LuaValue Pop(this LuaState state)
		{
			return state.Stack.Pop();
		}

		public static LuaTopValuesReader ReadTopValues(this LuaState state, int argumentCount)
		{
			LuaStack stack = state.Stack;
			return new LuaTopValuesReader(stack, stack.Count - argumentCount);
		}

		public static ValueTask<LuaValue> Add(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result + result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Add, cancellationToken);
		}

		public static ValueTask<LuaValue> Sub(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result - result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Sub, cancellationToken);
		}

		public static ValueTask<LuaValue> Mul(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result * result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Mul, cancellationToken);
		}

		public static ValueTask<LuaValue> Div(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(result / result2);
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Div, cancellationToken);
		}

		public static ValueTask<LuaValue> Mod(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(LuaVirtualMachine.Mod(result, result2));
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Mod, cancellationToken);
		}

		public static ValueTask<LuaValue> Pow(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadDouble(out var result) && y.TryReadDouble(out var result2))
			{
				return new ValueTask<LuaValue>(Math.Pow(result, result2));
			}
			return LuaVirtualMachine.ExecuteBinaryOperationMetaMethod(state, x, y, OpCode.Pow, cancellationToken);
		}

		public static ValueTask<LuaValue> Unm(this LuaState state, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (value.TryReadDouble(out var result))
			{
				return new ValueTask<LuaValue>(0.0 - result);
			}
			return LuaVirtualMachine.ExecuteUnaryOperationMetaMethod(state, value, OpCode.Unm, cancellationToken);
		}

		public static ValueTask<LuaValue> Len(this LuaState state, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (value.TryReadString(out string result))
			{
				return new ValueTask<LuaValue>(result.Length);
			}
			if (value.TryReadTable(out LuaTable result2))
			{
				return new ValueTask<LuaValue>(result2.ArrayLength);
			}
			return LuaVirtualMachine.ExecuteUnaryOperationMetaMethod(state, value, OpCode.Len, cancellationToken);
		}

		public static ValueTask<bool> LessThan(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadNumber(out var result) && y.TryReadNumber(out var result2))
			{
				return new ValueTask<bool>(result < result2);
			}
			if (x.TryReadString(out string result3) && y.TryReadString(out string result4))
			{
				int num = StringComparer.Ordinal.Compare(result3, result4);
				return new ValueTask<bool>(num < 0);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Lt, cancellationToken);
		}

		public static ValueTask<bool> LessThanOrEquals(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x.TryReadNumber(out var result) && y.TryReadNumber(out var result2))
			{
				return new ValueTask<bool>(result <= result2);
			}
			if (x.TryReadString(out string result3) && y.TryReadString(out string result4))
			{
				int num = StringComparer.Ordinal.Compare(result3, result4);
				return new ValueTask<bool>(num <= 0);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Le, cancellationToken);
		}

		public static ValueTask<bool> Equals(this LuaState state, LuaValue x, LuaValue y, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (x == y)
			{
				return new ValueTask<bool>(result: true);
			}
			return LuaVirtualMachine.ExecuteCompareOperationMetaMethod(state, x, y, OpCode.Eq, cancellationToken);
		}

		public static async ValueTask<LuaValue> GetTable(this LuaState state, LuaValue table, LuaValue key, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (table.TryReadTable(out LuaTable luaTable) && luaTable.TryGetValue(key, out var value))
			{
				return value;
			}
			return await LuaVirtualMachine.ExecuteGetTableSlowPath(state, table, key, cancellationToken);
		}

		public static ValueTask SetTable(this LuaState state, LuaValue table, LuaValue key, LuaValue value, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (key.TryReadNumber(out var result) && double.IsNaN(result))
			{
				throw new LuaRuntimeException(state, "table index is NaN");
			}
			if (table.TryReadTable(out LuaTable result2))
			{
				ref LuaValue reference = ref result2.FindValue(key);
				if (!Unsafe.IsNullRef(ref reference) && reference.Type != 0)
				{
					reference = value;
					return default(ValueTask);
				}
			}
			return LuaVirtualMachine.ExecuteSetTableSlowPath(state, table, key, value, cancellationToken);
		}

		public static ValueTask<LuaValue> Concat(this LuaState state, ReadOnlySpan<LuaValue> values, CancellationToken cancellationToken = default(CancellationToken))
		{
			state.Stack.PushRange(values);
			return state.Concat(values.Length, cancellationToken);
		}

		public static ValueTask<LuaValue> Concat(this LuaState state, int concatCount, CancellationToken cancellationToken = default(CancellationToken))
		{
			return LuaVirtualMachine.Concat(state, concatCount, cancellationToken);
		}

		public static ValueTask<int> Call(this LuaState state, int funcIndex, int returnBase, CancellationToken cancellationToken = default(CancellationToken))
		{
			return LuaVirtualMachine.Call(state, funcIndex, returnBase, cancellationToken);
		}

		public static ValueTask<LuaValue[]> Call(this LuaState state, LuaValue function, ReadOnlySpan<LuaValue> arguments, CancellationToken cancellationToken = default(CancellationToken))
		{
			int count = state.Stack.Count;
			state.Stack.Push(function);
			state.Stack.PushRange(arguments);
			return Impl(state, count, cancellationToken);
			static async ValueTask<LuaValue[]> Impl(LuaState state, int funcIndex, CancellationToken cancellationToken)
			{
				await LuaVirtualMachine.Call(state, funcIndex, funcIndex, cancellationToken);
				int count2 = state.Stack.Count - funcIndex;
				using LuaTopValuesReader results = state.ReadTopValues(count2);
				return results.AsSpan().ToArray();
			}
		}
	}
	public sealed class LuaTable : IEnumerable<KeyValuePair<LuaValue, LuaValue>>, IEnumerable
	{
		public struct LuaTableEnumerator : IEnumerator<KeyValuePair<LuaValue, LuaValue>>, IEnumerator, IDisposable
		{
			[CompilerGenerated]
			[DebuggerBrowsable(DebuggerBrowsableState.Never)]
			private LuaTable <table>P;

			private int index;

			private readonly int version;

			private KeyValuePair<LuaValue, LuaValue> current;

			public KeyValuePair<LuaValue, LuaValue> Current => current;

			object IEnumerator.Current => Current;

			public LuaTableEnumerator(LuaTable table)
			{
				<table>P = table;
				index = -1;
				version = <table>P.dictionary.Version;
				current = default(KeyValuePair<LuaValue, LuaValue>);
			}

			public bool MoveNext()
			{
				if (index < 0)
				{
					int num = -index - 1;
					Span<LuaValue> span = <table>P.array.AsSpan(num);
					for (int i = 0; i < span.Length; i++)
					{
						if (span[i].Type != 0)
						{
							current = new KeyValuePair<LuaValue, LuaValue>(num + i + 1, span[i]);
							index = -num - i - 2;
							return true;
						}
					}
					index = 0;
				}
				while (LuaValueDictionary.MoveNext(<table>P.Dictionary, version, ref index, out current) && current.Value.Type == LuaValueType.Nil)
				{
				}
				return current.Value.Type != LuaValueType.Nil;
			}

			public void Reset()
			{
			}

			public void Dispose()
			{
			}
		}

		private LuaValue[] array;

		private readonly LuaValueDictionary dictionary;

		private LuaTable? metatable;

		private const int MaxArraySize = 16777216;

		private const int MaxDistance = 4096;

		internal LuaValueDictionary Dictionary => dictionary;

		public LuaValue this[LuaValue key]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				if (key.Type == LuaValueType.Nil)
				{
					ThrowIndexIsNil();
				}
				if (TryGetInteger(key, out var integer) && integer > 0 && integer <= array.Length)
				{
					return array[integer - 1];
				}
				if (dictionary.TryGetValue(key, out var value))
				{
					return value;
				}
				return LuaValue.Nil;
			}
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			set
			{
				if (key.TryReadNumber(out var result))
				{
					if (double.IsNaN(result))
					{
						ThrowIndexIsNaN();
					}
					if (MathEx.IsInteger(result))
					{
						int num = (int)result;
						int num2 = num - array.Length;
						if (num2 > 4096)
						{
							dictionary[key] = value;
							return;
						}
						if (0 < num && num < 16777216 && num <= Math.Max(array.Length * 2, 8))
						{
							if (array.Length < num)
							{
								EnsureArrayCapacity(num);
							}
							array[num - 1] = value;
							return;
						}
					}
				}
				dictionary[key] = value;
			}
		}

		public int HashMapCount => dictionary.Count - dictionary.NilCount;

		public int ArrayLength
		{
			get
			{
				for (int i = 0; i < array.Length; i++)
				{
					if (array[i].Type == LuaValueType.Nil)
					{
						return i;
					}
				}
				return array.Length;
			}
		}

		public LuaTable? Metatable
		{
			get
			{
				return metatable;
			}
			set
			{
				metatable = value;
			}
		}

		public LuaTable()
			: this(8, 8)
		{
		}

		public LuaTable(int arrayCapacity, int dictionaryCapacity)
		{
			array = ((arrayCapacity > 1) ? new LuaValue[arrayCapacity] : Array.Empty<LuaValue>());
			dictionary = new LuaValueDictionary(dictionaryCapacity);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool TryGetValue(LuaValue key, out LuaValue value)
		{
			if (key.Type == LuaValueType.Nil)
			{
				value = default(LuaValue);
				return false;
			}
			if (TryGetInteger(key, out var integer) && integer > 0 && integer <= array.Length)
			{
				value = array[integer - 1];
				return value.Type != LuaValueType.Nil;
			}
			return dictionary.TryGetValue(key, out value) && value.Type != LuaValueType.Nil;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal ref LuaValue FindValue(LuaValue key)
		{
			if (key.Type == LuaValueType.Nil)
			{
				ThrowIndexIsNil();
			}
			if (TryGetInteger(key, out var integer) && integer > 0 && integer <= array.Length)
			{
				return ref array[integer - 1];
			}
			int index;
			return ref dictionary.FindValue(key, out index);
		}

		public bool ContainsKey(LuaValue key)
		{
			if (key.Type == LuaValueType.Nil)
			{
				return false;
			}
			if (TryGetInteger(key, out var integer))
			{
				return integer > 0 && integer <= array.Length && array[integer - 1].Type != LuaValueType.Nil;
			}
			LuaValue value;
			return dictionary.TryGetValue(key, out value) && value.Type != LuaValueType.Nil;
		}

		public LuaValue RemoveAt(int index)
		{
			int num = index - 1;
			LuaValue result = array[num];
			if (num < array.Length - 1)
			{
				array.AsSpan(num + 1).CopyTo(array.AsSpan(num));
			}
			array[^1] = default(LuaValue);
			return result;
		}

		public void Insert(int index, LuaValue value)
		{
			if (index <= 0 || index > array.Length + 1)
			{
				throw new IndexOutOfRangeException();
			}
			int num = index - 1;
			int num2 = index - array.Length;
			if (num2 > 4096)
			{
				dictionary[index] = value;
				return;
			}
			if (index > array.Length || array[^1].Type != 0)
			{
				EnsureArrayCapacity(array.Length + 1);
			}
			if (num != array.Length - 1)
			{
				array.AsSpan(num, array.Length - num - 1).CopyTo(array.AsSpan(num + 1));
			}
			array[num] = value;
		}

		public bool TryGetNext(LuaValue key, out KeyValuePair<LuaValue, LuaValue> pair)
		{
			int num = -1;
			int integer;
			if (key.Type == LuaValueType.Nil)
			{
				num = 0;
			}
			else if (TryGetInteger(key, out integer) && integer > 0 && integer <= array.Length)
			{
				num = integer;
			}
			if (num != -1)
			{
				Span<LuaValue> span = array.AsSpan(num);
				for (int i = 0; i < span.Length; i++)
				{
					if (span[i].Type != 0)
					{
						pair = new KeyValuePair<LuaValue, LuaValue>(num + i + 1, span[i]);
						return true;
					}
				}
				LuaValueDictionary.Enumerator enumerator = dictionary.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<LuaValue, LuaValue> current = enumerator.Current;
					if (current.Value.Type != 0)
					{
						pair = current;
						return true;
					}
				}
			}
			else if (dictionary.TryGetNext(key, out pair))
			{
				return true;
			}
			pair = default(KeyValuePair<LuaValue, LuaValue>);
			return false;
		}

		public void Clear()
		{
			array.AsSpan().Clear();
			dictionary.Clear();
		}

		public Memory<LuaValue> GetArrayMemory()
		{
			return array.AsMemory();
		}

		public Span<LuaValue> GetArraySpan()
		{
			return array.AsSpan();
		}

		internal void EnsureArrayCapacity(int newCapacity)
		{
			if (array.Length >= newCapacity)
			{
				return;
			}
			int num = array.Length;
			int num2 = array.Length;
			num2 = ((newCapacity <= 8) ? 8 : MathEx.NextPowerOfTwo(newCapacity));
			Array.Resize(ref array, num2);
			PooledList<(int, LuaValue)> pooledList = new PooledList<(int, LuaValue)>(dictionary.Count);
			try
			{
				LuaValueDictionary.Enumerator enumerator = dictionary.GetEnumerator();
				while (enumerator.MoveNext())
				{
					KeyValuePair<LuaValue, LuaValue> current = enumerator.Current;
					if (TryGetInteger(current.Key, out var integer) && integer > num && integer <= num2)
					{
						(int, LuaValue) item = (integer, current.Value);
						pooledList.Add(in item);
					}
				}
				ReadOnlySpan<(int, LuaValue)> readOnlySpan = pooledList.AsSpan();
				for (int i = 0; i < readOnlySpan.Length; i++)
				{
					var (num3, luaValue) = readOnlySpan[i];
					dictionary.Remove(num3);
					array[num3 - 1] = luaValue;
				}
			}
			finally
			{
				((IDisposable)pooledList).Dispose();
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static bool TryGetInteger(LuaValue value, out int integer)
		{
			if (value.TryReadNumber(out var result) && MathEx.IsInteger(result))
			{
				integer = (int)result;
				return true;
			}
			integer = 0;
			return false;
		}

		private static void ThrowIndexIsNil()
		{
			throw new ArgumentException("the table index is nil");
		}

		private static void ThrowIndexIsNaN()
		{
			throw new ArgumentException("the table index is NaN");
		}

		public LuaTableEnumerator GetEnumerator()
		{
			return new LuaTableEnumerator(this);
		}

		IEnumerator<KeyValuePair<LuaValue, LuaValue>> IEnumerable<KeyValuePair<LuaValue, LuaValue>>.GetEnumerator()
		{
			return new LuaTableEnumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new LuaTableEnumerator(this);
		}
	}
	public static class LuaThreadExtensions
	{
		internal static void ThrowIfCancellationRequested(this LuaState state, CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				Throw(state, cancellationToken);
			}
			static void Throw(LuaState state, CancellationToken cancellationToken)
			{
				throw new LuaCanceledException(state, cancellationToken);
			}
		}
	}
	public enum LuaThreadStatus : byte
	{
		Suspended,
		Normal,
		Running,
		Dead
	}
	public readonly struct LuaTopValuesReader : IDisposable
	{
		private readonly LuaStack stack;

		private readonly int returnBase;

		public int Count => stack.Count - returnBase;

		public int Length => stack.Count - returnBase;

		public LuaValue this[int index] => AsSpan()[index];

		internal LuaTopValuesReader(LuaStack stack, int returnBase)
		{
			this.stack = stack;
			this.returnBase = returnBase;
		}

		public ReadOnlySpan<LuaValue> AsSpan()
		{
			Span<LuaValue> span = stack.AsSpan();
			int num = returnBase;
			return span.Slice(num, span.Length - num);
		}

		public void Dispose()
		{
			stack.PopUntil(returnBase);
		}
	}
	internal sealed class LuaUserData : ILuaUserData
	{
		private readonly LuaValue[] userValues = new LuaValue[1];

		public LuaTable? Metatable { get; set; }

		public Span<LuaValue> UserValues => userValues;

		public LuaUserData(LuaValue value, LuaTable? metatable)
		{
			userValues[0] = value;
			Metatable = metatable;
		}
	}
	public interface ILuaUserData
	{
		LuaTable? Metatable { get; set; }

		Span<LuaValue> UserValues => default(Span<LuaValue>);
	}
	public enum LuaValueType : byte
	{
		Nil,
		Boolean,
		String,
		Number,
		Function,
		Thread,
		LightUserData,
		UserData,
		Table
	}
	[StructLayout(LayoutKind.Auto)]
	public readonly struct LuaValue : IEquatable<LuaValue>
	{
		public static readonly LuaValue Nil = default(LuaValue);

		public readonly LuaValueType Type;

		private readonly double value;

		private readonly object? referenceValue;

		internal LuaValue(LuaValueType type, double value, object? referenceValue)
		{
			Type = type;
			this.value = value;
			this.referenceValue = referenceValue;
		}

		public bool TryRead<T>(out T result)
		{
			Type typeFromHandle = typeof(T);
			switch (Type)
			{
			case LuaValueType.Number:
				if (typeFromHandle == typeof(float))
				{
					float source3 = (float)value;
					result = Unsafe.As<float, T>(ref source3);
					return true;
				}
				if (typeFromHandle == typeof(double))
				{
					double source4 = value;
					result = Unsafe.As<double, T>(ref source4);
					return true;
				}
				if (typeFromHandle == typeof(int))
				{
					if (MathEx.IsInteger(value))
					{
						int source5 = (int)value;
						result = Unsafe.As<int, T>(ref source5);
						return true;
					}
				}
				else if (typeFromHandle == typeof(long))
				{
					if (MathEx.IsInteger(value))
					{
						long source6 = (long)value;
						result = Unsafe.As<long, T>(ref source6);
						return true;
					}
				}
				else if (typeFromHandle == typeof(object))
				{
					result = (T)(object)value;
					return true;
				}
				break;
			case LuaValueType.Boolean:
				if (typeFromHandle == typeof(bool))
				{
					bool source7 = value != 0.0;
					result = Unsafe.As<bool, T>(ref source7);
					return true;
				}
				if (typeFromHandle == typeof(object))
				{
					result = (T)(object)value;
					return true;
				}
				break;
			case LuaValueType.String:
				if (typeFromHandle == typeof(string))
				{
					object source2 = referenceValue;
					result = Unsafe.As<object, T>(ref source2);
					return true;
				}
				if (typeFromHandle == typeof(double))
				{
					result = default(T);
					return TryParseToDouble(out Unsafe.As<T, double>(ref result));
				}
				if (typeFromHandle == typeof(object))
				{
					result = (T)referenceValue;
					return true;
				}
				break;
			case LuaValueType.Function:
				if (typeFromHandle == typeof(LuaFunction) || typeFromHandle.IsSubclassOf(typeof(LuaFunction)))
				{
					object source8 = referenceValue;
					result = Unsafe.As<object, T>(ref source8);
					return true;
				}
				if (typeFromHandle == typeof(object))
				{
					result = (T)referenceValue;
					return true;
				}
				break;
			case LuaValueType.Thread:
				if (typeFromHandle == typeof(LuaState))
				{
					object source9 = referenceValue;
					result = Unsafe.As<object, T>(ref source9);
					return true;
				}
				if (typeFromHandle == typeof(object))
				{
					result = (T)referenceValue;
					return true;
				}
				break;
			case LuaValueType.LightUserData:
			{
				object obj = referenceValue;
				if (obj is T)
				{
					T val = (T)obj;
					if (true)
					{
						result = val;
						return true;
					}
				}
				break;
			}
			case LuaValueType.UserData:
				if (typeFromHandle == typeof(ILuaUserData) || typeof(ILuaUserData).IsAssignableFrom(typeFromHandle))
				{
					object obj = referenceValue;
					if (obj is T)
					{
						T val2 = (T)obj;
						if (true)
						{
							result = val2;
							return true;
						}
					}
				}
				else if (typeFromHandle == typeof(object))
				{
					result = (T)referenceValue;
					return true;
				}
				break;
			case LuaValueType.Table:
				if (typeFromHandle == typeof(LuaTable))
				{
					object source = referenceValue;
					result = Unsafe.As<object, T>(ref source);
					return true;
				}
				if (typeFromHandle == typeof(object))
				{
					result = (T)referenceValue;
					return true;
				}
				break;
			}
			result = default(T);
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadBool(out bool result)
		{
			if (Type == LuaValueType.Boolean)
			{
				result = value != 0.0;
				return true;
			}
			result = false;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadNumber(out double result)
		{
			if (Type == LuaValueType.Number)
			{
				result = value;
				return true;
			}
			result = 0.0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadTable(out LuaTable result)
		{
			if (Type == LuaValueType.Table)
			{
				object source = referenceValue;
				result = Unsafe.As<object, LuaTable>(ref source);
				return true;
			}
			result = null;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadFunction(out LuaFunction result)
		{
			if (Type == LuaValueType.Function)
			{
				object source = referenceValue;
				result = Unsafe.As<object, LuaFunction>(ref source);
				return true;
			}
			result = null;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadString(out string result)
		{
			if (Type == LuaValueType.String)
			{
				object source = referenceValue;
				result = Unsafe.As<object, string>(ref source);
				return true;
			}
			result = null;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal bool TryReadDouble(out double result)
		{
			if (Type == LuaValueType.Number)
			{
				result = value;
				return true;
			}
			return TryParseToDouble(out result);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool TryReadOrSetDouble(ref LuaValue luaValue, out double result)
		{
			if (luaValue.Type == LuaValueType.Number)
			{
				result = luaValue.value;
				return true;
			}
			if (luaValue.TryParseToDouble(out result))
			{
				luaValue = result;
				return true;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal double UnsafeReadDouble()
		{
			

plugins/Marioalexsan.AtlyssLua.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("Marioalexsan.AtlyssLua")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("AtlyssLua")]
[assembly: AssemblyTitle("Marioalexsan.AtlyssLua")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Marioalexsan.AtlyssLua
{
	[BepInPlugin("Marioalexsan.AtlyssLua", "AtlyssLua", "0.1.0")]
	public class AtlyssLua : BaseUnityPlugin
	{
	}
	internal static class ModInfo
	{
		public const string GUID = "Marioalexsan.AtlyssLua";

		public const string NAME = "AtlyssLua";

		public const string VERSION = "0.1.0";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}

plugins/Microsoft.Bcl.TimeProvider.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using FxResources.Microsoft.Bcl.TimeProvider;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.TimeProvider")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides support for system time abstraction primitives for .NET Framework and .NET Standard.\r\n\r\nCommonly Used Types:\r\nSystem.TimeProvider\r\nSystem.ITimer")]
[assembly: AssemblyFileVersion("8.0.23.53103")]
[assembly: AssemblyInformationalVersion("8.0.0+5535e31a712343a63f5d7d796cd874e563e5ac14")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.TimeProvider")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("8.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
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 NullablePublicOnlyAttribute : Attribute
	{
		public readonly bool IncludesInternals;

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.Microsoft.Bcl.TimeProvider
{
	internal static class SR
	{
	}
}
namespace System
{
	public abstract class TimeProvider
	{
		private sealed class SystemTimeProviderTimer : ITimer, IDisposable, IAsyncDisposable
		{
			private sealed class TimerState
			{
				public TimerCallback Callback { get; }

				public object State { get; }

				public Timer Timer { get; set; }

				public TimerState(TimerCallback callback, object state)
				{
					Callback = callback;
					State = state;
					base..ctor();
				}
			}

			private readonly Timer _timer;

			public SystemTimeProviderTimer(TimeSpan dueTime, TimeSpan period, TimerCallback callback, object state)
			{
				TimerState timerState = new TimerState(callback, state);
				timerState.Timer = (_timer = new Timer(delegate(object s)
				{
					TimerState timerState2 = (TimerState)s;
					timerState2.Callback(timerState2.State);
				}, timerState, dueTime, period));
			}

			public bool Change(TimeSpan dueTime, TimeSpan period)
			{
				try
				{
					return _timer.Change(dueTime, period);
				}
				catch (ObjectDisposedException)
				{
					return false;
				}
			}

			public void Dispose()
			{
				_timer.Dispose();
			}

			public ValueTask DisposeAsync()
			{
				_timer.Dispose();
				return default(ValueTask);
			}
		}

		private sealed class SystemTimeProvider : TimeProvider
		{
			internal SystemTimeProvider()
			{
			}
		}

		private static readonly long s_minDateTicks;

		private static readonly long s_maxDateTicks;

		public static TimeProvider System { get; } = new SystemTimeProvider();


		public virtual TimeZoneInfo LocalTimeZone => TimeZoneInfo.Local;

		public virtual long TimestampFrequency => Stopwatch.Frequency;

		public virtual DateTimeOffset GetUtcNow()
		{
			return DateTimeOffset.UtcNow;
		}

		public DateTimeOffset GetLocalNow()
		{
			DateTimeOffset utcNow = GetUtcNow();
			TimeZoneInfo localTimeZone = LocalTimeZone;
			if (localTimeZone == null)
			{
				throw new InvalidOperationException(global::System.SR.InvalidOperation_TimeProviderNullLocalTimeZone);
			}
			TimeSpan utcOffset = localTimeZone.GetUtcOffset(utcNow);
			if (utcOffset.Ticks == 0L)
			{
				return utcNow;
			}
			long num = utcNow.Ticks + utcOffset.Ticks;
			if ((ulong)num > (ulong)s_maxDateTicks)
			{
				num = ((num < s_minDateTicks) ? s_minDateTicks : s_maxDateTicks);
			}
			return new DateTimeOffset(num, utcOffset);
		}

		public virtual long GetTimestamp()
		{
			return Stopwatch.GetTimestamp();
		}

		public TimeSpan GetElapsedTime(long startingTimestamp, long endingTimestamp)
		{
			long timestampFrequency = TimestampFrequency;
			if (timestampFrequency <= 0)
			{
				throw new InvalidOperationException(global::System.SR.InvalidOperation_TimeProviderInvalidTimestampFrequency);
			}
			return new TimeSpan((long)((double)(endingTimestamp - startingTimestamp) * (10000000.0 / (double)timestampFrequency)));
		}

		public TimeSpan GetElapsedTime(long startingTimestamp)
		{
			return GetElapsedTime(startingTimestamp, GetTimestamp());
		}

		public virtual ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
		{
			if (callback == null)
			{
				throw new ArgumentNullException("callback");
			}
			return new SystemTimeProviderTimer(dueTime, period, callback, state);
		}

		static TimeProvider()
		{
			DateTime minValue = DateTime.MinValue;
			s_minDateTicks = minValue.Ticks;
			minValue = DateTime.MaxValue;
			s_maxDateTicks = minValue.Ticks;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_Generic_MustBeNonNegativeNonZero => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegativeNonZero");

		internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual");

		internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual");

		internal static string InvalidOperation_TimeProviderNullLocalTimeZone => GetResourceString("InvalidOperation_TimeProviderNullLocalTimeZone");

		internal static string InvalidOperation_TimeProviderInvalidTimestampFrequency => GetResourceString("InvalidOperation_TimeProviderInvalidTimestampFrequency");

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

		internal static string Format(string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(resourceFormat, p1);
		}

		internal static string Format(string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(resourceFormat, p1, p2);
		}

		internal static string Format(string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(resourceFormat, p1, p2, p3);
		}

		internal static string Format(string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(resourceFormat, args);
			}
			return resourceFormat;
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1);
			}
			return string.Format(provider, resourceFormat, p1);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2);
			}
			return string.Format(provider, resourceFormat, p1, p2);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2, object p3)
		{
			if (UsingResourceKeys())
			{
				return string.Join(", ", resourceFormat, p1, p2, p3);
			}
			return string.Format(provider, resourceFormat, p1, p2, p3);
		}

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Threading
{
	public interface ITimer : IDisposable, IAsyncDisposable
	{
		bool Change(TimeSpan dueTime, TimeSpan period);
	}
}
namespace System.Threading.Tasks
{
	public static class TimeProviderTaskExtensions
	{
		private sealed class DelayState : TaskCompletionSource<bool>
		{
			public ITimer Timer { get; set; }

			public CancellationToken CancellationToken { get; }

			public CancellationTokenRegistration Registration { get; set; }

			public DelayState(CancellationToken cancellationToken)
			{
				CancellationToken = cancellationToken;
			}
		}

		private sealed class WaitAsyncState : TaskCompletionSource<bool>
		{
			public readonly CancellationTokenSource ContinuationCancellation = new CancellationTokenSource();

			public CancellationTokenRegistration Registration;

			public ITimer Timer;

			public CancellationToken CancellationToken { get; }

			public WaitAsyncState(CancellationToken cancellationToken)
				: base(TaskCreationOptions.RunContinuationsAsynchronously)
			{
				CancellationToken = cancellationToken;
			}
		}

		public static Task Delay(this TimeProvider timeProvider, TimeSpan delay, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (timeProvider == TimeProvider.System)
			{
				return Task.Delay(delay, cancellationToken);
			}
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (delay != Timeout.InfiniteTimeSpan && delay < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("delay");
			}
			if (delay == TimeSpan.Zero)
			{
				return Task.CompletedTask;
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			DelayState delayState2 = new DelayState(cancellationToken);
			delayState2.Timer = timeProvider.CreateTimer(delegate(object delayState)
			{
				DelayState delayState5 = (DelayState)delayState;
				delayState5.TrySetResult(result: true);
				delayState5.Registration.Dispose();
				delayState5.Timer?.Dispose();
			}, delayState2, delay, Timeout.InfiniteTimeSpan);
			delayState2.Registration = cancellationToken.Register(delegate(object delayState)
			{
				DelayState delayState3 = (DelayState)delayState;
				ThreadPool.UnsafeQueueUserWorkItem(delegate(object state)
				{
					DelayState delayState4 = (DelayState)state;
					delayState4.TrySetCanceled(delayState4.CancellationToken);
				}, delayState3);
				delayState3.Registration.Dispose();
				delayState3.Timer?.Dispose();
			}, delayState2);
			if (delayState2.Task.IsCompleted)
			{
				delayState2.Registration.Dispose();
				delayState2.Timer.Dispose();
			}
			return delayState2.Task;
		}

		public static Task WaitAsync(this Task task, TimeSpan timeout, TimeProvider timeProvider, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (task == null)
			{
				throw new ArgumentNullException("task");
			}
			if (timeout != Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("timeout");
			}
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (task.IsCompleted)
			{
				return task;
			}
			if (timeout == Timeout.InfiniteTimeSpan && !cancellationToken.CanBeCanceled)
			{
				return task;
			}
			if (timeout == TimeSpan.Zero)
			{
				Task.FromException(new TimeoutException());
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			WaitAsyncState waitAsyncState = new WaitAsyncState(cancellationToken);
			waitAsyncState.Timer = timeProvider.CreateTimer(delegate(object s)
			{
				WaitAsyncState waitAsyncState4 = (WaitAsyncState)s;
				waitAsyncState4.TrySetException(new TimeoutException());
				waitAsyncState4.Registration.Dispose();
				waitAsyncState4.Timer?.Dispose();
				waitAsyncState4.ContinuationCancellation.Cancel();
			}, waitAsyncState, timeout, Timeout.InfiniteTimeSpan);
			task.ContinueWith(delegate(Task t, object s)
			{
				WaitAsyncState waitAsyncState3 = (WaitAsyncState)s;
				if (t.IsFaulted)
				{
					waitAsyncState3.TrySetException(t.Exception.InnerExceptions);
				}
				else if (t.IsCanceled)
				{
					waitAsyncState3.TrySetCanceled();
				}
				else
				{
					waitAsyncState3.TrySetResult(result: true);
				}
				waitAsyncState3.Registration.Dispose();
				waitAsyncState3.Timer?.Dispose();
			}, waitAsyncState, waitAsyncState.ContinuationCancellation.Token, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
			waitAsyncState.Registration = cancellationToken.Register(delegate(object s)
			{
				WaitAsyncState waitAsyncState2 = (WaitAsyncState)s;
				waitAsyncState2.TrySetCanceled(waitAsyncState2.CancellationToken);
				waitAsyncState2.Timer?.Dispose();
				waitAsyncState2.ContinuationCancellation.Cancel();
			}, waitAsyncState);
			if (waitAsyncState.Task.IsCompleted)
			{
				waitAsyncState.Registration.Dispose();
				waitAsyncState.Timer.Dispose();
			}
			return waitAsyncState.Task;
		}

		public static async Task<TResult> WaitAsync<TResult>(this Task<TResult> task, TimeSpan timeout, TimeProvider timeProvider, CancellationToken cancellationToken = default(CancellationToken))
		{
			await ((Task)task).WaitAsync(timeout, timeProvider, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			return task.Result;
		}

		public static CancellationTokenSource CreateCancellationTokenSource(this TimeProvider timeProvider, TimeSpan delay)
		{
			if (timeProvider == null)
			{
				throw new ArgumentNullException("timeProvider");
			}
			if (delay != Timeout.InfiniteTimeSpan && delay < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("delay");
			}
			if (timeProvider == TimeProvider.System)
			{
				return new CancellationTokenSource(delay);
			}
			CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
			ITimer state = timeProvider.CreateTimer(delegate(object s)
			{
				try
				{
					((CancellationTokenSource)s).Cancel();
				}
				catch (ObjectDisposedException)
				{
				}
			}, cancellationTokenSource, delay, Timeout.InfiniteTimeSpan);
			cancellationTokenSource.Token.Register(delegate(object t)
			{
				((ITimer)t).Dispose();
			}, state);
			return cancellationTokenSource;
		}
	}
}

plugins/System.Runtime.CompilerServices.Unsafe.dll

Decompiled 3 months ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.0.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

		public NativeIntegerAttribute()
		{
			TransformFlags = new bool[1] { true };
		}

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}