Decompiled source of AtlyssJint v0.1.1
plugins/Acornima.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Numerics; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; 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 Acornima.Ast; using Acornima.Helpers; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Adam Simon")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Adam Simon")] [assembly: AssemblyDescription("A standard-compliant JavaScript parser, which is a fork of Esprima.NET combined with the .NET port of the acornjs parser.")] [assembly: AssemblyFileVersion("1.1.1.0")] [assembly: AssemblyInformationalVersion("1.1.1+2d9dfb291de04ddba645cd7ff35a4972ac99c691")] [assembly: AssemblyProduct("Acornima")] [assembly: AssemblyTitle("Acornima")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/adams85/acornima")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("Acornima.Benchmarks, PublicKey=00240000048000009400000006020000002400005253413100040000010001009386e741f80212b92e6324bd2d5d89871d081fa41cce46ba30a3d3cae4be4935a92cf6c76a55e5192adad2235139d550816388bdad8a972a7a4eace42838c7694a0124c56174ff27690ba4d470c423ee72efac06decef995b89b6e936b59fe4c6ba88d3c2d3a34216221e1bf455faf1c3e88d93f37b0891b2fbbad9bf606d9ce")] [assembly: InternalsVisibleTo("Acornima.Extras, PublicKey=00240000048000009400000006020000002400005253413100040000010001009386e741f80212b92e6324bd2d5d89871d081fa41cce46ba30a3d3cae4be4935a92cf6c76a55e5192adad2235139d550816388bdad8a972a7a4eace42838c7694a0124c56174ff27690ba4d470c423ee72efac06decef995b89b6e936b59fe4c6ba88d3c2d3a34216221e1bf455faf1c3e88d93f37b0891b2fbbad9bf606d9ce")] [assembly: InternalsVisibleTo("Acornima.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001009386e741f80212b92e6324bd2d5d89871d081fa41cce46ba30a3d3cae4be4935a92cf6c76a55e5192adad2235139d550816388bdad8a972a7a4eace42838c7694a0124c56174ff27690ba4d470c423ee72efac06decef995b89b6e936b59fe4c6ba88d3c2d3a34216221e1bf455faf1c3e88d93f37b0891b2fbbad9bf606d9ce")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.1.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: SkipLocalsInit] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class RequiresLocationAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace System { internal static class SpanExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref readonly T Last<T>(this ReadOnlySpan<T> span) { return ref span[span.Length - 1]; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T Last<T>(this Span<T> span) { return ref span[span.Length - 1]; } public static int FindIndex<T>(this ReadOnlySpan<T> s, Predicate<T> match, int startIndex = 0) { while (startIndex < s.Length) { if (match(s[startIndex])) { return startIndex; } startIndex++; } return -1; } } internal static class StringExtensions { private static readonly string[] s_charToString; static StringExtensions() { s_charToString = new string[256]; for (int i = 0; i < s_charToString.Length; i++) { s_charToString[i] = ((char)i).ToString(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string ToStringCached(this char c) { int num = c; string[] array = s_charToString; if ((uint)num < (uint)array.Length) { return array[num]; } return c.ToString(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInRange(this char c, ushort min, ushort max) { return (uint)(c - min) <= (uint)(max - min); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsOctalDigit(this char c) { return c.IsInRange(48, 55); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDecimalDigit(this char c) { return c.IsInRange(48, 57); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBasicLatinLetter(this char c) { if (!c.IsInRange(97, 122)) { return c.IsInRange(65, 90); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsSurrogate(this char c) { return c.IsInRange(55296, 57343); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsHighSurrogate(this char c) { return c.IsInRange(55296, 56319); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLowSurrogate(this char c) { return c.IsInRange(56320, 57343); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CharCodeAt(this string s, int index) { if ((uint)index < (uint)s.Length) { return s[index]; } return int.MinValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CharCodeAt(this string s, int index, int endIndex) { if ((uint)index < (uint)endIndex) { return s[index]; } return int.MinValue; } public static int CodePointAt(this string s, int index, int endIndex) { int num = s.CharCodeAt(index, endIndex); if (((char)num).IsHighSurrogate()) { int num2 = s.CharCodeAt(index + 1, endIndex); if (((char)num2).IsLowSurrogate()) { return (num << 10) + num2 - 56613888; } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> SliceBetween(this string s, int startIndex, int endIndex) { return s.AsSpan(startIndex, endIndex - startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> ToParsable(this ReadOnlySpan<char> s) { return s; } public static bool TryReadInt(this ref ReadOnlySpan<char> s, out int result) { result = 0; int i; for (i = 0; i < s.Length; i++) { char c; if (!(c = s[i]).IsDecimalDigit()) { break; } result = checked(result * 10 + c - 48); } if (i == 0) { result = 0; return false; } s = s.Slice(i); return true; } public static int GetSequenceHashCode(this ReadOnlySpan<char> span) { int num = 5381; while (span.Length >= 8) { num = ((num << 5) + num) ^ span[0].GetHashCode(); num = ((num << 5) + num) ^ span[1].GetHashCode(); num = ((num << 5) + num) ^ span[2].GetHashCode(); num = ((num << 5) + num) ^ span[3].GetHashCode(); num = ((num << 5) + num) ^ span[4].GetHashCode(); num = ((num << 5) + num) ^ span[5].GetHashCode(); num = ((num << 5) + num) ^ span[6].GetHashCode(); num = ((num << 5) + num) ^ span[7].GetHashCode(); span = span.Slice(8); } if (span.Length >= 4) { num = ((num << 5) + num) ^ span[0].GetHashCode(); num = ((num << 5) + num) ^ span[1].GetHashCode(); num = ((num << 5) + num) ^ span[2].GetHashCode(); num = ((num << 5) + num) ^ span[3].GetHashCode(); span = span.Slice(4); } if (span.Length > 0) { num = ((num << 5) + num) ^ span[0].GetHashCode(); if (span.Length > 1) { num = ((num << 5) + num) ^ span[1].GetHashCode(); if (span.Length > 2) { num = ((num << 5) + num) ^ span[2].GetHashCode(); } } } return num; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [EditorBrowsable(EditorBrowsableState.Never)] [ExcludeFromCodeCoverage] internal static class IsExternalInit { } [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 Acornima { public enum AllowReservedOption { Default, Yes, No, Never } [AutoGeneratedAstVisitor] public class AstRewriter : AstVisitor { public virtual T VisitAndConvert<T>(T node, bool allowNull = false) where T : Node? { if (node == null) { if (!allowNull) { throw new ArgumentNullException("node"); } return null; } object obj = Visit(node); if (!(obj is T result)) { if (obj == null) { if (allowNull) { return null; } throw MustRewriteToSameNodeNonNullable(typeof(T)); } throw allowNull ? MustRewriteToSameNodeNullable(typeof(T)) : MustRewriteToSameNodeNonNullable(typeof(T)); } return result; static Exception MustRewriteToSameNodeNonNullable(Type nodeType) { return new InvalidOperationException(string.Format(null, ExceptionMessages.MustRewriteToSameNodeNonNullable, nodeType)); } static Exception MustRewriteToSameNodeNullable(Type nodeType) { return new InvalidOperationException(string.Format(null, ExceptionMessages.MustRewriteToSameNodeNullable, nodeType)); } } public virtual bool VisitAndConvert<T>(in NodeList<T> nodes, out NodeList<T> newNodes, bool allowNullElement = false) where T : Node? { List<T> list = null; for (int i = 0; i < nodes.Count; i++) { T val = nodes[i]; T val2 = VisitAndConvert(val, allowNullElement); if (list != null) { list.Add(val2); } else if (val2 != val) { list = new List<T>(); for (int j = 0; j < i; j++) { list.Add(nodes[j]); } list.Add(val2); } } if (list != null) { newNodes = new NodeList<T>(list); return true; } newNodes = nodes; return false; } protected internal override object? VisitAssignmentProperty(AssignmentProperty node) { Node node2; Expression key; if (node.Shorthand) { node2 = VisitAndConvert(node.Value); key = ((node2 is AssignmentPattern assignmentPattern) ? assignmentPattern.Left : node2).As<Identifier>(); } else { key = VisitAndConvert(node.Key); node2 = VisitAndConvert(node.Value); } return node.UpdateWith(key, node2); } protected internal override object? VisitExportSpecifier(ExportSpecifier node) { Expression exported; Expression local; if (node.Exported == node.Local) { exported = (local = VisitAndConvert(node.Local)); } else { local = VisitAndConvert(node.Local); exported = VisitAndConvert(node.Exported); } return node.UpdateWith(local, exported); } protected internal override object? VisitImportSpecifier(ImportSpecifier node) { Expression imported; Identifier local; if (node.Imported == node.Local) { imported = (local = VisitAndConvert(node.Local)); } else { imported = VisitAndConvert(node.Imported); local = VisitAndConvert(node.Local); } return node.UpdateWith(imported, local); } protected internal override object? VisitObjectProperty(ObjectProperty node) { Node node2; Expression key; if (node.Shorthand) { node2 = VisitAndConvert(node.Value); key = node2.As<Identifier>(); } else { key = VisitAndConvert(node.Key); node2 = VisitAndConvert(node.Value); } return node.UpdateWith(key, node2); } protected internal override object? VisitAccessorProperty(AccessorProperty node) { VisitAndConvert(in node.Decorators, out var newNodes); Expression key = VisitAndConvert(node.Key); Expression value = VisitAndConvert(node.Value, allowNull: true); return node.UpdateWith(in newNodes, key, value); } protected internal override object? VisitArrayExpression(ArrayExpression node) { VisitAndConvert<Expression>(in node.Elements, out var newNodes, allowNullElement: true); return node.UpdateWith(in newNodes); } protected internal override object? VisitArrayPattern(ArrayPattern node) { VisitAndConvert<Node>(in node.Elements, out var newNodes, allowNullElement: true); return node.UpdateWith(in newNodes); } protected internal override object? VisitArrowFunctionExpression(ArrowFunctionExpression node) { VisitAndConvert(in node.Params, out var newNodes); StatementOrExpression body = VisitAndConvert(node.Body); return node.UpdateWith(in newNodes, body); } protected internal override object? VisitAssignmentExpression(AssignmentExpression node) { Node left = VisitAndConvert(node.Left); Expression right = VisitAndConvert(node.Right); return node.UpdateWith(left, right); } protected internal override object? VisitAssignmentPattern(AssignmentPattern node) { Node left = VisitAndConvert(node.Left); Expression right = VisitAndConvert(node.Right); return node.UpdateWith(left, right); } protected internal override object? VisitAwaitExpression(AwaitExpression node) { Expression argument = VisitAndConvert(node.Argument); return node.UpdateWith(argument); } protected internal override object? VisitBinaryExpression(BinaryExpression node) { Expression left = VisitAndConvert(node.Left); Expression right = VisitAndConvert(node.Right); return node.UpdateWith(left, right); } protected internal override object? VisitBlockStatement(BlockStatement node) { VisitAndConvert(in node.Body, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitBreakStatement(BreakStatement node) { Identifier label = VisitAndConvert(node.Label, allowNull: true); return node.UpdateWith(label); } protected internal override object? VisitCallExpression(CallExpression node) { Expression callee = VisitAndConvert(node.Callee); VisitAndConvert(in node.Arguments, out var newNodes); return node.UpdateWith(callee, in newNodes); } protected internal override object? VisitCatchClause(CatchClause node) { Node param = VisitAndConvert(node.Param, allowNull: true); NestedBlockStatement body = VisitAndConvert(node.Body); return node.UpdateWith(param, body); } protected internal override object? VisitChainExpression(ChainExpression node) { Expression expression = VisitAndConvert(node.Expression); return node.UpdateWith(expression); } protected internal override object? VisitClassBody(ClassBody node) { VisitAndConvert(in node.Body, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitClassDeclaration(ClassDeclaration node) { VisitAndConvert(in node.Decorators, out var newNodes); Identifier id = VisitAndConvert(node.Id, allowNull: true); Expression superClass = VisitAndConvert(node.SuperClass, allowNull: true); ClassBody body = VisitAndConvert(node.Body); return node.UpdateWith(in newNodes, id, superClass, body); } protected internal override object? VisitClassExpression(ClassExpression node) { VisitAndConvert(in node.Decorators, out var newNodes); Identifier id = VisitAndConvert(node.Id, allowNull: true); Expression superClass = VisitAndConvert(node.SuperClass, allowNull: true); ClassBody body = VisitAndConvert(node.Body); return node.UpdateWith(in newNodes, id, superClass, body); } protected internal override object? VisitConditionalExpression(ConditionalExpression node) { Expression test = VisitAndConvert(node.Test); Expression consequent = VisitAndConvert(node.Consequent); Expression alternate = VisitAndConvert(node.Alternate); return node.UpdateWith(test, consequent, alternate); } protected internal override object? VisitContinueStatement(ContinueStatement node) { Identifier label = VisitAndConvert(node.Label, allowNull: true); return node.UpdateWith(label); } protected internal override object? VisitDecorator(Decorator node) { Expression expression = VisitAndConvert(node.Expression); return node.UpdateWith(expression); } protected internal override object? VisitDoWhileStatement(DoWhileStatement node) { Statement body = VisitAndConvert(node.Body); Expression test = VisitAndConvert(node.Test); return node.UpdateWith(body, test); } protected internal override object? VisitExportAllDeclaration(ExportAllDeclaration node) { Expression exported = VisitAndConvert(node.Exported, allowNull: true); StringLiteral source = VisitAndConvert(node.Source); VisitAndConvert(in node.Attributes, out var newNodes); return node.UpdateWith(exported, source, in newNodes); } protected internal override object? VisitExportDefaultDeclaration(ExportDefaultDeclaration node) { StatementOrExpression declaration = VisitAndConvert(node.Declaration); return node.UpdateWith(declaration); } protected internal override object? VisitExportNamedDeclaration(ExportNamedDeclaration node) { Declaration declaration = VisitAndConvert(node.Declaration, allowNull: true); VisitAndConvert(in node.Specifiers, out var newNodes); StringLiteral source = VisitAndConvert(node.Source, allowNull: true); VisitAndConvert(in node.Attributes, out var newNodes2); return node.UpdateWith(declaration, in newNodes, source, in newNodes2); } protected internal override object? VisitExpressionStatement(ExpressionStatement node) { Expression expression = VisitAndConvert(node.Expression); return node.UpdateWith(expression); } protected internal override object? VisitForInStatement(ForInStatement node) { Node left = VisitAndConvert(node.Left); Expression right = VisitAndConvert(node.Right); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(left, right, body); } protected internal override object? VisitForOfStatement(ForOfStatement node) { Node left = VisitAndConvert(node.Left); Expression right = VisitAndConvert(node.Right); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(left, right, body); } protected internal override object? VisitForStatement(ForStatement node) { StatementOrExpression init = VisitAndConvert(node.Init, allowNull: true); Expression test = VisitAndConvert(node.Test, allowNull: true); Expression update = VisitAndConvert(node.Update, allowNull: true); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(init, test, update, body); } protected internal override object? VisitFunctionBody(FunctionBody node) { VisitAndConvert(in node.Body, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitFunctionDeclaration(FunctionDeclaration node) { Identifier id = VisitAndConvert(node.Id, allowNull: true); VisitAndConvert(in node.Params, out var newNodes); FunctionBody body = VisitAndConvert(node.Body); return node.UpdateWith(id, in newNodes, body); } protected internal override object? VisitFunctionExpression(FunctionExpression node) { Identifier id = VisitAndConvert(node.Id, allowNull: true); VisitAndConvert(in node.Params, out var newNodes); FunctionBody body = VisitAndConvert(node.Body); return node.UpdateWith(id, in newNodes, body); } protected internal override object? VisitIfStatement(IfStatement node) { Expression test = VisitAndConvert(node.Test); Statement consequent = VisitAndConvert(node.Consequent); Statement alternate = VisitAndConvert(node.Alternate, allowNull: true); return node.UpdateWith(test, consequent, alternate); } protected internal override object? VisitImportAttribute(ImportAttribute node) { Expression key = VisitAndConvert(node.Key); StringLiteral value = VisitAndConvert(node.Value); return node.UpdateWith(key, value); } protected internal override object? VisitImportDeclaration(ImportDeclaration node) { VisitAndConvert(in node.Specifiers, out var newNodes); StringLiteral source = VisitAndConvert(node.Source); VisitAndConvert(in node.Attributes, out var newNodes2); return node.UpdateWith(in newNodes, source, in newNodes2); } protected internal override object? VisitImportDefaultSpecifier(ImportDefaultSpecifier node) { Identifier local = VisitAndConvert(node.Local); return node.UpdateWith(local); } protected internal override object? VisitImportExpression(ImportExpression node) { Expression source = VisitAndConvert(node.Source); Expression options = VisitAndConvert(node.Options, allowNull: true); return node.UpdateWith(source, options); } protected internal override object? VisitImportNamespaceSpecifier(ImportNamespaceSpecifier node) { Identifier local = VisitAndConvert(node.Local); return node.UpdateWith(local); } protected internal override object? VisitLabeledStatement(LabeledStatement node) { Identifier label = VisitAndConvert(node.Label); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(label, body); } protected internal override object? VisitMemberExpression(MemberExpression node) { Expression @object = VisitAndConvert(node.Object); Expression property = VisitAndConvert(node.Property); return node.UpdateWith(@object, property); } protected internal override object? VisitMetaProperty(MetaProperty node) { Identifier meta = VisitAndConvert(node.Meta); Identifier property = VisitAndConvert(node.Property); return node.UpdateWith(meta, property); } protected internal override object? VisitMethodDefinition(MethodDefinition node) { VisitAndConvert(in node.Decorators, out var newNodes); Expression key = VisitAndConvert(node.Key); FunctionExpression value = VisitAndConvert(node.Value); return node.UpdateWith(in newNodes, key, value); } protected internal override object? VisitNewExpression(NewExpression node) { Expression callee = VisitAndConvert(node.Callee); VisitAndConvert(in node.Arguments, out var newNodes); return node.UpdateWith(callee, in newNodes); } protected internal override object? VisitObjectExpression(ObjectExpression node) { VisitAndConvert(in node.Properties, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitObjectPattern(ObjectPattern node) { VisitAndConvert(in node.Properties, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitParenthesizedExpression(ParenthesizedExpression node) { Expression expression = VisitAndConvert(node.Expression); return node.UpdateWith(expression); } protected internal override object? VisitProgram(Program node) { VisitAndConvert(in node.Body, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitPropertyDefinition(PropertyDefinition node) { VisitAndConvert(in node.Decorators, out var newNodes); Expression key = VisitAndConvert(node.Key); Expression value = VisitAndConvert(node.Value, allowNull: true); return node.UpdateWith(in newNodes, key, value); } protected internal override object? VisitRestElement(RestElement node) { Node argument = VisitAndConvert(node.Argument); return node.UpdateWith(argument); } protected internal override object? VisitReturnStatement(ReturnStatement node) { Expression argument = VisitAndConvert(node.Argument, allowNull: true); return node.UpdateWith(argument); } protected internal override object? VisitSequenceExpression(SequenceExpression node) { VisitAndConvert(in node.Expressions, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitSpreadElement(SpreadElement node) { Expression argument = VisitAndConvert(node.Argument); return node.UpdateWith(argument); } protected internal override object? VisitStaticBlock(StaticBlock node) { VisitAndConvert(in node.Body, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitSwitchCase(SwitchCase node) { Expression test = VisitAndConvert(node.Test, allowNull: true); VisitAndConvert(in node.Consequent, out var newNodes); return node.UpdateWith(test, in newNodes); } protected internal override object? VisitSwitchStatement(SwitchStatement node) { Expression discriminant = VisitAndConvert(node.Discriminant); VisitAndConvert(in node.Cases, out var newNodes); return node.UpdateWith(discriminant, in newNodes); } protected internal override object? VisitTaggedTemplateExpression(TaggedTemplateExpression node) { Expression tag = VisitAndConvert(node.Tag); TemplateLiteral quasi = VisitAndConvert(node.Quasi); return node.UpdateWith(tag, quasi); } protected internal override object? VisitTemplateLiteral(TemplateLiteral node) { VisitAndConvert(in node.Quasis, out var newNodes); VisitAndConvert(in node.Expressions, out var newNodes2); return node.UpdateWith(in newNodes, in newNodes2); } protected internal override object? VisitThrowStatement(ThrowStatement node) { Expression argument = VisitAndConvert(node.Argument); return node.UpdateWith(argument); } protected internal override object? VisitTryStatement(TryStatement node) { NestedBlockStatement block = VisitAndConvert(node.Block); CatchClause handler = VisitAndConvert(node.Handler, allowNull: true); NestedBlockStatement finalizer = VisitAndConvert(node.Finalizer, allowNull: true); return node.UpdateWith(block, handler, finalizer); } protected internal override object? VisitUnaryExpression(UnaryExpression node) { Expression argument = VisitAndConvert(node.Argument); return node.UpdateWith(argument); } protected internal override object? VisitVariableDeclaration(VariableDeclaration node) { VisitAndConvert(in node.Declarations, out var newNodes); return node.UpdateWith(in newNodes); } protected internal override object? VisitVariableDeclarator(VariableDeclarator node) { Node id = VisitAndConvert(node.Id); Expression init = VisitAndConvert(node.Init, allowNull: true); return node.UpdateWith(id, init); } protected internal override object? VisitWhileStatement(WhileStatement node) { Expression test = VisitAndConvert(node.Test); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(test, body); } protected internal override object? VisitWithStatement(WithStatement node) { Expression @object = VisitAndConvert(node.Object); Statement body = VisitAndConvert(node.Body); return node.UpdateWith(@object, body); } protected internal override object? VisitYieldExpression(YieldExpression node) { Expression argument = VisitAndConvert(node.Argument, allowNull: true); return node.UpdateWith(argument); } } [AutoGeneratedAstVisitor] public class AstVisitor { private int _recursionDepth; private static NotImplementedException UnsupportedNodeType(Type nodeType, [CallerMemberName] string? callerName = null) { return new NotImplementedException(string.Format(null, ExceptionMessages.UnsupportedNodeTypeVisited, nodeType, callerName)); } protected virtual void Reset() { _recursionDepth = 0; } public virtual object? Visit(Node node) { _recursionDepth++; StackGuard.EnsureSufficientExecutionStack(_recursionDepth); object? result = node.Accept(this); _recursionDepth--; return result; } protected internal virtual object? VisitAssignmentProperty(AssignmentProperty node) { if (!node.Shorthand) { Visit(node.Key); } Visit(node.Value); return node; } protected internal virtual object? VisitExportSpecifier(ExportSpecifier node) { Visit(node.Local); if (node.Exported != node.Local) { Visit(node.Exported); } return node; } protected internal virtual object? VisitExtension(Node node) { throw UnsupportedNodeType(node.GetType(), "VisitExtension"); } protected internal virtual object? VisitImportSpecifier(ImportSpecifier node) { if (node.Imported != node.Local) { Visit(node.Imported); } Visit(node.Local); return node; } protected internal virtual object? VisitObjectProperty(ObjectProperty node) { if (!node.Shorthand) { Visit(node.Key); } Visit(node.Value); return node; } protected internal virtual object? VisitTemplateLiteral(TemplateLiteral node) { ref readonly NodeList<TemplateElement> quasis = ref node.Quasis; ref readonly NodeList<Expression> expressions = ref node.Expressions; int num = 0; TemplateElement node2; while (!(node2 = quasis[num]).Tail) { Visit(node2); Visit(expressions[num]); num++; } Visit(node2); return node; } protected internal virtual object? VisitAccessorProperty(AccessorProperty node) { ref readonly NodeList<Decorator> decorators = ref node.Decorators; for (int i = 0; i < decorators.Count; i++) { Visit(decorators[i]); } Visit(node.Key); if (node.Value != null) { Visit(node.Value); } return node; } protected internal virtual object? VisitArrayExpression(ArrayExpression node) { ref readonly NodeList<Expression> elements = ref node.Elements; for (int i = 0; i < elements.Count; i++) { Expression expression = elements[i]; if (expression != null) { Visit(expression); } } return node; } protected internal virtual object? VisitArrayPattern(ArrayPattern node) { ref readonly NodeList<Node> elements = ref node.Elements; for (int i = 0; i < elements.Count; i++) { Node node2 = elements[i]; if (node2 != null) { Visit(node2); } } return node; } protected internal virtual object? VisitArrowFunctionExpression(ArrowFunctionExpression node) { ref readonly NodeList<Node> @params = ref node.Params; for (int i = 0; i < @params.Count; i++) { Visit(@params[i]); } Visit(node.Body); return node; } protected internal virtual object? VisitAssignmentExpression(AssignmentExpression node) { Visit(node.Left); Visit(node.Right); return node; } protected internal virtual object? VisitAssignmentPattern(AssignmentPattern node) { Visit(node.Left); Visit(node.Right); return node; } protected internal virtual object? VisitAwaitExpression(AwaitExpression node) { Visit(node.Argument); return node; } protected internal virtual object? VisitBinaryExpression(BinaryExpression node) { Visit(node.Left); Visit(node.Right); return node; } protected internal virtual object? VisitBlockStatement(BlockStatement node) { ref readonly NodeList<Statement> body = ref node.Body; for (int i = 0; i < body.Count; i++) { Visit(body[i]); } return node; } protected internal virtual object? VisitBreakStatement(BreakStatement node) { if (node.Label != null) { Visit(node.Label); } return node; } protected internal virtual object? VisitCallExpression(CallExpression node) { Visit(node.Callee); ref readonly NodeList<Expression> arguments = ref node.Arguments; for (int i = 0; i < arguments.Count; i++) { Visit(arguments[i]); } return node; } protected internal virtual object? VisitCatchClause(CatchClause node) { if (node.Param != null) { Visit(node.Param); } Visit(node.Body); return node; } protected internal virtual object? VisitChainExpression(ChainExpression node) { Visit(node.Expression); return node; } protected internal virtual object? VisitClassBody(ClassBody node) { ref readonly NodeList<Node> body = ref node.Body; for (int i = 0; i < body.Count; i++) { Visit(body[i]); } return node; } protected internal virtual object? VisitClassDeclaration(ClassDeclaration node) { ref readonly NodeList<Decorator> decorators = ref node.Decorators; for (int i = 0; i < decorators.Count; i++) { Visit(decorators[i]); } if (node.Id != null) { Visit(node.Id); } if (node.SuperClass != null) { Visit(node.SuperClass); } Visit(node.Body); return node; } protected internal virtual object? VisitClassExpression(ClassExpression node) { ref readonly NodeList<Decorator> decorators = ref node.Decorators; for (int i = 0; i < decorators.Count; i++) { Visit(decorators[i]); } if (node.Id != null) { Visit(node.Id); } if (node.SuperClass != null) { Visit(node.SuperClass); } Visit(node.Body); return node; } protected internal virtual object? VisitConditionalExpression(ConditionalExpression node) { Visit(node.Test); Visit(node.Consequent); Visit(node.Alternate); return node; } protected internal virtual object? VisitContinueStatement(ContinueStatement node) { if (node.Label != null) { Visit(node.Label); } return node; } protected internal virtual object? VisitDebuggerStatement(DebuggerStatement node) { return node; } protected internal virtual object? VisitDecorator(Decorator node) { Visit(node.Expression); return node; } protected internal virtual object? VisitDoWhileStatement(DoWhileStatement node) { Visit(node.Body); Visit(node.Test); return node; } protected internal virtual object? VisitEmptyStatement(EmptyStatement node) { return node; } protected internal virtual object? VisitExportAllDeclaration(ExportAllDeclaration node) { if (node.Exported != null) { Visit(node.Exported); } Visit(node.Source); ref readonly NodeList<ImportAttribute> attributes = ref node.Attributes; for (int i = 0; i < attributes.Count; i++) { Visit(attributes[i]); } return node; } protected internal virtual object? VisitExportDefaultDeclaration(ExportDefaultDeclaration node) { Visit(node.Declaration); return node; } protected internal virtual object? VisitExportNamedDeclaration(ExportNamedDeclaration node) { if (node.Declaration != null) { Visit(node.Declaration); } ref readonly NodeList<ExportSpecifier> specifiers = ref node.Specifiers; for (int i = 0; i < specifiers.Count; i++) { Visit(specifiers[i]); } if (node.Source != null) { Visit(node.Source); } ref readonly NodeList<ImportAttribute> attributes = ref node.Attributes; for (int j = 0; j < attributes.Count; j++) { Visit(attributes[j]); } return node; } protected internal virtual object? VisitExpressionStatement(ExpressionStatement node) { Visit(node.Expression); return node; } protected internal virtual object? VisitForInStatement(ForInStatement node) { Visit(node.Left); Visit(node.Right); Visit(node.Body); return node; } protected internal virtual object? VisitForOfStatement(ForOfStatement node) { Visit(node.Left); Visit(node.Right); Visit(node.Body); return node; } protected internal virtual object? VisitForStatement(ForStatement node) { if (node.Init != null) { Visit(node.Init); } if (node.Test != null) { Visit(node.Test); } if (node.Update != null) { Visit(node.Update); } Visit(node.Body); return node; } protected internal virtual object? VisitFunctionBody(FunctionBody node) { ref readonly NodeList<Statement> body = ref node.Body; for (int i = 0; i < body.Count; i++) { Visit(body[i]); } return node; } protected internal virtual object? VisitFunctionDeclaration(FunctionDeclaration node) { if (node.Id != null) { Visit(node.Id); } ref readonly NodeList<Node> @params = ref node.Params; for (int i = 0; i < @params.Count; i++) { Visit(@params[i]); } Visit(node.Body); return node; } protected internal virtual object? VisitFunctionExpression(FunctionExpression node) { if (node.Id != null) { Visit(node.Id); } ref readonly NodeList<Node> @params = ref node.Params; for (int i = 0; i < @params.Count; i++) { Visit(@params[i]); } Visit(node.Body); return node; } protected internal virtual object? VisitIdentifier(Identifier node) { return node; } protected internal virtual object? VisitIfStatement(IfStatement node) { Visit(node.Test); Visit(node.Consequent); if (node.Alternate != null) { Visit(node.Alternate); } return node; } protected internal virtual object? VisitImportAttribute(ImportAttribute node) { Visit(node.Key); Visit(node.Value); return node; } protected internal virtual object? VisitImportDeclaration(ImportDeclaration node) { ref readonly NodeList<ImportDeclarationSpecifier> specifiers = ref node.Specifiers; for (int i = 0; i < specifiers.Count; i++) { Visit(specifiers[i]); } Visit(node.Source); ref readonly NodeList<ImportAttribute> attributes = ref node.Attributes; for (int j = 0; j < attributes.Count; j++) { Visit(attributes[j]); } return node; } protected internal virtual object? VisitImportDefaultSpecifier(ImportDefaultSpecifier node) { Visit(node.Local); return node; } protected internal virtual object? VisitImportExpression(ImportExpression node) { Visit(node.Source); if (node.Options != null) { Visit(node.Options); } return node; } protected internal virtual object? VisitImportNamespaceSpecifier(ImportNamespaceSpecifier node) { Visit(node.Local); return node; } protected internal virtual object? VisitLabeledStatement(LabeledStatement node) { Visit(node.Label); Visit(node.Body); return node; } protected internal virtual object? VisitLiteral(Literal node) { return node; } protected internal virtual object? VisitMemberExpression(MemberExpression node) { Visit(node.Object); Visit(node.Property); return node; } protected internal virtual object? VisitMetaProperty(MetaProperty node) { Visit(node.Meta); Visit(node.Property); return node; } protected internal virtual object? VisitMethodDefinition(MethodDefinition node) { ref readonly NodeList<Decorator> decorators = ref node.Decorators; for (int i = 0; i < decorators.Count; i++) { Visit(decorators[i]); } Visit(node.Key); Visit(node.Value); return node; } protected internal virtual object? VisitNewExpression(NewExpression node) { Visit(node.Callee); ref readonly NodeList<Expression> arguments = ref node.Arguments; for (int i = 0; i < arguments.Count; i++) { Visit(arguments[i]); } return node; } protected internal virtual object? VisitObjectExpression(ObjectExpression node) { ref readonly NodeList<Node> properties = ref node.Properties; for (int i = 0; i < properties.Count; i++) { Visit(properties[i]); } return node; } protected internal virtual object? VisitObjectPattern(ObjectPattern node) { ref readonly NodeList<Node> properties = ref node.Properties; for (int i = 0; i < properties.Count; i++) { Visit(properties[i]); } return node; } protected internal virtual object? VisitParenthesizedExpression(ParenthesizedExpression node) { Visit(node.Expression); return node; } protected internal virtual object? VisitPrivateIdentifier(PrivateIdentifier node) { return node; } protected internal virtual object? VisitProgram(Program node) { ref readonly NodeList<Statement> body = ref node.Body; for (int i = 0; i < body.Count; i++) { Visit(body[i]); } return node; } protected internal virtual object? VisitPropertyDefinition(PropertyDefinition node) { ref readonly NodeList<Decorator> decorators = ref node.Decorators; for (int i = 0; i < decorators.Count; i++) { Visit(decorators[i]); } Visit(node.Key); if (node.Value != null) { Visit(node.Value); } return node; } protected internal virtual object? VisitRestElement(RestElement node) { Visit(node.Argument); return node; } protected internal virtual object? VisitReturnStatement(ReturnStatement node) { if (node.Argument != null) { Visit(node.Argument); } return node; } protected internal virtual object? VisitSequenceExpression(SequenceExpression node) { ref readonly NodeList<Expression> expressions = ref node.Expressions; for (int i = 0; i < expressions.Count; i++) { Visit(expressions[i]); } return node; } protected internal virtual object? VisitSpreadElement(SpreadElement node) { Visit(node.Argument); return node; } protected internal virtual object? VisitStaticBlock(StaticBlock node) { ref readonly NodeList<Statement> body = ref node.Body; for (int i = 0; i < body.Count; i++) { Visit(body[i]); } return node; } protected internal virtual object? VisitSuper(Super node) { return node; } protected internal virtual object? VisitSwitchCase(SwitchCase node) { if (node.Test != null) { Visit(node.Test); } ref readonly NodeList<Statement> consequent = ref node.Consequent; for (int i = 0; i < consequent.Count; i++) { Visit(consequent[i]); } return node; } protected internal virtual object? VisitSwitchStatement(SwitchStatement node) { Visit(node.Discriminant); ref readonly NodeList<SwitchCase> cases = ref node.Cases; for (int i = 0; i < cases.Count; i++) { Visit(cases[i]); } return node; } protected internal virtual object? VisitTaggedTemplateExpression(TaggedTemplateExpression node) { Visit(node.Tag); Visit(node.Quasi); return node; } protected internal virtual object? VisitTemplateElement(TemplateElement node) { return node; } protected internal virtual object? VisitThisExpression(ThisExpression node) { return node; } protected internal virtual object? VisitThrowStatement(ThrowStatement node) { Visit(node.Argument); return node; } protected internal virtual object? VisitTryStatement(TryStatement node) { Visit(node.Block); if (node.Handler != null) { Visit(node.Handler); } if (node.Finalizer != null) { Visit(node.Finalizer); } return node; } protected internal virtual object? VisitUnaryExpression(UnaryExpression node) { Visit(node.Argument); return node; } protected internal virtual object? VisitVariableDeclaration(VariableDeclaration node) { ref readonly NodeList<VariableDeclarator> declarations = ref node.Declarations; for (int i = 0; i < declarations.Count; i++) { Visit(declarations[i]); } return node; } protected internal virtual object? VisitVariableDeclarator(VariableDeclarator node) { Visit(node.Id); if (node.Init != null) { Visit(node.Init); } return node; } protected internal virtual object? VisitWhileStatement(WhileStatement node) { Visit(node.Test); Visit(node.Body); return node; } protected internal virtual object? VisitWithStatement(WithStatement node) { Visit(node.Object); Visit(node.Body); return node; } protected internal virtual object? VisitYieldExpression(YieldExpression node) { if (node.Argument != null) { Visit(node.Argument); } return node; } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] internal sealed class AutoGeneratedAstVisitorAttribute : Attribute { public Type? VisitorType { get; set; } public string? TargetVisitorFieldName { get; set; } public string? BaseVisitorFieldName { get; set; } } public readonly struct Comment { internal readonly Range _range; internal readonly SourceLocation _location; public CommentKind Kind { get; } public Range ContentRange { get; } public int Start { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _range.Start; } } public int End { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _range.End; } } public Range Range { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _range; } } public SourceLocation Location { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _location; } } public Comment(CommentKind kind, Range contentRange, Range range, in SourceLocation location) { Kind = kind; ContentRange = contentRange; _range = range; _location = location; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<char> GetContent(string input) { return (input ?? ExceptionHelper.ThrowArgumentNullException<string>("input")).SliceBetween(ContentRange.Start, ContentRange.End); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan<char> GetRawValue(string input) { return (input ?? ExceptionHelper.ThrowArgumentNullException<string>("input")).SliceBetween(Start, End); } } public static class CommentExtensions { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref readonly Range RangeRef(this in Comment comment) { return ref comment._range; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref readonly SourceLocation LocationRef(this in Comment comment) { return ref comment._location; } } public enum CommentKind { Unknown, Block, Line, HashBang } public enum EcmaVersion { Unknown = 0, ES3 = 3, ES5 = 5, ES6 = 6, ES7 = 7, ES8 = 8, ES9 = 9, ES10 = 10, ES11 = 11, ES12 = 12, ES13 = 13, ES14 = 14, ES2015 = 6, ES2016 = 7, ES2017 = 8, ES2018 = 9, ES2019 = 10, ES2020 = 11, ES2021 = 12, ES2022 = 13, ES2023 = 14, Latest = 14 } [Flags] public enum ExperimentalESFeatures { None = 0, Decorators = 1, ImportAttributes = 2, RegExpDuplicateNamedCapturingGroups = 4, All = 7 } public interface IParser { ParserOptions Options { get; } Script ParseScript(string input, int start, int length, string? sourceFile = null, bool strict = false); Acornima.Ast.Module ParseModule(string input, int start, int length, string? sourceFile = null); Expression ParseExpression(string input, int start, int length, string? sourceFile = null, bool strict = false); } public interface ITokenizer { string Input { get; } Range Range { get; } SourceType SourceType { get; } string? SourceFile { get; } TokenizerOptions Options { get; } Token Current { get; } Token GetToken(in TokenizerContext context = default(TokenizerContext)); void Next(in TokenizerContext context = default(TokenizerContext)); void Reset(string input, int start, int length, SourceType sourceType = SourceType.Script, string? sourceFile = null); } internal enum Keyword { Unknown, Break, Case, Catch, Class, Const, Continue, Debugger, Default, Delete, Do, Else, Export, Extends, False, Finally, For, Function, If, Import, In, InstanceOf, New, Null, Return, Super, Switch, This, Throw, True, Try, TypeOf, Var, Void, While, With } public readonly ref struct OnNodeContext { internal readonly ReadOnlyRef<Scope> _scope; public bool HasScope { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return !Unsafe.IsNullRef(ref Unsafe.AsRef(in _scope.Value)); } } public ref readonly Scope Scope { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { ref readonly Scope value = ref _scope.Value; if (Unsafe.IsNullRef(ref Unsafe.AsRef(in value))) { ExceptionHelper.ThrowInvalidOperationException<object>(); } return ref value; } } public ReadOnlySpan<Scope> ScopeStack { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal OnNodeContext(ReadOnlyRef<Scope> scope, ArrayList<Scope> scopeStack) { _scope = scope; ScopeStack = scopeStack.AsReadOnlySpan(); } } public enum Operator { Unknown, Assignment, NullishCoalescingAssignment, LogicalOrAssignment, LogicalAndAssignment, BitwiseOrAssignment, BitwiseXorAssignment, BitwiseAndAssignment, LeftShiftAssignment, RightShiftAssignment, UnsignedRightShiftAssignment, AdditionAssignment, SubtractionAssignment, MultiplicationAssignment, DivisionAssignment, RemainderAssignment, ExponentiationAssignment, NullishCoalescing, LogicalOr, LogicalAnd, BitwiseOr, BitwiseXor, BitwiseAnd, Equality, Inequality, StrictEquality, StrictInequality, LessThan, LessThanOrEqual, GreaterThan, GreaterThanOrEqual, In, InstanceOf, LeftShift, RightShift, UnsignedRightShift, Addition, Subtraction, Multiplication, Division, Remainder, Exponentiation, Increment, Decrement, LogicalNot, BitwiseNot, UnaryPlus, UnaryNegation, TypeOf, Void, Delete } public abstract class ParseError { internal delegate ParseError Factory(string code, string description, int index, Position position, string? sourceFile); public string Code { get; } public string Description { get; } public bool IsIndexDefined => Index >= 0; public int Index { get; } public bool IsPositionDefined => Position.Line > 0; public Position Position { get; } public int LineNumber => Position.Line; public int Column => Position.Column; public string? SourceFile { get; } public ParseError(string code, string description, int index = -1, Position position = default(Position), string? sourceFile = null) { Code = code ?? throw new ArgumentNullException("code"); Description = description ?? throw new ArgumentNullException("description"); Index = index; Position = position; SourceFile = sourceFile; } public override string ToString() { if (SourceFile != null) { if (!IsPositionDefined) { return Description + " (" + SourceFile + ")"; } return $"{Description} ({SourceFile}:{LineNumber}:{Column + 1})"; } if (!IsPositionDefined) { return Description; } return $"{Description} ({LineNumber}:{Column + 1})"; } public abstract ParseErrorException ToException(); } public sealed class ParseErrorCollector : ParseErrorHandler { private readonly List<ParseError> _errors = new List<ParseError>(); public IReadOnlyCollection<ParseError> Errors => _errors; protected internal override void Reset() { _errors.Clear(); if (_errors.Capacity > 16) { _errors.Capacity = 16; } } protected override void RecordError(ParseError error) { _errors.Add(error); } } public abstract class ParseErrorException : Exception { public ParseError Error { get; } public string Description => Error.Description; public int LineNumber => Error.LineNumber; public int Column => Error.Column; public string? SourceFile => Error.SourceFile; protected ParseErrorException(ParseError error, Exception? innerException = null) : base((error ?? throw new ArgumentNullException("error")).ToString(), innerException) { Error = error; } } public class ParseErrorHandler { public static readonly ParseErrorHandler Default = new ParseErrorHandler(); protected internal virtual void Reset() { } protected virtual void RecordError(ParseError error) { } [DoesNotReturn] internal void ThrowError(ParseError error) { throw error.ToException(); } internal ParseError TolerateError(ParseError error, bool tolerant) { if (!tolerant) { ThrowError(error); } RecordError(error); return error; } } public sealed class Parser : IParser { internal interface IExtension { Tokenizer CreateTokenizer(TokenizerOptions tokenizerOptions); Expression ParseExprAtom(); } internal enum ReservedWordKind : sbyte { None = 0, OptionalModule = 1, Optional = 2, Strict = 4, StrictBind = -124 } internal delegate bool IsReservedWordDelegate(ReadOnlySpan<char> word, bool strict); internal readonly struct Marker { public readonly int Index; public readonly Position Position; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Marker(int index, Position position) { Index = index; Position = position; } } private enum BindingType : byte { None, Var, Lexical, Function, SimpleCatch, Outside } [Flags] private enum StatementContext : byte { Default = 0, Label = 1, Do = 2, For = 4, If = 8, With = 0x10, While = 0x20 } [Flags] internal enum ExpressionContext : byte { Default = 0, ForInit = 2, AwaitForInit = 3, ForNew = 4, Decorator = 8 } internal struct DestructuringErrors { public int ShorthandAssign; public int TrailingComma; public int ParenthesizedAssign; public int ParenthesizedBind; public int DoubleProto; [MethodImpl(MethodImplOptions.AggressiveInlining)] public DestructuringErrors() { ShorthandAssign = (TrailingComma = (ParenthesizedAssign = (ParenthesizedBind = (DoubleProto = -1)))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly int GetTrailingComma() { if (TrailingComma != -1) { return TrailingComma & 0x7FFFFFFF; } return -1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetTrailingComma(int index, bool isParam) { TrailingComma = ((!isParam || index == int.MaxValue) ? index : (index | int.MinValue)); } } [Flags] private enum FunctionOrClassFlags : byte { None = 0, Statement = 1, HangingStatement = 2, NullableId = 4 } private enum LeftHandSideKind : byte { Unknown, Assignment, PrefixUpdate, PostfixUpdate, ForInOf } internal readonly struct TokenState { public readonly int Position; public readonly TokenType TokenType; public readonly object? TokenValue; public TokenState(int position, TokenType tokenType, object? tokenValue) { Position = position; TokenType = tokenType; TokenValue = tokenValue; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TokenState(Tokenizer tokenizer) : this(tokenizer._start, tokenizer._type, tokenizer._value.Value) { } } private enum LabelKind : byte { None, Loop, Switch } private struct Label { public LabelKind Kind; public string? Name; public int StatementStart; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset(LabelKind kind, string? name = null, int statementStart = 0) { Kind = kind; Name = name; StatementStart = statementStart; } } private struct PrivateNameStatus { public Dictionary<string, int>? Declared; public ArrayList<PrivateIdentifier> Used; [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Reset() { Declared?.Clear(); Used.Clear(); } } private readonly ParserOptions _options; private readonly TokenizerOptions _tokenizerOptions; internal Tokenizer _tokenizer; private readonly IExtension? _extension; internal IsReservedWordDelegate _isReservedWord; internal IsReservedWordDelegate _isReservedWordBind; private bool _inModule; private bool _strict; private bool _topLevelAwaitAllowed; private ScopeFlags _functionsAsVarInScopeFlags; private int _potentialArrowAt; private int _forInitPosition; private int _yieldPosition; private int _awaitPosition; private int _awaitIdentifierPosition; private ArrayList<Label> _labels; private HashSet<string>? _exports; private Dictionary<string, int>? _undefinedExports; private int _scopeId; private ArrayList<Scope> _scopeStack; private ArrayList<PrivateNameStatus> _privateNameStack; private ArrayList<Decorator> _decorators; private int _bindingPatternDepth; private int _recursionDepth; public ParserOptions Options => _options; private ref Scope CurrentScope { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _scopeStack.PeekRef(); } } private ref Scope CurrentVarScope { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _scopeStack.GetItemRef(_scopeStack.PeekRef()._currentVarScopeIndex); } } private ref Scope CurrentThisScope { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _scopeStack.GetItemRef(_scopeStack.PeekRef()._currentThisScopeIndex); } } private bool InFunction { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentVarScope._flags & ScopeFlags.Function) != 0; } } private bool InGenerator { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentVarScope._flags & (ScopeFlags.Generator | ScopeFlags.InClassFieldInit)) == ScopeFlags.Generator; } } private bool InAsync { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentVarScope._flags & (ScopeFlags.Async | ScopeFlags.InClassFieldInit)) == ScopeFlags.Async; } } private bool CanAwait { get { ref Scope currentVarScope = ref CurrentVarScope; if ((currentVarScope._flags & ScopeFlags.Function) != 0) { return (currentVarScope._flags & (ScopeFlags.Async | ScopeFlags.InClassFieldInit)) == ScopeFlags.Async; } if ((currentVarScope._flags & ScopeFlags.Top) != 0) { if (_options._allowAwaitOutsideFunction || _topLevelAwaitAllowed) { return (currentVarScope._flags & ScopeFlags.InClassFieldInit) == 0; } return false; } return false; } } private bool AllowSuper { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (!_options._allowSuperOutsideMethod) { return (CurrentThisScope._flags & (ScopeFlags.Super | ScopeFlags.InClassFieldInit)) != 0; } return true; } } private bool AllowDirectSuper { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentThisScope._flags & ScopeFlags.DirectSuper) != 0; } } private bool TreatFunctionsAsVar { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentScope._flags & _functionsAsVarInScopeFlags) != 0; } } private bool AllowNewDotTarget { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (!_options._allowNewTargetOutsideFunction) { return (CurrentThisScope._flags & (ScopeFlags.Function | ScopeFlags.ClassStaticBlock | ScopeFlags.InClassFieldInit)) != 0; } return true; } } private bool InClassStaticBlock { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentVarScope._flags & ScopeFlags.ClassStaticBlock) != 0; } } private bool InClassFieldInit { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (CurrentThisScope._flags & ScopeFlags.InClassFieldInit) != 0; } } public Parser() : this(ParserOptions.Default) { } public Parser(ParserOptions options) : this(options, null) { } internal Parser(ParserOptions options, IExtension? extension) { _options = options ?? throw new ArgumentNullException("options"); _extension = extension; _tokenizer = ((extension == null) ? new Tokenizer(options.GetTokenizerOptions(), null) : extension.CreateTokenizer(options.GetTokenizerOptions())); _tokenizerOptions = _tokenizer.Options; _isReservedWord = (_isReservedWordBind = null); } public Script ParseScript(string input, string? sourceFile = null, bool strict = false) { return ParseScript(input ?? ExceptionHelper.ThrowArgumentNullException<string>("input"), 0, input.Length, sourceFile, strict); } public Script ParseScript(string input, int start, int length, string? sourceFile = null, bool strict = false) { if (strict && _tokenizerOptions._ecmaVersion < EcmaVersion.ES5) { throw new InvalidOperationException(string.Format(null, ExceptionMessages.InvalidEcmaVersionForStrictMode, EcmaVersion.ES5)); } Reset(input, start, length, SourceType.Script, sourceFile, strict); Marker startMarker = StartNode(); try { NodeList<Statement> body = ParseTopLevel(); Marker endMarker = new Marker(_tokenizer._start, _tokenizer._startLocation); return FinishNodeAt(in startMarker, in endMarker, new Script(in body, _strict), Scope.GetScopeRef(_scopeStack, 0)); } finally { ReleaseLargeBuffers(); } } public Acornima.Ast.Module ParseModule(string input, string? sourceFile = null) { return ParseModule(input ?? ExceptionHelper.ThrowArgumentNullException<string>("input"), 0, input.Length, sourceFile); } public Acornima.Ast.Module ParseModule(string input, int start, int length, string? sourceFile = null) { if (_tokenizerOptions._ecmaVersion < EcmaVersion.ES6) { throw new InvalidOperationException(string.Format(null, ExceptionMessages.InvalidEcmaVersionForModule, EcmaVersion.ES6)); } Reset(input, start, length, SourceType.Module, sourceFile, strict: true); Marker startMarker = StartNode(); try { NodeList<Statement> body = ParseTopLevel(); Marker endMarker = new Marker(_tokenizer._start, _tokenizer._startLocation); return FinishNodeAt(in startMarker, in endMarker, new Acornima.Ast.Module(in body), Scope.GetScopeRef(_scopeStack, 0)); } finally { ReleaseLargeBuffers(); } } public Expression ParseExpression(string input, string? sourceFile = null, bool strict = false) { return ParseExpression(input ?? ExceptionHelper.ThrowArgumentNullException<string>("input"), 0, input.Length, sourceFile, strict); } public Expression ParseExpression(string input, int start, int length, string? sourceFile = null, bool strict = false) { if (strict && _tokenizerOptions._ecmaVersion < EcmaVersion.ES5) { throw new InvalidOperationException(string.Format(null, ExceptionMessages.InvalidEcmaVersionForStrictMode, EcmaVersion.ES5)); } Reset(input, start, length, SourceType.Unknown, sourceFile, strict); try { Next(); Expression result = ParseExpression(ref Unsafe.NullRef<DestructuringErrors>()); if (_tokenizer._type != TokenType.EOF) { Unexpected(); } return result; } finally { ReleaseLargeBuffers(); } } private void CheckPropertyClash(Node property, ref bool hasProto, ref Dictionary<string, int>? propHash, ref DestructuringErrors destructuringErrors) { if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES9 && property.Type == NodeType.SpreadElement) { return; } ObjectProperty objectProperty = (ObjectProperty)property; if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES6 && (objectProperty.Computed || objectProperty.Method || objectProperty.Shorthand)) { return; } Expression key = objectProperty.Key; string text; if (key is Identifier identifier) { text = identifier.Name; } else { if (!(key is Literal literal)) { return; } text = Convert.ToString(literal.Value, CultureInfo.InvariantCulture); } PropertyKind kind = objectProperty.Kind; if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES6) { if (kind != PropertyKind.Init || !(text == "__proto__")) { return; } if (hasProto) { if (Unsafe.IsNullRef(ref destructuringErrors)) { Raise(key.Start, SyntaxErrorMessages.DuplicateProto, "DuplicateProto"); } else if (destructuringErrors.DoubleProto < 0) { destructuringErrors.DoubleProto = key.Start; } } else { hasProto = true; } return; } if (propHash == null) { propHash = new Dictionary<string, int>(); } if (propHash.TryGetValue(text, out var value)) { bool num; if (kind != PropertyKind.Init) { num = (value & (2 | (1 << (int)kind))) != 0; } else { if (_strict && ((uint)value & 2u) != 0) { goto IL_013c; } num = (value & 0xC) != 0; } if (num) { goto IL_013c; } } else { value = 0; } goto IL_0161; IL_0161: propHash[text] = value | (1 << (int)kind); return; IL_013c: Raise(key.Start, SyntaxErrorMessages.PropertyRedefinition, new object[1] { text }, "PropertyRedefinition"); goto IL_0161; } internal Expression ParseExpression(ref DestructuringErrors destructuringErrors, ExpressionContext context = ExpressionContext.Default) { Marker startMarker = StartNode(); Expression expression = ParseMaybeAssign(ref destructuringErrors, context); if (_tokenizer._type == TokenType.Comma) { ArrayList<Expression> arrayList = default(ArrayList<Expression>); arrayList.Add(expression); ArrayList<Expression> arrayList2 = arrayList; while (Eat(TokenType.Comma)) { arrayList2.Add(ParseMaybeAssign(ref destructuringErrors, context)); } NodeList<Expression> expressions = NodeList.From(ref arrayList2); return FinishNode(in startMarker, new SequenceExpression(in expressions)); } return expression; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] internal Expression ParseMaybeAssign(ref DestructuringErrors destructuringErrors, ExpressionContext context = ExpressionContext.Default) { EnterRecursion(); if (IsContextual("yield")) { if (InGenerator) { return ExitRecursion(ParseYield(context)); } _tokenizer._expressionAllowed = false; } bool flag = Unsafe.IsNullRef(ref destructuringErrors); DestructuringErrors destructuringErrors2 = new DestructuringErrors(); ref DestructuringErrors reference = ref flag ? ref destructuringErrors2 : ref destructuringErrors; int parenthesizedAssign = reference.ParenthesizedAssign; int trailingComma = reference.TrailingComma; int doubleProto = reference.DoubleProto; reference.ParenthesizedAssign = (reference.TrailingComma = -1); Marker startMarker = StartNode(); if (_tokenizer._type == TokenType.ParenLeft || _tokenizer._type == TokenType.Name) { _potentialArrowAt = _tokenizer._start; } Expression expression = ParseMaybeConditional(ref reference, context); if (_tokenizer._type.IsAssignment) { Operator op = AssignmentExpression.OperatorFromString((string)_tokenizer._value.Value); Node node = ((_tokenizer._type == TokenType.Eq) ? ToAssignable(expression, ref reference, isBinding: false, isParam: false, LeftHandSideKind.Assignment) : expression); if (!flag) { reference.ParenthesizedAssign = (reference.TrailingComma = (reference.DoubleProto = -1)); } if (reference.ShorthandAssign >= node.Start) { reference.ShorthandAssign = -1; } if (_tokenizer._type == TokenType.Eq) { CheckLValPattern(node, BindingType.None, null, LeftHandSideKind.Assignment); } else { CheckLValSimple(node, BindingType.None, null, LeftHandSideKind.Assignment); } Next(); Expression right = ParseMaybeAssign(ref Unsafe.NullRef<DestructuringErrors>(), context); if (doubleProto >= 0) { reference.DoubleProto = doubleProto; } return ExitRecursion(FinishNode(in startMarker, new AssignmentExpression(op, node, right))); } if (flag) { CheckExpressionErrors(ref reference, andThrow: true); } if (parenthesizedAssign >= 0) { reference.ParenthesizedAssign = parenthesizedAssign; } if (trailingComma != -1) { reference.TrailingComma = trailingComma; } return ExitRecursion(expression); } private Expression ParseMaybeConditional(ref DestructuringErrors destructuringErrors, ExpressionContext context) { Marker startMarker = StartNode(); Expression expression = ParseMaybeBinary(ref destructuringErrors, context); if (CheckExpressionErrors(ref destructuringErrors)) { return expression; } if (Eat(TokenType.Question)) { Expression consequent = ParseMaybeAssign(ref Unsafe.NullRef<DestructuringErrors>()); Expect(TokenType.Colon); Expression alternate = ParseMaybeAssign(ref Unsafe.NullRef<DestructuringErrors>(), context); return FinishNode(in startMarker, new ConditionalExpression(expression, consequent, alternate)); } return expression; } private Expression ParseMaybeBinary(ref DestructuringErrors destructuringErrors, ExpressionContext context) { Marker leftStartMarker = StartNode(); Expression expression = ParseMaybeUnary(sawUnary: false, incDec: false, ref destructuringErrors, context); if (CheckExpressionErrors(ref destructuringErrors)) { return expression; } if (expression.Start != leftStartMarker.Index || expression.Type != NodeType.ArrowFunctionExpression) { return ParseBinaryOp(in leftStartMarker, expression, -1, context); } return expression; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private Expression ParseBinaryOp(in Marker leftStartMarker, Expression left, int minPrec, ExpressionContext context) { while (true) { int precedence = _tokenizer._type.Precedence; if (precedence <= minPrec || ((context & ExpressionContext.ForInit) != 0 && _tokenizer._type == TokenType.In)) { break; } bool flag = _tokenizer._type == TokenType.LogicalOr || _tokenizer._type == TokenType.LogicalAnd; bool flag2; Operator op; if (flag) { flag2 = false; op = ((_tokenizer._type == TokenType.LogicalOr) ? Operator.LogicalOr : Operator.LogicalAnd); } else if (_tokenizer._type == TokenType.Coalesce) { flag2 = true; op = Operator.NullishCoalescing; precedence = TokenType.LogicalAnd.Precedence; } else { flag2 = false; op = NonLogicalBinaryExpression.OperatorFromString((string)_tokenizer._value.Value); } Next(); Marker leftStartMarker2 = StartNode(); Expression right = ParseBinaryOp(in leftStartMarker2, ParseMaybeUnary(sawUnary: false, incDec: false, ref Unsafe.NullRef<DestructuringErrors>(), context), precedence, context); BinaryExpression binaryExpression = BuildBinary(in leftStartMarker, left, right, op, flag || flag2); if ((flag && _tokenizer._type == TokenType.Coalesce) || (flag2 && (_tokenizer._type == TokenType.LogicalOr || _tokenizer._type == TokenType.LogicalAnd))) { RaiseRecoverable(_tokenizer._start, _tokenizer._type, _tokenizer._value.Value); } left = binaryExpression; } return left; } private BinaryExpression BuildBinary(in Marker startMarker, Expression left, Expression right, Operator op, bool logical) { if (right.Type == NodeType.PrivateIdentifier) { Unexpected(right.Start, TokenType.PrivateId, right.As<PrivateIdentifier>().Name); } return FinishNode(in startMarker, logical ? ((BinaryExpression)new LogicalExpression(op, left, right)) : ((BinaryExpression)new NonLogicalBinaryExpression(op, left, right))); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private Expression ParseMaybeUnary(bool sawUnary, bool incDec, ref DestructuringErrors destructuringErrors, ExpressionContext context) { Marker startMarker = StartNode(); Expression expression; if (IsContextual("await") && CanAwait) { EnterRecursion(); expression = ExitRecursion(ParseAwait(context)); sawUnary = true; } else if (_tokenizer._type.Prefix) { bool flag = _tokenizer._type == TokenType.IncDec; Operator @operator = (flag ? UpdateExpression.OperatorFromString((string)_tokenizer._value.Value) : NonUpdateUnaryExpression.OperatorFromString((string)_tokenizer._value.Value)); Next(); EnterRecursion(); Expression expression2 = ExitRecursion(ParseMaybeUnary(sawUnary: true, flag, ref Unsafe.NullRef<DestructuringErrors>(), context)); CheckExpressionErrors(ref destructuringErrors, andThrow: true); if (flag) { CheckLValSimple(expression2, BindingType.None, null, LeftHandSideKind.PrefixUpdate); } else { if (@operator == Operator.Delete) { CheckDeleteErrors(expression2); } sawUnary = true; } expression = FinishNode(in startMarker, flag ? ((UnaryExpression)new UpdateExpression(@operator, expression2, prefix: true)) : ((UnaryExpression)new NonUpdateUnaryExpression(@operator, expression2))); } else if (!sawUnary && _tokenizer._type == TokenType.PrivateId) { if (_options._checkPrivateFields && ((context & ExpressionContext.ForInit) != 0 || _privateNameStack.Count == 0)) { Unexpected(); } expression = ParsePrivateIdentifier(); if (_tokenizer._type != TokenType.In) { Unexpected(expression.Start, TokenType.PrivateId, expression.As<PrivateIdentifier>().Name); } } else { expression = ParseExprSubscripts(ref destructuringErrors, context); while (_tokenizer._type.Postfix && !CanInsertSemicolon()) { Operator @operator = UpdateExpression.OperatorFromString((string)_tokenizer._value.Value); CheckLValSimple(expression, BindingType.None, null, LeftHandSideKind.PostfixUpdate); Next(); expression = FinishNode(in startMarker, new UpdateExpression(@operator, expression, prefix: false)); } } if (!incDec && Eat(TokenType.StarStar)) { if (!sawUnary) { EnterRecursion(); Expression right = ExitRecursion(ParseMaybeUnary(sawUnary: false, incDec: false, ref Unsafe.NullRef<DestructuringErrors>(), context)); return BuildBinary(in startMarker, expression, right, Operator.Exponentiation, logical: false); } Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.UnexpectedTokenUnaryExponentiation, "UnexpectedTokenUnaryExponentiation"); } return expression; [MethodImpl(MethodImplOptions.NoInlining)] void CheckDeleteErrors(Expression argument) { if (_strict && IsLocalVariableAccess(argument, out Expression identifier)) { RaiseRecoverable(identifier.Start, SyntaxErrorMessages.StrictDelete, "StrictDelete"); } else if (IsPrivateFieldAccess(argument, out identifier)) { Raise(identifier.Start, SyntaxErrorMessages.DeletePrivateField, "DeletePrivateField"); } } } private static bool IsLocalVariableAccess(Expression expr, [NotNullWhen(true)] out Expression? identifier) { while (true) { if (!(expr is Identifier)) { if (!(expr is ParenthesizedExpression parenthesizedExpression)) { break; } expr = parenthesizedExpression.Expression; continue; } identifier = expr; return true; } identifier = null; return false; } private static bool IsPrivateFieldAccess(Expression expr, [NotNullWhen(true)] out Expression? identifier) { while (true) { if (expr is MemberExpression memberExpression) { Expression property = memberExpression.Property; if (property == null || property.Type != NodeType.PrivateIdentifier) { break; } identifier = memberExpression.Property; return true; } if (!(expr is ChainExpression chainExpression)) { if (!(expr is ParenthesizedExpression parenthesizedExpression)) { break; } expr = parenthesizedExpression.Expression; } else { expr = chainExpression.Expression; } } identifier = null; return false; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private Expression ParseExprSubscripts(ref DestructuringErrors destructuringErrors, ExpressionContext context = ExpressionContext.Default) { Marker startMarker = StartNode(); Expression expression; if ((context & ExpressionContext.Decorator) == 0) { expression = ParseExprAtom(ref destructuringErrors, context); } else { if (_tokenizer._type != TokenType.Name && _tokenizer._type != TokenType.ParenLeft) { Unexpected(); } expression = ParseExprAtom(ref destructuringErrors, context & ~ExpressionContext.Decorator); } if (expression.Type == NodeType.ArrowFunctionExpression && !_tokenizer._input.SliceBetween(_tokenizer._lastTokenStart, _tokenizer._lastTokenEnd).SequenceEqual(")".AsSpan())) { return expression; } Expression expression2 = ParseSubscripts(in startMarker, expression, noCalls: false, context); if (!Unsafe.IsNullRef(ref destructuringErrors) && expression2.Type == NodeType.MemberExpression) { if (destructuringErrors.ParenthesizedAssign >= expression2.Start) { destructuringErrors.ParenthesizedAssign = -1; } if (destructuringErrors.ParenthesizedBind >= expression2.Start) { destructuringErrors.ParenthesizedBind = -1; } if (destructuringErrors.GetTrailingComma() >= expression2.Start) { destructuringErrors.TrailingComma = -1; } } return expression2; } private Expression ParseSubscripts(in Marker startMarker, Expression baseExpr, bool noCalls, ExpressionContext context) { bool maybeAsyncArrow = _tokenizerOptions._ecmaVersion >= EcmaVersion.ES8 && baseExpr is Identifier identifier && identifier.Name == "async" && _tokenizer._lastTokenEnd == baseExpr.End && !CanInsertSemicolon() && baseExpr.End - baseExpr.Start == "async".Length && _potentialArrowAt == baseExpr.Start; int optionalChainPos = -1; bool hasCall = false; Expression expression; while (true) { expression = ParseSubscript(in startMarker, baseExpr, noCalls, maybeAsyncArrow, ref optionalChainPos, ref hasCall, context); if (expression == baseExpr || expression.Type == NodeType.ArrowFunctionExpression) { break; } baseExpr = expression; } if (optionalChainPos >= 0) { expression = FinishNode(in startMarker, new ChainExpression(expression)); } return expression; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private Expression ParseSubscript(in Marker startMarker, Expression baseExpr, bool noCalls, bool maybeAsyncArrow, ref int optionalChainPos, ref bool hasCall, ExpressionContext context) { bool flag = _tokenizerOptions._ecmaVersion >= EcmaVersion.ES11 && Eat(TokenType.QuestionDot); if (flag) { if (noCalls) { Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.OptionalChainingNoNew, "OptionalChainingNoNew"); } if ((context & ExpressionContext.Decorator) != 0) { Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.InvalidDecoratorMemberExpr, "InvalidDecoratorMemberExpr"); } if (optionalChainPos < 0) { optionalChainPos = _tokenizer._lastTokenStart; } } bool flag2 = Eat(TokenType.BracketLeft); if (flag2 || (flag && _tokenizer._type != TokenType.ParenLeft && _tokenizer._type != TokenType.BackQuote) || Eat(TokenType.Dot)) { Expression property; if (flag2) { if ((context & ExpressionContext.Decorator) != 0) { Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.InvalidDecoratorMemberExpr, "InvalidDecoratorMemberExpr"); } property = ParseExpression(ref Unsafe.NullRef<DestructuringErrors>()); Expect(TokenType.BracketRight); } else { if (hasCall && (context & ExpressionContext.Decorator) != 0) { Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.InvalidDecoratorMemberExpr, "InvalidDecoratorMemberExpr"); } property = ((_tokenizer._type == TokenType.PrivateId && baseExpr.Type != NodeType.Super) ? ((Expression)ParsePrivateIdentifier()) : ((Expression)ParseIdentifier(_options._allowReserved != AllowReservedOption.Never))); } baseExpr = FinishNode(in startMarker, new MemberExpression(baseExpr, property, flag2, flag)); } else if (!noCalls && Eat(TokenType.ParenLeft)) { DestructuringErrors destructuringErrors = new DestructuringErrors(); int yieldPosition = _yieldPosition; int awaitPosition = _awaitPosition; int awaitIdentifierPosition = _awaitIdentifierPosition; _yieldPosition = (_awaitPosition = (_awaitIdentifierPosition = 0)); if (hasCall && (context & ExpressionContext.Decorator) != 0) { Raise(_tokenizer._lastTokenStart, SyntaxErrorMessages.InvalidDecoratorMemberExpr, "InvalidDecoratorMemberExpr"); } NodeList<Expression> args = ParseExprList(TokenType.ParenRight, _tokenizerOptions._ecmaVersion >= EcmaVersion.ES8, allowEmptyItem: false, ref destructuringErrors); if (maybeAsyncArrow && !flag && !CanInsertSemicolon() && Eat(TokenType.Arrow)) { CheckPatternErrors(ref destructuringErrors, isAssign: false); CheckYieldAwaitInDefaultParams(); if (_awaitIdentifierPosition > 0) { Raise(_awaitIdentifierPosition, SyntaxErrorMessages.AwaitBindingIdentifier, "AwaitBindingIdentifier"); } _yieldPosition = yieldPosition; _awaitPosition = awaitPosition; _awaitIdentifierPosition = awaitIdentifierPosition; NodeList<Node> parameters = args.AsNodes(); return ParseArrowExpression(in startMarker, in parameters, isAsync: true, context); } CheckExpressionErrors(ref destructuringErrors, andThrow: true); if (yieldPosition != 0) { _yieldPosition = yieldPosition; } if (awaitPosition != 0) { _awaitPosition = awaitPosition; } if (awaitIdentifierPosition != 0) { _awaitIdentifierPosition = awaitIdentifierPosition; } baseExpr = FinishNode(in startMarker, new CallExpression(baseExpr, in args, flag)); hasCall = true; } else if (_tokenizer._type == TokenType.BackQuote) { if (optionalChainPos >= 0) { Raise(optionalChainPos, SyntaxErrorMessages.OptionalChainingNoTemplate, "OptionalChainingNoTemplate"); } if ((context & ExpressionContext.Decorator) != 0) { Raise(_tokenizer._start, SyntaxErrorMessages.InvalidDecoratorMemberExpr, "InvalidDecoratorMemberExpr"); } TemplateLiteral quasi = ParseTemplate(isTagged: true); baseExpr = FinishNode(in startMarker, new TaggedTemplateExpression(baseExpr, quasi)); } return baseExpr; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] internal Expression ParseExprAtom(ref DestructuringErrors destructuringErrors, ExpressionContext context = ExpressionContext.Default) { Marker startMarker = StartNode(); switch (_tokenizer._type.Kind) { case TokenKind.Keyword: switch (_tokenizer._type.Keyword.Value) { case Keyword.Super: if (!AllowSuper) { Raise(_tokenizer._start, SyntaxErrorMessages.UnexpectedSuper, "UnexpectedSuper"); } Next(); if (_tokenizer._type == TokenType.ParenLeft && !AllowDirectSuper) { Raise(startMarker.Index, SyntaxErrorMessages.UnexpectedSuper, "UnexpectedSuper"); } if (_tokenizer._type != TokenType.Dot && _tokenizer._type != TokenType.BracketLeft && _tokenizer._type != TokenType.ParenLeft) { Raise(startMarker.Index, SyntaxErrorMessages.UnexpectedSuper, "UnexpectedSuper"); } return FinishNode(in startMarker, new Super()); case Keyword.This: Next(); return FinishNode(in startMarker, new ThisExpression()); case Keyword.Function: Next(); return (FunctionExpression)ParseFunction(in startMarker, FunctionOrClassFlags.None); case Keyword.Class: Next(); EnterRecursion(); return ExitRecursion((ClassExpression)ParseClass(in startMarker, FunctionOrClassFlags.None)); case Keyword.New: EnterRecursion(); return ExitRecursion(ParseNew()); case Keyword.Import: if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES11) { return ParseExprImport(context); } break; } break; case TokenKind.Identifier: { if (_tokenizer._type != TokenType.Name) { break; } bool canBeArrow = _potentialArrowAt == _tokenizer._start; bool containsEscape = _tokenizer._containsEscape; Identifier identifier = ParseIdentifier(); if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES8 && !containsEscape && identifier.Name == "async" && !CanInsertSemicolon() && Eat(TokenType.Function)) { _tokenizer.OverrideContext(TokenContext.FunctionInExpression); return (FunctionExpression)ParseFunction(in startMarker, FunctionOrClassFlags.None, isAsync: true, context & ~ExpressionContext.ForNew); } if (canBeArrow && !CanInsertSemicolon()) { if (Eat(TokenType.Arrow)) { NodeList<Node> parameters = new NodeList<Node>(identifier); return ParseArrowExpression(in startMarker, in parameters, isAsync: false, context & ~ExpressionContext.ForNew); } if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES8 && !containsEscape && identifier.Name == "async" && _tokenizer._type == TokenType.Name && ((context & ExpressionContext.AwaitForInit) != ExpressionContext.AwaitForInit || !"of".Equals(_tokenizer._value.Value) || _tokenizer._containsEscape)) { containsEscape = _tokenizer._containsEscape; identifier = ParseIdentifier(); if (CanInsertSemicolon() || !Eat(TokenType.Arrow)) { if ((context & ExpressionContext.AwaitForInit) == ExpressionContext.ForInit && !containsEscape && identifier.Name == "of") { if (startMarker.Index == _forInitPosition) { Raise(_forInitPosition, SyntaxErrorMessages.ForOfAsync, "ForOfAsync"); } else { Raise(_forInitPosition, SyntaxErrorMessages.InvalidLhsInFor, "InvalidLhsInFor"); } } else { Unexpected(); } } NodeList<Node> parameters = new NodeList<Node>(identifier); return ParseArrowExpression(in startMarker, in parameters, isAsync: true, context & ~ExpressionContext.ForNew); } } return identifier; } case TokenKind.NullLiteral: case TokenKind.BooleanLiteral: { string raw2 = (_tokenizer._containsEscape ? Tokenizer.DeduplicateString(_tokenizer._input.SliceBetween(_tokenizer._start, _tokenizer._end), ref _tokenizer._stringPool) : _tokenizer._type.Label); Literal node = ((_tokenizer._type.Kind == TokenKind.NullLiteral) ? ((Literal)new NullLiteral(raw2)) : ((Literal)new BooleanLiteral(_tokenizer._type.Value, raw2))); Next(); return FinishNode(in startMarker, node); } case TokenKind.StringLiteral: case TokenKind.NumericLiteral: case TokenKind.BigIntLiteral: case TokenKind.RegExpLiteral: { string raw2 = Tokenizer.DeduplicateString(_tokenizer._input.SliceBetween(_tokenizer._start, _tokenizer._end), ref _tokenizer._stringPool, 20); Literal node = _tokenizer._type.Kind switch { TokenKind.StringLiteral => new StringLiteral((string)_tokenizer._value.Value, raw2), TokenKind.NumericLiteral => new NumericLiteral(_tokenizer._value.NumericValue, raw2), TokenKind.BigIntLiteral => new BigIntLiteral(_tokenizer._value.BigIntValue, raw2), _ => CreateRegExpLiteral(in _tokenizer._value, raw2), }; Next(); return FinishNode(in startMarker, node); } case TokenKind.Punctuator: if (_tokenizer._type == TokenType.ParenLeft) { bool canBeArrow = _potentialArrowAt == _tokenizer._start; Expression expression = ParseParenAndDistinguishExpression(canBeArrow, context & ~ExpressionContext.ForNew); if (!Unsafe.IsNullRef(ref destructuringErrors)) { if (destructuringErrors.ParenthesizedAssign < 0 && !IsSimpleAssignTarget(expression)) { destructuringErrors.ParenthesizedAssign = startMarker.Index; } if (destructuringErrors.ParenthesizedBind < 0) { destructuringErrors.ParenthesizedBind = startMarker.Index; } } return expression; } if (_tokenizer._type == TokenType.BracketLeft) { Next(); NodeList<Expression> elements = ParseExprList(TokenType.BracketRight, allowTrailingComma: true, allowEmptyItem: true, ref destructuringErrors); return FinishNode(in startMarker, new ArrayExpression(in elements)); } if (_tokenizer._type == TokenType.BraceLeft) { _tokenizer.OverrideContext(TokenContext.BracketsInExpression); EnterRecursion(); return ExitRecursion((Expression)ParseObject(isPattern: false, ref destructuringErrors)); } if (_tokenizer._type == TokenType.BackQuote) { return ParseTemplate(isTagged: false); } if (_tokenizer._type == TokenType.Slash) { _tokenizer.ReadRegExp(); } else { if (_tokenizer._type != TokenType.Assign || !"/=".Equals(_tokenizer._value.Value)) { if (_tokenizer._type == TokenType.At) { EnterRecursion(); return ExitRecursion(ParseDecoratedClassExpression(in startMarker)); } break; } _tokenizer._position--; _tokenizer.ReadRegExp(); } goto case TokenKind.StringLiteral; } if (_extension != null) { return _extension.ParseExprAtom(); } return Unexpected<Expression>(); [MethodImpl(MethodImplOptions.AggressiveInlining)] static RegExpLiteral CreateRegExpLiteral(in TokenValue value, string raw) { Tuple<RegExpValue, RegExpParseResult> tuple = (Tuple<RegExpValue, RegExpParseResult>)value.Value; return new RegExpLiteral(tuple.Item1, tuple.Item2, raw); } } private Expression ParseExprImport(ExpressionContext context) { Marker startMarker = StartNode(); if (_tokenizer._containsEscape) { RaiseRecoverable(_tokenizer._start, SyntaxErrorMessages.InvalidEscapedReservedWord, "InvalidEscapedReservedWord"); } Next(); if (_tokenizer._type == TokenType.ParenLeft && (context & ExpressionContext.ForNew) == 0) { return ParseDynamicImport(in startMarker); } if (_tokenizer._type == TokenType.Dot) { Identifier meta = FinishNode(in startMarker, new Identifier(TokenType.Import.Label)); return ParseImportMeta(in startMarker, meta); } return Unexpected<Expression>(); } private ImportExpression ParseDynamicImport(in Marker startMarker) { Next(); Expression source = ParseMaybeAssign(ref Unsafe.NullRef<DestructuringErrors>()); Expression options = null; if (_tokenizerOptions.AllowImportAttributes() && Eat(TokenType.Comma) && _tokenizer._type != TokenType.ParenRight) { options = ParseMaybeAssign(ref Unsafe.NullRef<DestructuringErrors>()); if (Eat(TokenType.Comma)) { AfterTrailingComma(TokenType.ParenRight, isAllowed: true, notNext: true); } Expect(TokenType.ParenRight); } else if (!Eat(TokenType.ParenRight)) { TokenState tokenState = new TokenState(_tokenizer); if (Eat(TokenType.Comma) && Eat(TokenType.ParenRight)) { RaiseRecoverable(tokenState.Position, tokenState.TokenType, tokenState.TokenValue); } else { Unexpected(tokenState); } } return FinishNode(in startMarker, new ImportExpression(source, options)); } private MetaProperty ParseImportMeta(in Marker startMarker, Identifier meta) { Next(); bool containsEscape = _tokenizer._containsEscape; Identifier identifier = ParseIdentifier(liberal: true); if (identifier.Name != "meta") { Unexpected(identifier.Start, TokenType.Name, identifier.Name); } if (containsEscape) { RaiseRecoverable(identifier.Start, SyntaxErrorMessages.InvalidEscapedMetaProperty, new object[1] { "import.meta" }, "InvalidEscapedMetaProperty"); } if (!_inModule && !_options._allowImportExportEverywhere) { Raise(identifier.Start, SyntaxErrorMessages.ImportMetaOutsideModule, "ImportMetaOutsideModule"); } return FinishNode(in startMarker, new MetaProperty(meta, identifier)); } private Expression ParseParenExpression() { Expect(TokenType.ParenLeft); Expression result = ParseExpression(ref Unsafe.NullRef<DestructuringErrors>()); Expect(TokenType.ParenRight); return result; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] private Expression ParseParenAndDistinguishExpression(bool canBeArrow, ExpressionContext context) { Marker startMarker = StartNode(); Expression expression; if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES6) { Next(); Marker startMarker2 = StartNode(); ArrayList<Node> arrayList = default(ArrayList<Node>); DestructuringErrors destructuringErrors = new DestructuringErrors(); int yieldPosition = _yieldPosition; int awaitPosition = _awaitPosition; _yieldPosition = (_awaitPosition = 0); int num = -1; bool flag = true; bool flag2 = _tokenizerOptions._ecmaVersion >= EcmaVersion.ES8; bool flag3 = false; while (_tokenizer._type != TokenType.ParenRight) { if (!flag) { if (!Eat(TokenType.Comma)) { CheckExpressionErrors(ref destructuringErrors, andThrow: true); Unexpected(); } if (AfterTrailingComma(TokenType.ParenRight, flag2, notNext: true)) { flag3 = true; break; } } else { flag = false; } if (_tokenizer._type == TokenType.Ellipsis) { if (num < 0) { num = _tokenizer._start; } arrayList.Add(ParseSpread(ref destructuringErrors)); if (_tokenizer._type == TokenType.Comma && destructuringErrors.GetTrailingComma() < 0) { destructuringErrors.SetTrailingComma(arrayList.LastItemRef().As<SpreadElement>().Argument.Start, isParam: true); } } else { arrayList.Add(ParseMaybeAssign(ref destructuringErrors)); } } Marker endMarker = new Marker(_tokenizer._lastTokenEnd, _tokenizer._lastTokenEndLocation); Expect(TokenType.ParenRight); if (canBeArrow && !CanInsertSemicolon() && Eat(TokenType.Arrow)) { CheckPatternErrors(ref destructuringErrors, isAssign: false); CheckYieldAwaitInDefaultParams(); _yieldPosition = yieldPosition; _awaitPosition = awaitPosition; NodeList<Node> parameters = NodeList.From(ref arrayList); return ParseArrowExpression(in startMarker, in parameters, isAsync: false, context); } if (arrayList.Count == 0) { Unexpected(_tokenizer._lastTokenStart, TokenType.ParenRight, TokenType.ParenRight.Value); } if (num >= 0) { Unexpected(num, TokenType.Ellipsis, TokenType.Ellipsis.Value); } CheckExpressionErrors(ref destructuringErrors, andThrow: true); if (flag2 && flag3) { RaiseRecoverable(_tokenizer._lastTokenStart, TokenType.ParenRight, TokenType.ParenRight.Value); } if (yieldPosition != 0) { _yieldPosition = yieldPosition; } if (awaitPosition != 0) { _awaitPosition = awaitPosition; } if (arrayList.Count > 1) { ArrayList<Expression> arrayList2 = new ArrayList<Expression>(new Expression[arrayList.Count]); for (int i = 0; i < arrayList.Count; i++) { arrayList2[i] = (Expression)arrayList[i]; } NodeList<Expression> expressions = NodeList.From(ref arrayList2); expression = FinishNodeAt(in startMarker2, in endMarker, new SequenceExpression(in expressions)); } else { expression = (Expression)arrayList[0]; } } else { expression = ParseParenExpression(); } if (!_options._preserveParens) { return expression; } return FinishNode(in startMarker, new ParenthesizedExpression(expression)); } private Expression ParseNew() { if (_tokenizer._containsEscape) { RaiseRecoverable(_tokenizer._start, SyntaxErrorMessages.InvalidEscapedReservedWord, "InvalidEscapedReservedWord"); } Marker startMarker = StartNode(); Next(); if (_tokenizerOptions._ecmaVersion >= EcmaVersion.ES6 && _tokenizer._type == TokenType.Dot) { Identifier meta = FinishNode(in startMarker, new Identifier(TokenType.New.Label)); Next(); bool containsEscape = _tokenizer._containsEscape; Identifier identifier = ParseIdentifier(liberal: true); if (identifier.Name != "target") { Unexpected(identifier.Start, TokenType.Name, identifier.Name); } if (containsEscape) { RaiseRecoverable(identifier.Start, SyntaxErrorMessages.InvalidEscapedMetaProperty, new object[1] { "new.target" }, "InvalidEscapedMetaProperty"); } if (!AllowNewDotTarget) { Raise(identifier.Start, SyntaxErrorMessages.UnexpectedNewTarget, "UnexpectedNewTarget"); } return FinishNode(in startMarker, new MetaProperty(meta, identifier)); } Marker startMarker2 = StartNode(); Expression callee = ParseSubscripts(in startMarker2, ParseExprAtom(ref Unsafe.NullRef<DestructuringErrors>(), ExpressionContext.ForNew), noCalls: true, ExpressionContext.Default); NodeList<Expression> args = (Eat(TokenType.ParenLeft) ? ParseExprList(TokenType.ParenRight, _tokenizerOptions._ecmaVersion >= EcmaVersion.ES8, allowEmptyItem: false, ref Unsafe.NullRef<DestructuringErrors>()) : default(NodeList<Expression>)); return FinishNode(in startMarker, new NewExpression(callee, in args)); } private TemplateElement ParseTemplateElement() { Marker startMarker = StartNode(); TemplateValue value = new TemplateValue(_tokenizer._value.TemplateCooked, (string)_tokenizer._value.Value); Next(); bool tail = _tokenizer._type == TokenType.BackQuote; return FinishNode(in startMarker, new TemplateElement(value, tail)); } private TemplateLiteral ParseTemplate(bool isTagged) { Marker startMarker = StartNode(); Next(ignoreEscapeSequenceInKeyword: false, !isTagged); TemplateElement templateElement = ParseTemplateElement(); ArrayList<TemplateElement> arrayList = default(ArrayList<TemplateElement>); arrayList.Add(templateElement); ArrayList<TemplateElement> arrayList2 = arrayList; ArrayList<Expression> arrayList3 = default(ArrayList<Expression>); while (!templateElement.Tail) { if (_tokenizer._type == TokenType.EOF) { Raise(_tokenizer._start, SyntaxErrorMessages.UnexpectedEOS, "UnexpectedEOS"); } int start = _tokenizer._start; Expect(TokenType.DollarBraceLeft); arrayList3.Add(ParseExpression(ref Unsafe.NullRef<DestructuringErrors>())); if (_tokenizer._type == TokenType.BraceRight) { Next(ignoreEscapeSequenceInKeyword: false, !isTagged); } else { Raise(start, SyntaxErrorMessages.UnterminatedTemplateExpr, "UnterminatedTemplateExpr"); } arrayList2.Add(templateElement = ParseTemplateElement()); } Next(); NodeList<TemplateElement> quasis = NodeList.From(ref arrayList2); NodeList<Expression> expressions = NodeList.From(ref arrayList3); return FinishNode(in startMarker, new TemplateLiteral(in quasis, in expressions)); } private bool IsAsyncProperty(Expression key, bool computed) { bool flag = !computed && key is Identifier identifier && identifier.Name == "async"; int num; if (flag) { bool flag2 = _tokenizer._type == TokenType.Name || _tokenizer._type == TokenType.BracketLeft; if (!flag2) { TokenKind kind = _tokenizer._type.Kind; bool flag3 = (uint)(kind - 6) <= 2u; flag2 = flag3; } if (!flag2) { Keyword? keyword = _tokenizer._type.Keyword; if (!keyword.HasValue) { num = ((_tokenizerOptions._ecmaVersion >= EcmaVersion.ES9 && _tokenizer._type == TokenType.Star) ? 1 : 0); goto IL_00bc; } } num = 1; goto IL_00bc; } goto IL_00bd; IL_00bd: if (flag) { return !Tokenizer.ContainsLineBreak(_tokenizer._input.SliceBetween(_tokenizer._lastTokenEnd, _tokenizer._start)); } return false; IL_00bc: flag = (byte)num != 0; goto IL_00bd; } private Node ParseObject(bool isPattern, ref DestructuringErrors destructuringErrors) { Marker startMarker = StartNode(); ArrayList<Node> arrayList = default(ArrayList<Node>); Next(); bool flag = true; bool hasProto = false; bool isAllowed = _tokenizerOptions._ecmaVersion >= EcmaVersion.ES5; Dictionary<string, int> propHash = null; while (!Eat(TokenType.BraceRight)) { if (!flag) { Expect(TokenType.Comma); if (AfterTrailingComma(TokenType.BraceRight, isAllowed)) { break; } } else { flag = false; } Node node = ParseProperty(isPattern, ref destructuringErr
plugins/Jint.dll
Decompiled 3 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Resources; 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 Acornima; using Acornima.Ast; using Jint.Collections; using Jint.Constraints; using Jint.Extensions; using Jint.Native; using Jint.Native.AggregateError; using Jint.Native.Array; using Jint.Native.ArrayBuffer; using Jint.Native.AsyncFunction; using Jint.Native.Atomics; using Jint.Native.BigInt; using Jint.Native.Boolean; using Jint.Native.DataView; using Jint.Native.Date; using Jint.Native.Error; using Jint.Native.FinalizationRegistry; using Jint.Native.Function; using Jint.Native.Generator; using Jint.Native.Global; using Jint.Native.Intl; using Jint.Native.Iterator; using Jint.Native.Json; using Jint.Native.Map; using Jint.Native.Math; using Jint.Native.Number; using Jint.Native.Number.Dtoa; using Jint.Native.Object; using Jint.Native.Promise; using Jint.Native.Proxy; using Jint.Native.Reflect; using Jint.Native.RegExp; using Jint.Native.Set; using Jint.Native.ShadowRealm; using Jint.Native.SharedArrayBuffer; using Jint.Native.String; using Jint.Native.Symbol; using Jint.Native.TypedArray; using Jint.Native.WeakMap; using Jint.Native.WeakRef; using Jint.Native.WeakSet; using Jint.Pooling; using Jint.Runtime; using Jint.Runtime.CallStack; using Jint.Runtime.Debugger; using Jint.Runtime.Descriptors; using Jint.Runtime.Descriptors.Specialized; using Jint.Runtime.Environments; using Jint.Runtime.Interop; using Jint.Runtime.Interop.Reflection; using Jint.Runtime.Interpreter; using Jint.Runtime.Interpreter.Expressions; using Jint.Runtime.Interpreter.Statements; using Jint.Runtime.Modules; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("Jint.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bf2553c9f214cb21f1f64ed62cadad8fe4f2fa11322a5dfa1d650743145c6085aba05b145b29867af656e0bb9bfd32f5d0deb1668263a38233e7e8e5bad1a3c6edd3f2ec6c512668b4aa797283101444628650949641b4f7cb16707efba542bb754afe87ce956f3a5d43f450d14364eb9571cbf213d1061852fb9dd47a6c05c4")] [assembly: InternalsVisibleTo("Jint.Tests.Test262, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bf2553c9f214cb21f1f64ed62cadad8fe4f2fa11322a5dfa1d650743145c6085aba05b145b29867af656e0bb9bfd32f5d0deb1668263a38233e7e8e5bad1a3c6edd3f2ec6c512668b4aa797283101444628650949641b4f7cb16707efba542bb754afe87ce956f3a5d43f450d14364eb9571cbf213d1061852fb9dd47a6c05c4")] [assembly: InternalsVisibleTo("Jint.Benchmark, PublicKey=0024000004800000940000000602000000240000525341310004000001000100bf2553c9f214cb21f1f64ed62cadad8fe4f2fa11322a5dfa1d650743145c6085aba05b145b29867af656e0bb9bfd32f5d0deb1668263a38233e7e8e5bad1a3c6edd3f2ec6c512668b4aa797283101444628650949641b4f7cb16707efba542bb754afe87ce956f3a5d43f450d14364eb9571cbf213d1061852fb9dd47a6c05c4")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Sebastien Ros")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("Sebastien Ros")] [assembly: AssemblyDescription("Javascript interpreter for .NET.")] [assembly: AssemblyFileVersion("4.0.0.0")] [assembly: AssemblyInformationalVersion("4.3.0+17f6a71d57158ca2b2c5db02a0f61affc5a76f8e")] [assembly: AssemblyProduct("Jint")] [assembly: AssemblyTitle("Jint")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/sebastienros/jint")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.3.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: SkipLocalsInit] 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.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 { [AttributeUsage(AttributeTargets.Method)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class DebuggerDisableUserUnhandledExceptionsAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class StackTraceHiddenAttribute : Attribute { } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class ConstantExpectedAttribute : Attribute { public object? Min { get; set; } public object? Max { get; set; } } [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 { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class DynamicallyAccessedMembersAttribute : Attribute { public DynamicallyAccessedMemberTypes MemberTypes { get; } public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) { MemberTypes = memberTypes; } } [Flags] internal enum DynamicallyAccessedMemberTypes { None = 0, PublicParameterlessConstructor = 1, PublicConstructors = 3, NonPublicConstructors = 4, PublicMethods = 8, NonPublicMethods = 0x10, PublicFields = 0x20, NonPublicFields = 0x40, PublicNestedTypes = 0x80, NonPublicNestedTypes = 0x100, PublicProperties = 0x200, NonPublicProperties = 0x400, PublicEvents = 0x800, NonPublicEvents = 0x1000, Interfaces = 0x2000, All = -1 } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class DynamicDependencyAttribute : Attribute { public string? MemberSignature { get; } public DynamicallyAccessedMemberTypes MemberTypes { get; } public Type? Type { get; } public string? TypeName { get; } public string? AssemblyName { get; } public string? Condition { get; set; } public DynamicDependencyAttribute(string memberSignature) { MemberSignature = memberSignature; } public DynamicDependencyAttribute(string memberSignature, Type type) { MemberSignature = memberSignature; Type = type; } public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName) { MemberSignature = memberSignature; TypeName = typeName; AssemblyName = assemblyName; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type) { MemberTypes = memberTypes; Type = type; } public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName) { MemberTypes = memberTypes; TypeName = typeName; AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class FeatureGuardAttribute : Attribute { public Type FeatureType { get; } public FeatureGuardAttribute(Type featureType) { FeatureType = featureType; } } [AttributeUsage(AttributeTargets.Property, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class FeatureSwitchDefinitionAttribute : Attribute { public string SwitchName { get; } public FeatureSwitchDefinitionAttribute(string switchName) { SwitchName = switchName; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event, Inherited = false, AllowMultiple = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class RequiresAssemblyFilesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresAssemblyFilesAttribute() { } public RequiresAssemblyFilesAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class RequiresDynamicCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresDynamicCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class RequiresUnreferencedCodeAttribute : Attribute { public string Message { get; } public string? Url { get; set; } public RequiresUnreferencedCodeAttribute(string message) { Message = message; } } [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class UnconditionalSuppressMessageAttribute : Attribute { public string Category { get; } public string CheckId { get; } public string? Scope { get; set; } public string? Target { get; set; } public string? MessageId { get; set; } public string? Justification { get; set; } public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } } } namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class SuppressGCTransitionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class UnmanagedCallersOnlyAttribute : Attribute { public Type[]? CallConvs; public string? EntryPoint; } [AttributeUsage(AttributeTargets.Method, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class WasmImportLinkageAttribute : Attribute { } } namespace System.Runtime.CompilerServices2 { [AttributeUsage(AttributeTargets.Struct, AllowMultiple = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class InlineArrayAttribute : Attribute { public int Length { get; } public InlineArrayAttribute(int length) { Length = length; } } } 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; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class ObsoletedOSPlatformAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public ObsoletedOSPlatformAttribute(string platformName) { } public ObsoletedOSPlatformAttribute(string platformName, string? message) { Message = message; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class SupportedOSPlatformAttribute : Attribute { public SupportedOSPlatformAttribute(string platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class SupportedOSPlatformGuardAttribute : Attribute { public SupportedOSPlatformGuardAttribute(string platformName) { } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class TargetPlatformAttribute : Attribute { public TargetPlatformAttribute(string platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class UnsupportedOSPlatformAttribute : Attribute { public string? Message { get; } public UnsupportedOSPlatformAttribute(string platformName) { } public UnsupportedOSPlatformAttribute(string platformName, string? message) { Message = message; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class UnsupportedOSPlatformGuardAttribute : Attribute { public UnsupportedOSPlatformGuardAttribute(string platformName) { } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] internal sealed class SkipLocalsInitAttribute : Attribute { } [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.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class OverloadResolutionPriorityAttribute : Attribute { public int Priority { get; } public OverloadResolutionPriorityAttribute(int priority) { Priority = priority; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] [ExcludeFromCodeCoverage] internal sealed class ParamCollectionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] internal sealed class RequiredMemberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class DisableRuntimeMarshallingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [ExcludeFromCodeCoverage] [Conditional("MULTI_TARGETING_SUPPORT_ATTRIBUTES")] internal sealed class UnsafeAccessorAttribute : Attribute { public UnsafeAccessorKind Kind { get; } public string? Name { get; set; } public UnsafeAccessorAttribute(UnsafeAccessorKind kind) { Kind = kind; } } internal enum UnsafeAccessorKind { Constructor, Method, StaticMethod, Field, StaticField } } namespace System.Text { internal ref struct ValueStringBuilder { private char[]? _arrayToReturnToPool; private Span<char> _chars; private int _pos; public int Length { get { return _pos; } set { _pos = value; } } public int Capacity => _chars.Length; public ref char this[int index] => 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) { 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 void Reverse() { _chars.Slice(0, _pos).Reverse(); } 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 AppendHex(byte b) { ReadOnlySpan<char> value = new ReadOnlySpan<char>(new char[2] { "0123456789ABCDEF"[b / 16], "0123456789ABCDEF"[b % 16] }); Append(value); } [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); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(int value) { Append(value.ToString(CultureInfo.InvariantCulture)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(long value) { Append(value.ToString(CultureInfo.InvariantCulture)); } 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) { 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) { 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) { 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.Buffers { internal static class SearchValues { internal static SearchValues<char> Create(string input) { return new SearchValues<char>(input.AsSpan()); } internal static SearchValues<char> Create(ReadOnlySpan<char> input) { return new SearchValues<char>(input); } } internal sealed class SearchValues<T> { private readonly bool[] _data; private readonly char _min; private readonly char _max; internal SearchValues(ReadOnlySpan<char> input) { _min = '\uffff'; _max = '\0'; ReadOnlySpan<char> readOnlySpan = input; for (int i = 0; i < readOnlySpan.Length; i++) { char val = readOnlySpan[i]; _min = (char)Math.Min(_min, val); _max = (char)Math.Max(_max, val); } _data = new bool[_max - _min + 1]; readOnlySpan = input; for (int i = 0; i < readOnlySpan.Length; i++) { char c = readOnlySpan[i]; _data[c - _min] = true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Contains(char c) { uint num = (uint)(c - _min); bool[] data = _data; if (num < data.Length) { return data[num]; } return false; } } } namespace Jint { internal sealed class Agent { private readonly List<JsValue> _keptAlive = new List<JsValue>(); public void AddToKeptObjects(JsValue target) { _keptAlive.Add(target); } public void ClearKeptObjects() { _keptAlive.Clear(); } } public static class AstExtensions { internal readonly record struct Record(JsValue Key, ScriptFunction Closure); private sealed class MinimalSyntaxElement : Node { public MinimalSyntaxElement(in SourceLocation location) : base((NodeType)0) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) ((Node)this).set_Location(location); } protected override IEnumerator<Node>? GetChildNodes() { throw new NotImplementedException(); } protected override object? Accept(AstVisitor visitor) { throw new NotImplementedException(); } } private sealed class PrivateIdentifierValidator : AstVisitor { private readonly Realm _realm; private HashSet<PrivateIdentifier>? _privateNames; public PrivateIdentifierValidator(Realm realm, HashSet<PrivateIdentifier>? privateNames) { _realm = realm; _privateNames = privateNames; } protected override object VisitPrivateIdentifier(PrivateIdentifier privateIdentifier) { if (_privateNames == null || !_privateNames.Contains(privateIdentifier)) { Throw(_realm, privateIdentifier); } return privateIdentifier; } protected override object VisitClassBody(ClassBody classBody) { HashSet<PrivateIdentifier> privateNames = _privateNames; _privateNames = new HashSet<PrivateIdentifier>(PrivateIdentifierNameComparer._instance); ((Node)(object)classBody).PrivateBoundIdentifiers(_privateNames); ((AstVisitor)this).VisitClassBody(classBody); _privateNames = privateNames; return classBody; } [MethodImpl(MethodImplOptions.NoInlining)] private static void Throw(Realm r, PrivateIdentifier id) { ExceptionHelper.ThrowSyntaxError(r, "Private field '#" + id.Name + "' must be declared in an enclosing class"); } } internal static readonly SourceLocation DefaultLocation; public static JsValue GetKey<T>(this T property, Engine engine) where T : IProperty { return ((IProperty)property).Key.GetKey(engine, ((IProperty)property).Computed); } public static JsValue GetKey(this Expression expression, Engine engine, bool resolveComputed = false) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) JsValue jsValue = expression.TryGetKey<Expression>(engine, resolveComputed); if ((object)jsValue != null) { return Jint.Runtime.TypeConverter.ToPropertyKey(jsValue); } NodeType type = ((Node)expression).Type; ExceptionHelper.ThrowArgumentException("Unable to extract correct key, node type: " + ((object)(NodeType)(ref type)).ToString()); return JsValue.Undefined; } internal static JsValue TryGetKey<T>(this T property, Engine engine) where T : IProperty { return ((IProperty)property).Key.TryGetKey<Expression>(engine, ((IProperty)property).Computed); } internal static JsValue TryGetKey<T>(this T expression, Engine engine, bool resolveComputed) where T : Expression { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 object obj = expression; Literal val = (Literal)((obj is Literal) ? obj : null); if (val != null) { return ((int)val.Kind == 4) ? JsValue.Null : ((JsValue)LiteralKeyToString(val)); } if (!resolveComputed) { object obj2 = expression; Identifier val2 = (Identifier)((obj2 is Identifier) ? obj2 : null); if (val2 != null) { return val2.Name; } } object obj3 = expression; PrivateIdentifier val3 = (PrivateIdentifier)((obj3 is PrivateIdentifier) ? obj3 : null); if (val3 != null) { return engine.ExecutionContext.PrivateEnvironment.Names[val3]; } if (resolveComputed) { return TryGetComputedPropertyKey(expression, engine); } return JsValue.Undefined; } internal static JsValue TryGetComputedPropertyKey<T>(T expression, Engine engine) where T : Expression { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Invalid comparison between Unknown and I4 //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Invalid comparison between Unknown and I4 //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Invalid comparison between Unknown and I4 //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Invalid comparison between Unknown and I4 NodeType type = ((Node)(object)expression).Type; if ((int)type <= 17) { if ((int)type <= 8) { if (type - 4 <= 1 || (int)type == 8) { goto IL_0053; } } else if ((int)type == 11 || (int)type == 17) { goto IL_0053; } } else if ((int)type <= 44) { if (type - 32 <= 1 || type - 43 <= 1) { goto IL_0053; } } else if ((int)type == 65 || type - 69 <= 1 || (int)type == 75) { goto IL_0053; } bool flag = false; goto IL_0059; IL_0053: flag = true; goto IL_0059; IL_0059: if (flag) { EvaluationContext context = engine._activeEvaluationContext ?? new EvaluationContext(engine); return JintExpression.Build((Expression)(object)expression).GetValue(context); } return JsValue.Undefined; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsFunctionDefinition<T>(this T node) where T : Node { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 NodeType type = ((Node)node).Type; if ((int)type == 4 || (int)type == 16 || (int)type == 32) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsStrict(this IFunction function) { StatementOrExpression body = function.Body; FunctionBody val = (FunctionBody)(object)((body is FunctionBody) ? body : null); if (val != null) { return val.Strict; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsConstantDeclaration(this Declaration d) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 VariableDeclaration val = (VariableDeclaration)(object)((d is VariableDeclaration) ? d : null); if (val != null) { return (int)val.Kind == 3; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool HasName<T>(this T node) where T : Node { if (!node.IsFunctionDefinition()) { return false; } object obj = node; IFunction val = (IFunction)((obj is IFunction) ? obj : null); if (val != null && val.Id != null) { return true; } object obj2 = node; ClassExpression val2 = (ClassExpression)((obj2 is ClassExpression) ? obj2 : null); if (val2 != null && val2.Id != null) { return true; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsAnonymousFunctionDefinition<T>(this T node) where T : Node { if (!node.IsFunctionDefinition()) { return false; } if (node.HasName()) { return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsOptional<T>(this T node) where T : Expression { object obj = node; IChainElement val = (IChainElement)((obj is IChainElement) ? obj : null); if (val != null) { return val.Optional; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static string LiteralKeyToString(Literal literal) { StringLiteral val = (StringLiteral)(object)((literal is StringLiteral) ? literal : null); if (val != null) { return val.Value; } NumericLiteral val2 = (NumericLiteral)(object)((literal is NumericLiteral) ? literal : null); if (val2 != null) { return Jint.Runtime.TypeConverter.ToString(val2.Value); } BigIntLiteral val3 = (BigIntLiteral)(object)((literal is BigIntLiteral) ? literal : null); if (val3 != null) { return val3.Value.ToString((IFormatProvider?)null); } return Convert.ToString(literal.Value, null) ?? ""; } internal static void GetBoundNames(this VariableDeclaration variableDeclaration, List<Key> target) { ref NodeList<VariableDeclarator> declarations = variableDeclaration.Declarations; for (int i = 0; i < declarations.Count; i++) { declarations[i].Id.GetBoundNames(target); } } internal static void GetBoundNames(this Node? parameter, List<Key> target) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected O, but got Unknown if (parameter == null || (int)parameter.Type == 42) { return; } Identifier val = (Identifier)(object)((parameter is Identifier) ? parameter : null); if (val != null) { target.Add(val.Name); return; } VariableDeclaration val2 = (VariableDeclaration)(object)((parameter is VariableDeclaration) ? parameter : null); if (val2 != null) { val2.GetBoundNames(target); return; } while (true) { Identifier val3 = (Identifier)(object)((parameter is Identifier) ? parameter : null); if (val3 != null) { target.Add(val3.Name); return; } RestElement val4 = (RestElement)(object)((parameter is RestElement) ? parameter : null); if (val4 != null) { parameter = val4.Argument; continue; } ArrayPattern val5 = (ArrayPattern)(object)((parameter is ArrayPattern) ? parameter : null); if (val5 != null) { ref NodeList<Node> elements = val5.Elements; for (int i = 0; i < elements.Count; i++) { elements[i].GetBoundNames(target); } return; } ObjectPattern val6 = (ObjectPattern)(object)((parameter is ObjectPattern) ? parameter : null); if (val6 != null) { ref NodeList<Node> properties = val6.Properties; for (int j = 0; j < properties.Count; j++) { Node val7 = properties[j]; AssignmentProperty val8 = (AssignmentProperty)(object)((val7 is AssignmentProperty) ? val7 : null); if (val8 != null) { ((Property)val8).Value.GetBoundNames(target); } else { ((Node?)(RestElement)val7).GetBoundNames(target); } } return; } AssignmentPattern val9 = (AssignmentPattern)(object)((parameter is AssignmentPattern) ? parameter : null); if (val9 == null) { break; } parameter = val9.Left; } ClassDeclaration val10 = (ClassDeclaration)(object)((parameter is ClassDeclaration) ? parameter : null); if (val10 != null) { Identifier id = val10.Id; string text = ((id != null) ? id.Name : null); if (text != null) { target.Add(text); } } } internal static void PrivateBoundIdentifiers(this Node parameter, HashSet<PrivateIdentifier> target) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Invalid comparison between Unknown and I4 //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if ((int)parameter.Type == 51) { target.Add((PrivateIdentifier)parameter); return; } NodeType type = parameter.Type; if (((int)type == 1 || (int)type == 46 || (int)type == 54) ? true : false) { Expression key = ((ClassProperty)parameter).Key; PrivateIdentifier val = (PrivateIdentifier)(object)((key is PrivateIdentifier) ? key : null); if (val != null) { target.Add(val); } } else if ((int)parameter.Type == 14) { ref NodeList<Node> body = ((ClassBody)parameter).Body; for (int i = 0; i < body.Count; i++) { body[i].PrivateBoundIdentifiers(target); } } } internal static void BindingInitialization(this Node? expression, EvaluationContext context, JsValue value, Jint.Runtime.Environments.Environment env) { Identifier val = (Identifier)(object)((expression is Identifier) ? expression : null); if (val != null) { ((DeclarativeEnvironment)env).CreateMutableBindingAndInitialize(val.Name, canBeDeleted: false, value); return; } DestructuringPattern val2 = (DestructuringPattern)(object)((expression is DestructuringPattern) ? expression : null); if (val2 != null) { DestructuringPatternAssignmentExpression.ProcessPatterns(context, val2, value, env); } } internal static Record DefineMethod<T>(this T m, ObjectInstance obj, ObjectInstance? functionPrototype = null) where T : IProperty { Engine engine = obj.Engine; JsValue key = Jint.Runtime.TypeConverter.ToPropertyKey(m.GetKey(engine)); Intrinsics intrinsics = engine.Realm.Intrinsics; Jint.Runtime.Environments.ExecutionContext executionContext = engine.ExecutionContext; Jint.Runtime.Environments.Environment lexicalEnvironment = executionContext.LexicalEnvironment; PrivateEnvironment privateEnvironment = executionContext.PrivateEnvironment; ObjectInstance functionPrototype2 = functionPrototype ?? intrinsics.Function.PrototypeObject; Node value = ((IProperty)m).Value; Node obj2 = ((value is IFunction) ? value : null); if (obj2 == null) { ExceptionHelper.ThrowSyntaxError(engine.Realm); } JintFunctionDefinition jintFunctionDefinition = new JintFunctionDefinition((IFunction)(object)obj2); ScriptFunction scriptFunction = intrinsics.Function.OrdinaryFunctionCreate(functionPrototype2, jintFunctionDefinition, jintFunctionDefinition.ThisMode, lexicalEnvironment, privateEnvironment); scriptFunction.MakeMethod(obj); return new Record(key, scriptFunction); } internal unsafe static void GetImportEntries(this ImportDeclaration import, List<ImportEntry> importEntries, HashSet<ModuleRequest> requestedModules) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) string value = import.Source.Value; NodeList<ImportDeclarationSpecifier> specifiers = Unsafe.Read<NodeList<ImportDeclarationSpecifier>>((void*)import.Specifiers); ModuleImportAttribute[] attributes = GetAttributes(import.Attributes); requestedModules.Add(new ModuleRequest(value, attributes)); Enumerator<ImportDeclarationSpecifier> enumerator = specifiers.GetEnumerator(); try { while (enumerator.MoveNext()) { ImportDeclarationSpecifier current = enumerator.Current; ImportNamespaceSpecifier val = (ImportNamespaceSpecifier)(object)((current is ImportNamespaceSpecifier) ? current : null); if (val == null) { ImportSpecifier val2 = (ImportSpecifier)(object)((current is ImportSpecifier) ? current : null); if (val2 == null) { ImportDefaultSpecifier val3 = (ImportDefaultSpecifier)(object)((current is ImportDefaultSpecifier) ? current : null); if (val3 != null) { importEntries.Add(new ImportEntry(new ModuleRequest(value, attributes), "default", ((Expression)(object)((ImportDeclarationSpecifier)val3).Local).GetModuleKey())); } } else { importEntries.Add(new ImportEntry(new ModuleRequest(value, attributes), val2.Imported.GetModuleKey(), ((Expression)(object)((ImportDeclarationSpecifier)val2).Local).GetModuleKey())); } } else { importEntries.Add(new ImportEntry(new ModuleRequest(value, attributes), "*", ((Expression)(object)((ImportDeclarationSpecifier)val).Local).GetModuleKey())); } } } finally { ((IDisposable)enumerator).Dispose(); } } private static ModuleImportAttribute[] GetAttributes(in NodeList<ImportAttribute> importAttributes) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (importAttributes.Count == 0) { return Array.Empty<ModuleImportAttribute>(); } ModuleImportAttribute[] array = new ModuleImportAttribute[importAttributes.Count]; for (int i = 0; i < importAttributes.Count; i++) { ImportAttribute val = importAttributes[i]; Expression key = val.Key; Identifier val2 = (Identifier)(object)((key is Identifier) ? key : null); string key2 = ((val2 != null) ? val2.Name : ((StringLiteral)val.Key).Value); array[i] = new ModuleImportAttribute(key2, val.Value.Value); } return array; } internal static void GetExportEntries(this ExportDeclaration export, List<ExportEntry> exportEntries, HashSet<ModuleRequest> requestedModules) { ExportDefaultDeclaration val = (ExportDefaultDeclaration)(object)((export is ExportDefaultDeclaration) ? export : null); if (val == null) { ExportAllDeclaration val2 = (ExportAllDeclaration)(object)((export is ExportAllDeclaration) ? export : null); if (val2 == null) { ExportNamedDeclaration val3 = (ExportNamedDeclaration)(object)((export is ExportNamedDeclaration) ? export : null); if (val3 == null) { return; } ref NodeList<ExportSpecifier> specifiers = val3.Specifiers; if (specifiers.Count == 0) { ModuleRequest? moduleRequest = ((val3.Source != null) ? new ModuleRequest?(new ModuleRequest(val3.Source.Value, Array.Empty<ModuleImportAttribute>())) : null); GetExportEntries(defaultExport: false, (StatementOrExpression)(object)val3.Declaration, exportEntries, moduleRequest); } else { for (int i = 0; i < specifiers.Count; i++) { ExportSpecifier val4 = specifiers[i]; if (val3.Source != null) { exportEntries.Add(new ExportEntry(val4.Exported.GetModuleKey(), new ModuleRequest(val3.Source.Value, Array.Empty<ModuleImportAttribute>()), val4.Local.GetModuleKey(), null)); } else { exportEntries.Add(new ExportEntry(val4.Exported.GetModuleKey(), null, null, val4.Local.GetModuleKey())); } } } if (val3.Source != null) { requestedModules.Add(new ModuleRequest(val3.Source.Value, Array.Empty<ModuleImportAttribute>())); } } else { requestedModules.Add(new ModuleRequest(val2.Source.Value, Array.Empty<ModuleImportAttribute>())); Expression exported = val2.Exported; exportEntries.Add(new ExportEntry((exported != null) ? exported.GetModuleKey() : null, new ModuleRequest(val2.Source.Value, Array.Empty<ModuleImportAttribute>()), "*", null)); } } else { GetExportEntries(defaultExport: true, val.Declaration, exportEntries); } } private static void GetExportEntries(bool defaultExport, StatementOrExpression declaration, List<ExportEntry> exportEntries, ModuleRequest? moduleRequest = null) { List<Key> exportNames = GetExportNames(declaration); if (exportNames.Count == 0) { if (defaultExport) { exportEntries.Add(new ExportEntry("default", null, null, "*default*")); } return; } for (int i = 0; i < exportNames.Count; i++) { Key key = exportNames[i]; string exportName = (defaultExport ? "default" : key.Name); exportEntries.Add(new ExportEntry(exportName, moduleRequest, null, key)); } } private static List<Key> GetExportNames(StatementOrExpression declaration) { List<Key> list = new List<Key>(); FunctionDeclaration val = (FunctionDeclaration)(object)((declaration is FunctionDeclaration) ? declaration : null); if (val == null) { ClassDeclaration val2 = (ClassDeclaration)(object)((declaration is ClassDeclaration) ? declaration : null); if (val2 == null) { ((VariableDeclaration)(object)((declaration is VariableDeclaration) ? declaration : null))?.GetBoundNames(list); } else { Identifier id = val2.Id; string text = ((id != null) ? id.Name : null); if (text != null) { list.Add(text); } } } else { Identifier id2 = val.Id; string text2 = ((id2 != null) ? id2.Name : null); if (text2 != null) { list.Add(text2); } } return list; } private static string GetModuleKey(this Expression expression) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) Expression obj = ((expression is Identifier) ? expression : null); return ((obj != null) ? ((Identifier)obj).Name : null) ?? ((StringLiteral)expression).Value; } internal static Node CreateLocationNode(in SourceLocation location) { return (Node)(object)new MinimalSyntaxElement(in location); } internal static void AllPrivateIdentifiersValid(this Script script, Realm realm, HashSet<PrivateIdentifier>? privateIdentifiers) { ((AstVisitor)new PrivateIdentifierValidator(realm, privateIdentifiers)).Visit((Node)(object)script); } } internal interface IEngineDictionary<in TKey, TValue> { int Count { get; } ref TValue this[TKey name] { get; } ref TValue GetValueRefOrNullRef(TKey key); ref TValue GetValueRefOrAddDefault(TKey key, out bool exists); } public static class ConstraintsOptionsExtensions { public static Options MaxStatements(this Options options, int maxStatements = 0) { options.WithoutConstraint((Constraint x) => x is MaxStatementsConstraint); if (maxStatements > 0 && maxStatements < int.MaxValue) { options.Constraint(new MaxStatementsConstraint(maxStatements)); } return options; } public static Options LimitMemory(this Options options, long memoryLimit) { options.WithoutConstraint((Constraint x) => x is MemoryLimitConstraint); if (memoryLimit > 0 && memoryLimit < long.MaxValue) { options.Constraint(new MemoryLimitConstraint(memoryLimit)); } return options; } public static Options TimeoutInterval(this Options options, TimeSpan timeoutInterval) { if (timeoutInterval > TimeSpan.Zero && timeoutInterval < TimeSpan.MaxValue) { options.Constraint(new TimeConstraint(timeoutInterval)); } return options; } public static Options CancellationToken(this Options options, CancellationToken cancellationToken) { options.WithoutConstraint((Constraint x) => x is CancellationConstraint); if (cancellationToken != default(CancellationToken)) { options.Constraint(new CancellationConstraint(cancellationToken)); } return options; } } public enum DeclarationBindingType { GlobalCode, FunctionCode, EvalCode } [DebuggerTypeProxy(typeof(EngineDebugView))] public sealed class Engine : IDisposable { public class AdvancedOperations { private readonly Engine _engine; public string StackTrace { get { //IL_0027: Unknown result type (might be due to invalid IL or missing references) Node lastSyntaxElement = _engine._lastSyntaxElement; if (lastSyntaxElement == null) { return string.Empty; } return _engine.CallStack.BuildCallStackString(_engine, lastSyntaxElement.Location); } } internal AdvancedOperations(Engine engine) { _engine = engine; } public void ResetCallStack() { _engine.ResetCallStack(); } public void ProcessTasks() { _engine.RunAvailableContinuations(); } public ManualPromise RegisterPromise() { return _engine.RegisterPromise(); } } private sealed class AstAnalyzer { private readonly IPreparationOptions<IParsingOptions> _preparationOptions; private readonly Dictionary<string, Jint.Runtime.Environments.Environment.BindingName> _bindingNames = new Dictionary<string, Jint.Runtime.Environments.Environment.BindingName>(StringComparer.Ordinal); public AstAnalyzer(IPreparationOptions<IParsingOptions> preparationOptions) { _preparationOptions = preparationOptions; } public void NodeVisitor(Node node, OnNodeContext _) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Invalid comparison between Unknown and I4 //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Invalid comparison between Unknown and I4 //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Invalid comparison between Unknown and I4 //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Expected O, but got Unknown //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Invalid comparison between Unknown and I4 //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Invalid comparison between Unknown and I4 //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Expected O, but got Unknown //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Invalid comparison between Unknown and I4 //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Invalid comparison between Unknown and I4 //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Expected O, but got Unknown //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Invalid comparison between Unknown and I4 //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Invalid comparison between Unknown and I4 NodeType type = node.Type; if ((int)type <= 33) { if ((int)type <= 8) { if ((int)type != 4) { if ((int)type != 8) { return; } NonLogicalBinaryExpression val = (NonLogicalBinaryExpression)node; if (!_preparationOptions.FoldConstants || (int)((BinaryExpression)val).Operator == 32 || (int)((BinaryExpression)val).Operator == 31 || val == null) { return; } Expression left = ((BinaryExpression)val).Left; Literal val2 = (Literal)(object)((left is Literal) ? left : null); if (val2 == null) { return; } Expression right = ((BinaryExpression)val).Right; Literal val3 = (Literal)(object)((right is Literal) ? right : null); if (val3 == null) { return; } JsValue? jsValue = JintLiteralExpression.ConvertToJsValue(val2); JsValue jsValue2 = JintLiteralExpression.ConvertToJsValue(val3); if ((object)jsValue == null || (object)jsValue2 == null) { return; } try { JintExpression jintExpression = JintBinaryExpression.Build(val); EvaluationContext context = new EvaluationContext(); node.UserData = new JintConstantExpression((Expression)(object)val, (JsValue)jintExpression.EvaluateWithoutNodeTracking(context)); return; } catch { return; } } } else { if ((int)type == 9) { node.UserData = JintBlockStatement.BuildState((BlockStatement)node); return; } if (type - 31 > 1) { if ((int)type == 33) { Identifier val4 = (Identifier)node; string name = val4.Name; if (!_bindingNames.TryGetValue(name, out Jint.Runtime.Environments.Environment.BindingName value)) { value = (_bindingNames[name] = new Jint.Runtime.Environments.Environment.BindingName(JsString.CachedCreate(name))); } node.UserData = new JintIdentifierExpression(val4, value); } return; } } node.UserData = JintFunctionDefinition.BuildState((IFunction)node); } else if ((int)type <= 44) { if ((int)type != 42) { if ((int)type == 44) { node.UserData = JintMemberExpression.InitializeDeterminedProperty((MemberExpression)node, cache: true); } } else { Literal val5 = (Literal)node; JsValue jsValue3 = JintLiteralExpression.ConvertToJsValue(val5); node.UserData = (((object)jsValue3 != null) ? new JintConstantExpression((Expression)(object)val5, jsValue3) : null); } } else if ((int)type != 52) { if ((int)type != 56) { if ((int)type == 69) { node.UserData = JintUnaryExpression.BuildConstantExpression((NonUpdateUnaryExpression)node); } return; } ReturnStatement val6 = (ReturnStatement)node; Expression argument = val6.Argument; Literal val7 = (Literal)(object)((argument is Literal) ? argument : null); if (val7 != null) { JsValue jsValue4 = JintLiteralExpression.ConvertToJsValue(val7); if ((object)jsValue4 != null) { node.UserData = new ConstantStatement((Statement)(object)val6, CompletionType.Return, jsValue4); } } } else { node.UserData = new CachedHoistingScope((Program)node); } } } public class ConstraintOperations { private readonly Engine _engine; internal ConstraintOperations(Engine engine) { _engine = engine; } public void Check() { Constraint[] constraints = _engine._constraints; for (int i = 0; i < constraints.Length; i++) { constraints[i].Check(); } } public T? Find<T>() where T : Constraint { Constraint[] constraints = _engine._constraints; foreach (Constraint constraint in constraints) { if (constraint.GetType() == typeof(T)) { return (T)constraint; } } return null; } public void Reset() { Constraint[] constraints = _engine._constraints; for (int i = 0; i < constraints.Length; i++) { constraints[i].Reset(); } } } internal readonly record struct ClrPropertyDescriptorFactoriesKey(Type Type, Key PropertyName); [DebuggerDisplay("Engine")] private sealed class EngineDebugView { private readonly Engine _engine; public ObjectInstance Globals => _engine.Realm.GlobalObject; public Options Options => _engine.Options; public Jint.Runtime.Environments.Environment VariableEnvironment => _engine.ExecutionContext.VariableEnvironment; public Jint.Runtime.Environments.Environment LexicalEnvironment => _engine.ExecutionContext.LexicalEnvironment; public EngineDebugView(Engine engine) { _engine = engine; } } public class ModuleOperations { private readonly Engine _engine; private readonly Dictionary<string, Jint.Runtime.Modules.Module> _modules = new Dictionary<string, Jint.Runtime.Modules.Module>(StringComparer.Ordinal); private readonly Dictionary<string, ModuleBuilder> _builders = new Dictionary<string, ModuleBuilder>(StringComparer.Ordinal); internal IModuleLoader ModuleLoader { get; } public ModuleOperations(Engine engine, IModuleLoader moduleLoader) { ModuleLoader = moduleLoader; _engine = engine; } internal Jint.Runtime.Modules.Module Load(string? referencingModuleLocation, ModuleRequest request) { ResolvedSpecifier resolvedSpecifier = ModuleLoader.Resolve(referencingModuleLocation, request); if (_modules.TryGetValue(resolvedSpecifier.Key, out Jint.Runtime.Modules.Module value)) { return value; } value = ((!_builders.TryGetValue(resolvedSpecifier.Key, out ModuleBuilder value2)) ? LoadFromModuleLoader(resolvedSpecifier) : LoadFromBuilder(resolvedSpecifier.Key, value2, resolvedSpecifier)); if (value is SourceTextModule sourceTextModule) { _engine.Debugger.OnBeforeEvaluate((Program)(object)sourceTextModule._source); } return value; } private BuilderModule LoadFromBuilder(string specifier, ModuleBuilder moduleBuilder, ResolvedSpecifier moduleResolution) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) Prepared<Module> source = moduleBuilder.Parse(); BuilderModule builderModule = new BuilderModule(_engine, _engine.Realm, in source, ((Node)source.Program).Location.SourceFile, async: false); _modules[moduleResolution.Key] = builderModule; moduleBuilder.BindExportedValues(builderModule); _builders.Remove(specifier); return builderModule; } private Jint.Runtime.Modules.Module LoadFromModuleLoader(ResolvedSpecifier moduleResolution) { Jint.Runtime.Modules.Module module = ModuleLoader.LoadModule(_engine, moduleResolution); _modules[moduleResolution.Key] = module; return module; } public void Add(string specifier, string code) { ModuleBuilder moduleBuilder = new ModuleBuilder(_engine, specifier); moduleBuilder.AddSource(code); Add(specifier, moduleBuilder); } public void Add(string specifier, Action<ModuleBuilder> buildModule) { ModuleBuilder moduleBuilder = new ModuleBuilder(_engine, specifier); buildModule(moduleBuilder); Add(specifier, moduleBuilder); } public void Add(string specifier, ModuleBuilder moduleBuilder) { _builders.Add(specifier, moduleBuilder); } public ObjectInstance Import(string specifier) { return Import(specifier, null); } internal ObjectInstance Import(string specifier, string? referencingModuleLocation) { return Import(new ModuleRequest(specifier, Array.Empty<ModuleImportAttribute>()), referencingModuleLocation); } internal ObjectInstance Import(ModuleRequest request, string? referencingModuleLocation) { ResolvedSpecifier resolvedSpecifier = ModuleLoader.Resolve(referencingModuleLocation, request); if (!_modules.TryGetValue(resolvedSpecifier.Key, out Jint.Runtime.Modules.Module value)) { value = Load(referencingModuleLocation, request); } CyclicModule cyclicModule = value as CyclicModule; if ((object)cyclicModule == null) { LinkModule(request.Specifier, value); EvaluateModule(request.Specifier, value); } else if (cyclicModule.Status == ModuleStatus.Unlinked) { LinkModule(request.Specifier, cyclicModule); if (cyclicModule.Status == ModuleStatus.Linked) { _engine.ExecuteWithConstraints(strict: true, () => EvaluateModule(request.Specifier, cyclicModule)); } if (cyclicModule.Status != ModuleStatus.Evaluated) { ExceptionHelper.ThrowNotSupportedException($"Error while evaluating module: Module is in an invalid state: '{cyclicModule.Status}'"); } } _engine.RunAvailableContinuations(); return Jint.Runtime.Modules.Module.GetModuleNamespace(value); } private static void LinkModule(string specifier, Jint.Runtime.Modules.Module module) { module.Link(); } private JsValue EvaluateModule(string specifier, Jint.Runtime.Modules.Module module) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) bool flag = _engine._activeEvaluationContext == null; Engine engine = _engine; if (engine._activeEvaluationContext == null) { engine._activeEvaluationContext = new EvaluationContext(_engine); } JsValue jsValue; try { jsValue = module.Evaluate(); } finally { if (flag) { _engine._activeEvaluationContext = null; } } if (!(jsValue is JsPromise jsPromise)) { ExceptionHelper.ThrowInvalidOperationException($"Error while evaluating module: Module evaluation did not return a promise: {jsValue.Type}"); } else if (jsPromise.State == PromiseState.Rejected) { SourceLocation location = ((module is CyclicModule cyclicModule) ? cyclicModule.AbnormalCompletionLocation : SourceLocation.From(default(Position), default(Position), (string)null)); Node val = AstExtensions.CreateLocationNode(in location); Engine engine2 = _engine; JsValue value = jsPromise.Value; SourceLocation location2 = val.Location; ExceptionHelper.ThrowJavaScriptException(engine2, value, in location2); } else if (jsPromise.State != PromiseState.Fulfilled) { ExceptionHelper.ThrowInvalidOperationException($"Error while evaluating module: Module evaluation did not return a fulfilled promise: {jsPromise.State}"); } return jsValue; } } private static readonly Options _defaultEngineOptions = new Options(); private readonly Parser _defaultParser; private ParserOptions? _defaultModuleParserOptions; private readonly ExecutionContextStack _executionContexts; private JsValue _completionValue; internal EvaluationContext? _activeEvaluationContext; internal ErrorDispatchInfo? _error; private readonly EventLoop _eventLoop; private readonly Agent _agent; private DebugHandler? _debugger; internal readonly IObjectConverter[]? _objectConverters; internal readonly Constraint[] _constraints; internal readonly bool _isDebugMode; internal readonly bool _isStrict; private readonly bool _customResolver; internal readonly IReferenceResolver _referenceResolver; internal readonly ReferencePool _referencePool; internal readonly ArgumentsInstancePool _argumentsInstancePool; internal readonly JsValueArrayPool _jsValueArrayPool; internal readonly ExtensionMethodCache _extensionMethods; internal readonly Dictionary<string, Type?> TypeCache; internal Dictionary<Type, TypeReference>? _typeReferences; internal ConditionalWeakTable<object, ObjectInstance>? _objectWrapperCache; internal readonly JintCallStack CallStack; internal readonly StackGuard _stackGuard; internal Intrinsics _originalIntrinsics; internal Host _host; internal Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor> _reflectionAccessors; internal Realm? _realmInConstruction; internal Node? _lastSyntaxElement; internal const bool FoldConstantsOnPrepareByDefault = true; internal static readonly ParserOptions BaseParserOptions; public AdvancedOperations Advanced { get; } public ConstraintOperations Constraints { get; } public ITypeConverter TypeConverter { get; internal set; } internal ref readonly Jint.Runtime.Environments.ExecutionContext ExecutionContext { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _executionContexts.Peek(); } } internal Realm Realm => _realmInConstruction ?? ExecutionContext.Realm; public Intrinsics Intrinsics => Realm.Intrinsics; public ObjectInstance Global => Realm.GlobalObject; internal GlobalSymbolRegistry GlobalSymbolRegistry { get; } internal long CurrentMemoryUsage { get; private set; } internal Options Options { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; private set; } public DebugHandler Debugger => _debugger ?? (_debugger = new DebugHandler(this, Options.Debugger.InitialStepMode)); internal ParserOptions DefaultModuleParserOptions => _defaultModuleParserOptions ?? (_defaultModuleParserOptions = ModuleParsingOptions.Default.GetParserOptions(Options)); public ModuleOperations Modules { get; internal set; } public static Prepared<Script> PrepareScript(string code, string? source = null, bool strict = false, ScriptPreparationOptions? options = null) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if ((object)options == null) { options = ScriptPreparationOptions.Default; } AstAnalyzer astAnalyzer = new AstAnalyzer(options); ParserOptions parserOptions = options.GetParserOptions(); ParserOptions obj = parserOptions.<Clone>$(); obj.set_OnNode(new OnNodeHandler(astAnalyzer.NodeVisitor)); Parser val = new Parser(obj); try { return new Prepared<Script>(val.ParseScript(code, source, strict), parserOptions); } catch (Exception ex) { throw new ScriptPreparationException("Could not prepare script: " + ex.Message, ex); } } public static Prepared<Module> PrepareModule(string code, string? source = null, ModulePreparationOptions? options = null) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown if ((object)options == null) { options = ModulePreparationOptions.Default; } AstAnalyzer astAnalyzer = new AstAnalyzer(options); ParserOptions parserOptions = options.GetParserOptions(); ParserOptions obj = parserOptions.<Clone>$(); obj.set_OnNode(new OnNodeHandler(astAnalyzer.NodeVisitor)); Parser val = new Parser(obj); try { return new Prepared<Module>(val.ParseModule(code, source), parserOptions); } catch (Exception ex) { throw new ScriptPreparationException("Could not prepare script: " + ex.Message, ex); } } public Engine() : this(null, null) { } public Engine(Action<Options>? options) { Action<Options> options2 = options; this..ctor(null, (options2 != null) ? ((Action<Engine, Options>)delegate(Engine _, Options opts) { options2(opts); }) : null); } public Engine(Options options) : this(options, null) { } public Engine(Action<Engine, Options> options) : this(null, options) { } private Engine(Options? options, Action<Engine, Options>? configure) { //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Expected O, but got Unknown _completionValue = JsValue.Undefined; _eventLoop = new EventLoop(); _agent = new Agent(); TypeCache = new Dictionary<string, Type>(StringComparer.Ordinal); _reflectionAccessors = new Dictionary<ClrPropertyDescriptorFactoriesKey, ReflectionAccessor>(); GlobalSymbolRegistry = new GlobalSymbolRegistry(); base..ctor(); Advanced = new AdvancedOperations(this); Constraints = new ConstraintOperations(this); TypeConverter = new DefaultTypeConverter(this); _executionContexts = new ExecutionContextStack(2); Options = options ?? ((configure != null) ? new Options() : _defaultEngineOptions); configure?.Invoke(this, Options); _extensionMethods = ExtensionMethodCache.Build(Options.Interop.ExtensionMethodTypes); Reset(); _isDebugMode = Options.Debugger.Enabled; _isStrict = Options.Strict; _objectConverters = ((Options.Interop.ObjectConverters.Count > 0) ? Options.Interop.ObjectConverters.ToArray() : null); _constraints = Options.Constraints.Constraints.ToArray(); _referenceResolver = Options.ReferenceResolver; _customResolver = _referenceResolver != DefaultReferenceResolver.Instance; _referencePool = new ReferencePool(); _argumentsInstancePool = new ArgumentsInstancePool(this); _jsValueArrayPool = new JsValueArrayPool(); Options.Apply(this); CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0); _stackGuard = new StackGuard(this); ParserOptions parserOptions = ScriptParsingOptions.Default.GetParserOptions(Options); _defaultParser = new Parser(parserOptions); } private void Reset() { _host = Options.Host.Factory(this); _host.Initialize(this); } internal ParserOptions GetActiveParserOptions() { return _executionContexts?.GetActiveParserOptions() ?? _defaultParser.Options; } internal Parser GetParserFor(ScriptParsingOptions parsingOptions) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if ((object)parsingOptions != ScriptParsingOptions.Default) { return new Parser(parsingOptions.GetParserOptions(Options)); } return _defaultParser; } internal Parser GetParserFor(ParserOptions parserOptions) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown if (parserOptions != _defaultParser.Options) { return new Parser(parserOptions); } return _defaultParser; } internal void EnterExecutionContext(Jint.Runtime.Environments.Environment lexicalEnvironment, Jint.Runtime.Environments.Environment variableEnvironment, Realm realm, PrivateEnvironment? privateEnvironment) { Jint.Runtime.Environments.ExecutionContext context = new Jint.Runtime.Environments.ExecutionContext(null, lexicalEnvironment, variableEnvironment, privateEnvironment, realm); _executionContexts.Push(in context); } internal void EnterExecutionContext(in Jint.Runtime.Environments.ExecutionContext context) { _executionContexts.Push(in context); } public Engine SetValue(string name, Delegate value) { Realm.GlobalObject.FastSetProperty(name, new Jint.Runtime.Descriptors.PropertyDescriptor(new DelegateWrapper(this, value), PropertyFlag.NonEnumerable)); return this; } public Engine SetValue(string name, string? value) { return SetValue(name, (value == null) ? JsValue.Null : JsString.Create(value)); } public Engine SetValue(string name, double value) { return SetValue(name, (JsValue)JsNumber.Create(value)); } public Engine SetValue(string name, int value) { return SetValue(name, (JsValue)JsNumber.Create(value)); } public Engine SetValue(string name, bool value) { return SetValue(name, (JsValue)(value ? JsBoolean.True : JsBoolean.False)); } public Engine SetValue(string name, JsValue value) { Realm.GlobalObject.Set(name, value); return this; } public Engine SetValue(string name, object? obj) { JsValue value = ((obj is Type type) ? TypeReference.CreateTypeReference(this, type) : JsValue.FromObject(this, obj)); return SetValue(name, value); } public Engine SetValue(string name, Type type) { return SetValue(name, TypeReference.CreateTypeReference(this, type)); } public Engine SetValue<T>(string name, T? obj) { if (!((object)obj is Type type)) { return SetValue(name, JsValue.FromObject(this, obj)); } return SetValue(name, type); } internal void LeaveExecutionContext() { _ = ref _executionContexts.Pop(); } internal void ResetConstraints() { Constraint[] constraints = _constraints; for (int i = 0; i < constraints.Length; i++) { constraints[i].Reset(); } } internal void ResetCallStack() { CallStack.Clear(); } public JsValue Evaluate(string code, string? source = null) { Script program = _defaultParser.ParseScriptGuarded(Realm, code, source ?? "<anonymous>", _isStrict); Prepared<Script> preparedScript = new Prepared<Script>(program, _defaultParser.Options); return Evaluate(in preparedScript); } public JsValue Evaluate(string code, ScriptParsingOptions parsingOptions) { return Evaluate(code, "<anonymous>", parsingOptions); } public JsValue Evaluate(string code, string source, ScriptParsingOptions parsingOptions) { Parser parserFor = GetParserFor(parsingOptions); Script program = parserFor.ParseScriptGuarded(Realm, code, source, _isStrict); Prepared<Script> preparedScript = new Prepared<Script>(program, parserFor.Options); return Evaluate(in preparedScript); } public JsValue Evaluate(in Prepared<Script> preparedScript) { return Execute(in preparedScript)._completionValue; } public Engine Execute(string code, string? source = null) { Script program = _defaultParser.ParseScriptGuarded(Realm, code, source ?? "<anonymous>", _isStrict); Prepared<Script> preparedScript = new Prepared<Script>(program, _defaultParser.Options); return Execute(in preparedScript); } public Engine Execute(string code, ScriptParsingOptions parsingOptions) { return Execute(code, "<anonymous>", parsingOptions); } public Engine Execute(string code, string source, ScriptParsingOptions parsingOptions) { Parser parserFor = GetParserFor(parsingOptions); Script program = parserFor.ParseScriptGuarded(Realm, code, source, _isStrict); Prepared<Script> preparedScript = new Prepared<Script>(program, parserFor.Options); return Execute(in preparedScript); } public Engine Execute(in Prepared<Script> preparedScript) { if (!preparedScript.IsValid) { ExceptionHelper.ThrowInvalidPreparedScriptArgumentException("preparedScript"); } Script script = preparedScript.Program; ParserOptions parserOptions = preparedScript.ParserOptions; bool strict = _isStrict || script.Strict; ExecuteWithConstraints(strict, () => ScriptEvaluation(new ScriptRecord(Realm, script, ((Node)script).Location.SourceFile), parserOptions)); return this; } private Engine ScriptEvaluation(ScriptRecord scriptRecord, ParserOptions parserOptions) { Debugger.OnBeforeEvaluate((Program)(object)scriptRecord.EcmaScriptCode); GlobalEnvironment globalEnv = Realm.GlobalEnv; Jint.Runtime.Environments.ExecutionContext context = new Jint.Runtime.Environments.ExecutionContext(scriptRecord, globalEnv, globalEnv, null, Realm, null, null, parserOptions); EnterExecutionContext(in context); try { Script ecmaScriptCode = scriptRecord.EcmaScriptCode; GlobalDeclarationInstantiation(ecmaScriptCode, globalEnv); JintStatementList jintStatementList = new JintStatementList(null, ((Program)ecmaScriptCode).Body); Completion completion; try { completion = jintStatementList.Execute(_activeEvaluationContext); } catch { ResetCallStack(); throw; } if (completion.Type == CompletionType.Throw) { JavaScriptException ex = new JavaScriptException(completion.GetValueOrDefault()).SetJavaScriptCallstack(this, in completion.Location); ResetCallStack(); throw ex; } _completionValue = completion.GetValueOrDefault(); RunAvailableContinuations(); return this; } finally { LeaveExecutionContext(); } } internal ManualPromise RegisterPromise() { JsPromise obj = new JsPromise(this) { _prototype = Realm.Intrinsics.Promise.PrototypeObject }; var (settle2, settle3) = obj.CreateResolvingFunctions(); return new ManualPromise(Reject: SettleWith(settle3), Promise: obj, Resolve: SettleWith(settle2)); Action<JsValue> SettleWith(Function settle) { Function settle4 = settle; return delegate(JsValue value) { settle4.Call(JsValue.Undefined, new JsValue[1] { value }); RunAvailableContinuations(); }; } } internal void AddToEventLoop(Action continuation) { _eventLoop.Events.Enqueue(continuation); } internal void AddToKeptObjects(JsValue target) { _agent.AddToKeptObjects(target); } internal void RunAvailableContinuations() { DoProcessEventLoop(_eventLoop.Events); } private static void DoProcessEventLoop(ConcurrentQueue<Action> queue) { Action result; while (queue.TryDequeue(out result)) { result(); } } internal void RunBeforeExecuteStatementChecks(StatementOrExpression? statement) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between Unknown and I4 Constraint[] constraints = _constraints; for (int i = 0; i < constraints.Length; i++) { constraints[i].Check(); } if (_isDebugMode && statement != null && (int)((Node)statement).Type != 9) { Debugger.OnStep((Node)(object)statement); } } internal JsValue GetValue(object value) { return GetValue(value, returnReferenceToPool: false); } internal JsValue GetValue(object value, bool returnReferenceToPool) { if (value is JsValue result) { return result; } if (!(value is Reference reference)) { return ((Completion)value).Value; } return GetValue(reference, returnReferenceToPool); } internal JsValue GetValue(Reference reference, bool returnReferenceToPool) { JsValue value = reference.Base; if (value.IsUndefined()) { if (_customResolver) { reference.EvaluateAndCachePropertyKey(); if (_referenceResolver.TryUnresolvableReference(this, reference, out JsValue value2)) { return value2; } } ExceptionHelper.ThrowReferenceError(Realm, reference); } if ((value._type & InternalTypes.ObjectEnvironmentRecord) == 0 && _customResolver) { reference.EvaluateAndCachePropertyKey(); if (_referenceResolver.TryPropertyReference(this, reference, ref value)) { return value; } } if (reference.IsPropertyReference) { JsValue referencedName = reference.ReferencedName; if (returnReferenceToPool) { _referencePool.Return(reference); } if (value.IsObject()) { ObjectInstance objectInstance = Jint.Runtime.TypeConverter.ToObject(Realm, value); if (reference.IsPrivateReference) { return objectInstance.PrivateGet((PrivateName)reference.ReferencedName); } reference.EvaluateAndCachePropertyKey(); return objectInstance.Get(reference.ReferencedName, reference.ThisValue); } ObjectInstance o = null; if ((referencedName._type & (InternalTypes.String | InternalTypes.Integer)) != 0 && value is JsString s && TryHandleStringValue(referencedName, s, ref o, out JsValue jsValue)) { return jsValue; } if ((object)o == null) { o = Jint.Runtime.TypeConverter.ToObject(Realm, value); } if (reference.IsPrivateReference) { return o.PrivateGet((PrivateName)reference.ReferencedName); } return o.Get(referencedName, reference.ThisValue); } JsValue bindingValue = ((Jint.Runtime.Environments.Environment)value).GetBindingValue(reference.ReferencedName.ToString(), reference.Strict); if (returnReferenceToPool) { _referencePool.Return(reference); } return bindingValue; } private bool TryHandleStringValue(JsValue property, JsString s, ref ObjectInstance? o, out JsValue jsValue) { if (CommonProperties.Length.Equals(property)) { jsValue = JsNumber.Create((uint)s.Length); return true; } if (property is JsNumber value && value.IsInteger()) { int num = value.AsInteger(); if (num < 0 || num >= s.Length) { jsValue = JsValue.Undefined; return true; } jsValue = JsString.Create(s[num]); return true; } if (property is JsString jsString && jsString.Length > 0 && char.IsLower(jsString[0])) { o = Realm.Intrinsics.String.PrototypeObject; } jsValue = JsValue.Undefined; return false; } internal void PutValue(Reference reference, JsValue value) { JsValue referencedName = reference.ReferencedName; if (reference.IsUnresolvableReference) { if (reference.Strict && referencedName != CommonProperties.Arguments) { ExceptionHelper.ThrowReferenceError(Realm, reference); } Realm.GlobalObject.Set(referencedName, value, throwOnError: false); } else if (reference.IsPropertyReference) { ObjectInstance objectInstance = Jint.Runtime.TypeConverter.ToObject(Realm, reference.Base); if (reference.IsPrivateReference) { objectInstance.PrivateSet((PrivateName)referencedName, value); return; } reference.EvaluateAndCachePropertyKey(); if (!objectInstance.Set(reference.ReferencedName, value, reference.ThisValue) && reference.Strict) { ExceptionHelper.ThrowTypeError(Realm, $"Cannot assign to read only property '{referencedName}' of {objectInstance}"); } } else { ((Jint.Runtime.Environments.Environment)reference.Base).SetMutableBinding(Jint.Runtime.TypeConverter.ToString(referencedName), value, reference.Strict); } } public JsValue Invoke(string propertyName, params object?[] arguments) { return Invoke(propertyName, null, arguments); } public JsValue Invoke(string propertyName, object? thisObj, object?[] arguments) { JsValue value = GetValue(propertyName); return Invoke(value, thisObj, arguments); } public JsValue Invoke(JsValue value, params object?[] arguments) { return Invoke(value, null, arguments); } public JsValue Invoke(JsValue value, object? thisObj, object?[] arguments) { object?[] arguments2 = arguments; object thisObj2 = thisObj; ICallable callable = value as ICallable; if (callable == null) { ExceptionHelper.ThrowJavaScriptException(Realm.Intrinsics.TypeError, "Can only invoke functions"); } return ExecuteWithConstraints(Options.Strict, DoInvoke); JsValue DoInvoke() { JsValue[] array = _jsValueArrayPool.RentArray(arguments2.Length); for (int i = 0; i < arguments2.Length; i++) { array[i] = JsValue.FromObject(this, arguments2[i]); } JsValue thisObject = JsValue.FromObject(this, thisObj2); JsValue result; if (callable is Function function) { JintCallStack callStack = CallStack; callStack.Push(function, null, in ExecutionContext); try { result = function.Call(thisObject, array); } finally { if (callStack.Count > 0) { callStack.Pop(); } } } else { result = callable.Call(thisObject, array); } _jsValueArrayPool.ReturnArray(array); return result; } } internal T ExecuteWithConstraints<T>(bool strict, Func<T> callback) { ResetConstraints(); bool flag = _activeEvaluationContext == null; if (_activeEvaluationContext == null) { _activeEvaluationContext = new EvaluationContext(this); } try { using (new StrictModeScope(strict)) { return callback(); } } finally { if (flag) { _activeEvaluationContext = null; } ResetConstraints(); _agent.ClearKeptObjects(); } } internal JsValue Invoke(JsValue v, JsValue p, JsValue[] arguments) { bool flag = _activeEvaluationContext == null; if (_activeEvaluationContext == null) { _activeEvaluationContext = new EvaluationContext(this); } try { ICallable obj = GetV(v, p) as ICallable; if (obj == null) { ExceptionHelper.ThrowTypeErrorNoEngine("Can only invoke functions"); } return obj.Call(v, arguments); } finally { if (flag) { _activeEvaluationContext = null; } } } private JsValue GetV(JsValue v, JsValue p) { return Jint.Runtime.TypeConverter.ToObject(Realm, v).Get(p); } public JsValue GetValue(string propertyName) { return GetValue(Realm.GlobalObject, new JsString(propertyName)); } internal Node GetLastSyntaxElement() { return _lastSyntaxElement; } public JsValue GetValue(JsValue scope, JsValue property) { Reference reference = _referencePool.Rent(scope, property, _isStrict, null); JsValue value = GetValue(reference, returnReferenceToPool: false); _referencePool.Return(reference); return value; } internal Reference ResolveBinding(string name, Jint.Runtime.Environments.Environment? env = null) { if ((object)env == null) { env = ExecutionContext.LexicalEnvironment; } return GetIdentifierReference(env, name, StrictModeScope.IsStrictModeCode); } private static Reference GetIdentifierReference(Jint.Runtime.Environments.Environment? env, string name, bool strict) { Key name2 = name; while (true) { if ((object)env == null) { return new Reference(JsValue.Undefined, name, strict); } if (env.HasBinding(name2)) { break; } env = env._outerEnv; } return new Reference(env, name, strict); } internal JsValue GetNewTarget(Jint.Runtime.Environments.Environment? thisEnvironment = null) { if ((object)thisEnvironment == null) { thisEnvironment = ExecutionContext.GetThisEnvironment(); } return thisEnvironment.NewTarget ?? JsValue.Undefined; } internal JsValue ResolveThisBinding() { return ExecutionContext.GetThisEnvironment().GetThisBinding(); } private void GlobalDeclarationInstantiation(Script script, GlobalEnvironment env) { HoistingScope hoistingScope = ((Program)(object)script).GetHoistingScope(); List<FunctionDeclaration> functionDeclarations = hoistingScope._functionDeclarations; List<JintFunctionDefinition> list = new List<JintFunctionDefinition>(); HashSet<Key> hashSet = new HashSet<Key>(); List<Key> list2 = new List<Key>(); Realm realm = Realm; if (functionDeclarations != null) { for (int num = functionDeclarations.Count - 1; num >= 0; num--) { FunctionDeclaration val = functionDeclarations[num]; Key key = val.Id.Name; if (!hashSet.Contains(key)) { if (!env.CanDeclareGlobalFunction(key)) { ExceptionHelper.ThrowTypeError(realm, "Cannot declare global function " + key); } hashSet.Add(key); list.Add(new JintFunctionDefinition((IFunction)(object)val)); } } } List<Key> varNames = ((Program)(object)script).GetVarNames(hoistingScope); for (int i = 0; i < varNames.Count; i++) { Key key2 = varNames[i]; if (env.HasLexicalDeclaration(key2)) { ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{key2}' has already been declared"); } if (!hashSet.Contains(key2)) { if (!env.CanDeclareGlobalVar(key2)) { ExceptionHelper.ThrowTypeError(realm); } list2.Add(key2); } } PrivateEnvironment privateEnv = null; List<ScopedDeclaration> lexNames = ((Program)(object)script).GetLexNames(hoistingScope); for (int j = 0; j < lexNames.Count; j++) { ScopedDeclaration scopedDeclaration = lexNames[j]; Key[] boundNames = scopedDeclaration.BoundNames; foreach (Key key3 in boundNames) { if (env.HasLexicalDeclaration(key3) || env.HasRestrictedGlobalProperty(key3)) { ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{key3}' has already been declared"); } if (scopedDeclaration.IsConstantDeclaration) { env.CreateImmutableBinding(key3); } else { env.CreateMutableBinding(key3); } } } for (int num2 = list.Count - 1; num2 > -1; num2--) { JintFunctionDefinition jintFunctionDefinition = list[num2]; Key key4 = jintFunctionDefinition.Name; if (env.HasLexicalDeclaration(key4)) { ExceptionHelper.ThrowSyntaxError(realm, $"Identifier '{key4}' has already been declared"); } Function value = realm.Intrinsics.Function.InstantiateFunctionObject(jintFunctionDefinition, env, privateEnv); env.CreateGlobalFunctionBinding(key4, value, canBeDeleted: false); } env.CreateGlobalVarBindings(list2, canBeDeleted: false); } internal JsArguments? FunctionDeclarationInstantiation(Function function, JsValue[] argumentsList) { Jint.Runtime.Environments.ExecutionContext executionContext = ExecutionContext; JintFunctionDefinition functionDefinition = function._functionDefinition; FunctionEnvironment functionEnvironment = (FunctionEnvironment)ExecutionContext.LexicalEnvironment; bool flag = _isStrict || StrictModeScope.IsStrictModeCode; JintFunctionDefinition.State state = functionDefinition.Initialize(); Key[] parameterNames = state.ParameterNames; bool hasDuplicates = state.HasDuplicates; bool isSimpleParameterList = state.IsSimpleParameterList; bool hasParameterExpressions = state.HasParameterExpressions; int num; object obj; if (isSimpleParameterList) { num = ((!state.HasDuplicates) ? 1 : 0); if (num != 0) { obj = argumentsList; goto IL_0077; } } else { num = 0; } obj = null; goto IL_0077; IL_0077: JsValue[] arguments = (JsValue[])obj; functionEnvironment.InitializeParameters(parameterNames, hasDuplicates, arguments); JsArguments jsArguments = null; if (state.ArgumentsObjectNeeded || _isDebugMode) { jsArguments = ((!flag && isSimpleParameterList) ? CreateMappedArgumentsObject(function, parameterNames, argumentsList, functionEnvironment, state.HasRestParameter) : CreateUnmappedArgumentsObject(argumentsList)); if (flag) { functionEnvironment.CreateImmutableBindingAndInitialize(KnownKeys.Arguments, strict: false, jsArguments); } else { functionEnvironment.CreateMutableBindingAndInitialize(KnownKeys.Arguments, canBeDeleted: false, jsArguments); } } if (num == 0) { functionEnvironment.AddFunctionParameters(_activeEvaluationContext, functionDefinition.Function, argumentsList); } DeclarativeEnvironment declarativeEnvironment; if (!hasParameterExpressions) { List<JintFunctionDefinition.State.VariableValuePair> varsToInitialize = state.VarsToInitialize; for (int i = 0; i < varsToInitialize.Count; i++) { functionEnvironment.CreateMutableBindingAndInitialize(varsToInitialize[i].Name, canBeDeleted: false, JsValue.Undefined);
plugins/Marioalexsan.AtlyssJint.dll
Decompiled 3 weeks agousing 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.AtlyssJint")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1")] [assembly: AssemblyProduct("AtlyssJint")] [assembly: AssemblyTitle("Marioalexsan.AtlyssJint")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.1.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.AtlyssJint { [BepInPlugin("Marioalexsan.AtlyssJint", "AtlyssJint", "0.1.1")] public class AtlyssJintPlugin : BaseUnityPlugin { private void Awake() { ((BaseUnityPlugin)this).Logger.LogInfo((object)"Jint dependency should now be available."); } } internal static class ModInfo { public const string GUID = "Marioalexsan.AtlyssJint"; public const string NAME = "AtlyssJint"; public const string VERSION = "0.1.1"; } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }
plugins/System.Runtime.CompilerServices.Unsafe.dll
Decompiled 3 weeks agousing 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 { } }