From dae3ec5b7ce7d6d1848fa1063a07d1e31f2b02b9 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sat, 1 Jul 2023 10:24:55 +0300 Subject: [PATCH 01/24] Fix constructor argument matching under interop (#1568) --- .../Runtime/ConstructorSignatureTests.cs | 35 +++++++++++++++++-- Jint/Runtime/Interop/MethodDescriptor.cs | 8 ++++- Jint/Runtime/Interop/TypeReference.cs | 4 +-- .../Expressions/JintAwaitExpression.cs | 2 -- Jint/Runtime/TypeConverter.cs | 24 ++++++------- 5 files changed, 53 insertions(+), 20 deletions(-) diff --git a/Jint.Tests/Runtime/ConstructorSignatureTests.cs b/Jint.Tests/Runtime/ConstructorSignatureTests.cs index e478ade103..25cdbf92ac 100644 --- a/Jint.Tests/Runtime/ConstructorSignatureTests.cs +++ b/Jint.Tests/Runtime/ConstructorSignatureTests.cs @@ -42,6 +42,18 @@ public void CorrectOverloadShouldBeSelected() Assert.Equal("A-30", engine.Evaluate("new B('A', 30).Result")); } + + [Fact] + public void CanConstructWithMixedFloatAndEnumConstructorParameters() + { + var engine = new Engine(); + engine.SetValue("Length", TypeReference.CreateTypeReference(engine)); + Assert.Equal(12.3, engine.Evaluate("new Length(12.3).Value").AsNumber(), precision: 2); + Assert.Equal(12.3, engine.Evaluate("new Length(12.3, 0).Value").AsNumber(), precision: 2); + Assert.Equal(0, engine.Evaluate("new Length(12.3, 0).UnitValue").AsInteger()); + Assert.Equal(LengthUnit.Pixel, (LengthUnit) engine.Evaluate("new Length(12.3, 42).UnitValue").AsInteger()); + } + private class A { public A(int param1, int param2 = 5) => Result = (param1 + param2).ToString(); @@ -62,8 +74,27 @@ public B(string param1, float param2, string param3) public B(string param1, float param2) { Result = string.Join("-", param1, param2.ToString(CultureInfo.InvariantCulture)); - } + } + + public string Result { get; } + } + + private enum LengthUnit { Pixel = 42 } + + private class Length + { + public Length(float value) + : this(value, LengthUnit.Pixel) + { + } + + public Length(float value, LengthUnit unit) + { + Value = value; + UnitValue = unit; + } - public string Result { get;} + public float Value { get; } + public LengthUnit UnitValue { get; } } } diff --git a/Jint/Runtime/Interop/MethodDescriptor.cs b/Jint/Runtime/Interop/MethodDescriptor.cs index 152c9de2e3..831cbe60ad 100644 --- a/Jint/Runtime/Interop/MethodDescriptor.cs +++ b/Jint/Runtime/Interop/MethodDescriptor.cs @@ -111,7 +111,8 @@ public JsValue Call(Engine engine, object? instance, JsValue[] arguments) { for (var i = 0; i < arguments.Length; i++) { - var parameterType = methodParameters[i].ParameterType; + var methodParameter = methodParameters[i]; + var parameterType = methodParameter.ParameterType; var value = arguments[i]; object? converted; @@ -119,6 +120,11 @@ public JsValue Call(Engine engine, object? instance, JsValue[] arguments) { converted = value; } + else if (value.IsUndefined() && methodParameter.IsOptional) + { + // undefined is considered missing, null is consider explicit value + converted = methodParameter.DefaultValue; + } else if (!ReflectionExtensions.TryConvertViaTypeCoercion(parameterType, valueCoercionType, value, out converted)) { converted = engine.ClrTypeConverter.Convert( diff --git a/Jint/Runtime/Interop/TypeReference.cs b/Jint/Runtime/Interop/TypeReference.cs index 31c40789a8..8d7bb98c42 100644 --- a/Jint/Runtime/Interop/TypeReference.cs +++ b/Jint/Runtime/Interop/TypeReference.cs @@ -131,10 +131,10 @@ static ObjectInstance ObjectCreator(Engine engine, Realm realm, ObjectCreateStat } // optional parameters - if (parameters.Length >= arguments.Length) + if (parameters.Length > arguments.Length) { // all missing ones must be optional - foreach (var parameter in parameters.AsSpan(parameters.Length - arguments.Length + 1)) + foreach (var parameter in parameters.AsSpan(parameters.Length - arguments.Length)) { if (!parameter.IsOptional) { diff --git a/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs index a7ff7a305e..96d470239d 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs @@ -1,6 +1,4 @@ using Esprima.Ast; -using Jint.Native; -using Jint.Native.Object; using Jint.Native.Promise; namespace Jint.Runtime.Interpreter.Expressions; diff --git a/Jint/Runtime/TypeConverter.cs b/Jint/Runtime/TypeConverter.cs index a79e5adae0..ece06bf412 100644 --- a/Jint/Runtime/TypeConverter.cs +++ b/Jint/Runtime/TypeConverter.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Numerics; +using System.Reflection; using System.Runtime.CompilerServices; using Esprima; using Esprima.Ast; @@ -1142,9 +1143,8 @@ private static int CalculateMethodScore(Engine engine, MethodDescriptor method, for (var i = 0; i < arguments.Length; i++) { var jsValue = arguments[i]; - var paramType = method.Parameters[i].ParameterType; - var parameterScore = CalculateMethodParameterScore(engine, jsValue, paramType); + var parameterScore = CalculateMethodParameterScore(engine, method.Parameters[i], jsValue); if (parameterScore < 0) { return parameterScore; @@ -1222,12 +1222,10 @@ internal static AssignableResult IsAssignableToGenericType(Type givenType, Type /// /// Determines how well parameter type matches target method's type. /// - private static int CalculateMethodParameterScore( - Engine engine, - JsValue jsValue, - Type paramType) + private static int CalculateMethodParameterScore(Engine engine, ParameterInfo parameter, JsValue parameterValue) { - var objectValue = jsValue.ToObject(); + var paramType = parameter.ParameterType; + var objectValue = parameterValue.ToObject(); var objectValueType = objectValue?.GetType(); if (objectValueType == paramType) @@ -1237,7 +1235,7 @@ private static int CalculateMethodParameterScore( if (objectValue is null) { - if (!TypeIsNullable(paramType)) + if (!parameter.IsOptional && !TypeIsNullable(paramType)) { // this is bad return -1; @@ -1258,18 +1256,18 @@ private static int CalculateMethodParameterScore( return 5; } - if (paramType == typeof(int) && jsValue.IsInteger()) + if (paramType == typeof(int) && parameterValue.IsInteger()) { return 0; } if (paramType == typeof(float) && objectValueType == typeof(double)) { - return jsValue.IsInteger() ? 1 : 2; + return parameterValue.IsInteger() ? 1 : 2; } if (paramType.IsEnum && - jsValue is JsNumber jsNumber + parameterValue is JsNumber jsNumber && jsNumber.IsInteger() && paramType.GetEnumUnderlyingType() == typeof(int) && Enum.IsDefined(paramType, jsNumber.AsInteger())) @@ -1284,7 +1282,7 @@ jsValue is JsNumber jsNumber return 1; } - if (jsValue.IsArray() && paramType.IsArray) + if (parameterValue.IsArray() && paramType.IsArray) { // we have potential, TODO if we'd know JS array's internal type we could have exact match return 2; @@ -1315,7 +1313,7 @@ jsValue is JsNumber jsNumber } } - if (ReflectionExtensions.TryConvertViaTypeCoercion(paramType, engine.Options.Interop.ValueCoercion, jsValue, out _)) + if (ReflectionExtensions.TryConvertViaTypeCoercion(paramType, engine.Options.Interop.ValueCoercion, parameterValue, out _)) { // gray JS zone where we start to do odd things return 10; From b1df4cb437636527425a70ac1815c7184f4e8992 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 2 Jul 2023 02:05:10 -0400 Subject: [PATCH 02/24] Avoid Mono's ParameterInfo[].AsSpan() bug (#1571) --- Jint/Runtime/Interop/TypeReference.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Jint/Runtime/Interop/TypeReference.cs b/Jint/Runtime/Interop/TypeReference.cs index 8d7bb98c42..92f0f61705 100644 --- a/Jint/Runtime/Interop/TypeReference.cs +++ b/Jint/Runtime/Interop/TypeReference.cs @@ -134,9 +134,10 @@ static ObjectInstance ObjectCreator(Engine engine, Realm realm, ObjectCreateStat if (parameters.Length > arguments.Length) { // all missing ones must be optional - foreach (var parameter in parameters.AsSpan(parameters.Length - arguments.Length)) + int start = parameters.Length - arguments.Length; + for (var i = start; i < parameters.Length; i++) { - if (!parameter.IsOptional) + if (!parameters[i].IsOptional) { // use original arguments return arguments; From db73cadf0a05d2485de49380a06bf7fea5b4f3b7 Mon Sep 17 00:00:00 2001 From: Umut Akkaya Date: Sun, 2 Jul 2023 09:46:50 +0300 Subject: [PATCH 03/24] Add StackGuard for improved stack handling support (#1566) Co-authored-by: Umut Akkaya Co-authored-by: Marko Lahma --- Jint.Tests/Runtime/EngineLimitTests.cs | 70 ++++++++++++--- Jint.Tests/Runtime/EngineTests.cs | 25 ++++++ Jint/Engine.cs | 2 + Jint/Options.cs | 11 +++ Jint/Runtime/CallStack/StackGuard.cs | 87 +++++++++++++++++++ .../Expressions/JintCallExpression.cs | 5 ++ 6 files changed, 186 insertions(+), 14 deletions(-) create mode 100644 Jint/Runtime/CallStack/StackGuard.cs diff --git a/Jint.Tests/Runtime/EngineLimitTests.cs b/Jint.Tests/Runtime/EngineLimitTests.cs index a8ec746ca8..29fc160600 100644 --- a/Jint.Tests/Runtime/EngineLimitTests.cs +++ b/Jint.Tests/Runtime/EngineLimitTests.cs @@ -1,11 +1,19 @@ #if !NETFRAMEWORK using System.Text; +using Jint.Runtime; namespace Jint.Tests.Runtime; public class EngineLimitTests { + +#if RELEASE + const int FunctionNestingCount = 960; +#else + const int FunctionNestingCount = 520; +#endif + [Fact] public void ShouldAllowReasonableCallStackDepth() { @@ -15,24 +23,61 @@ public void ShouldAllowReasonableCallStackDepth() return; } -#if RELEASE - const int FunctionNestingCount = 960; -#else - const int FunctionNestingCount = 520; -#endif + var script = GenerateCallTree(FunctionNestingCount); - // generate call tree + var engine = new Engine(); + engine.Execute(script); + Assert.Equal(123, engine.Evaluate("func1(123);").AsNumber()); + Assert.Equal(FunctionNestingCount, engine.Evaluate("x").AsNumber()); + } + + [Fact] + public void ShouldNotStackoverflowWhenStackGuardEnable() + { + // Can be more than actual dotnet stacktrace count, It does not hit stackoverflow anymore. + int functionNestingCount = FunctionNestingCount * 2; + + var script = GenerateCallTree(functionNestingCount); + + var engine = new Engine(option => option.Constraints.MaxExecutionStackCount = functionNestingCount); + engine.Execute(script); + Assert.Equal(123, engine.Evaluate("func1(123);").AsNumber()); + Assert.Equal(functionNestingCount, engine.Evaluate("x").AsNumber()); + } + + [Fact] + public void ShouldThrowJavascriptExceptionWhenStackGuardExceed() + { + // Can be more than actual dotnet stacktrace count, It does not hit stackoverflow anymore. + int functionNestingCount = FunctionNestingCount * 2; + + var script = GenerateCallTree(functionNestingCount); + + var engine = new Engine(option => option.Constraints.MaxExecutionStackCount = 500); + try + { + engine.Execute(script); + engine.Evaluate("func1(123);"); + } + catch (JavaScriptException jsException) + { + Assert.Equal("Maximum call stack size exceeded", jsException.Message); + } + } + + private string GenerateCallTree(int functionNestingCount) + { var sb = new StringBuilder(); - sb.AppendLine("var x = 10;"); + sb.AppendLine("var x = 1;"); sb.AppendLine(); - for (var i = 1; i <= FunctionNestingCount; ++i) + for (var i = 1; i <= functionNestingCount; ++i) { sb.Append("function func").Append(i).Append("(func").Append(i).AppendLine("Param) {"); sb.Append(" "); - if (i != FunctionNestingCount) + if (i != functionNestingCount) { // just to create a bit more nesting add some constructs - sb.Append("return x++ > 1 ? func").Append(i + 1).Append("(func").Append(i).AppendLine("Param): undefined;"); + sb.Append("return x++ >= 1 ? func").Append(i + 1).Append("(func").Append(i).AppendLine("Param): undefined;"); } else { @@ -43,10 +88,7 @@ public void ShouldAllowReasonableCallStackDepth() sb.AppendLine("}"); sb.AppendLine(); } - - var engine = new Engine(); - engine.Execute(sb.ToString()); - Assert.Equal(123, engine.Evaluate("func1(123);").AsNumber()); + return sb.ToString(); } } diff --git a/Jint.Tests/Runtime/EngineTests.cs b/Jint.Tests/Runtime/EngineTests.cs index 065b7211db..e4ec411d0f 100644 --- a/Jint.Tests/Runtime/EngineTests.cs +++ b/Jint.Tests/Runtime/EngineTests.cs @@ -1883,6 +1883,31 @@ public void DateShouldParseToString() "); } + + [Fact] + public void ShouldThrowErrorWhenMaxExecutionStackCountLimitExceeded() + { + new Engine(options => options.Constraints.MaxExecutionStackCount = 1000) + .SetValue("assert", new Action(Assert.True)) + .Evaluate(@" + var count = 0; + function recurse() { + count++; + recurse(); + return null; // ensure no tail recursion + } + try { + count = 0; + recurse(); + assert(false); + } catch(err) { + assert(count >= 1000); + } + "); + + } + + [Fact] public void LocaleNumberShouldUseLocalCulture() { diff --git a/Jint/Engine.cs b/Jint/Engine.cs index cf45fd0138..0cbad545f1 100644 --- a/Jint/Engine.cs +++ b/Jint/Engine.cs @@ -63,6 +63,7 @@ public sealed partial class Engine : IDisposable internal ConditionalWeakTable? _objectWrapperCache; internal readonly JintCallStack CallStack; + internal readonly StackGuard _stackGuard; // needed in initial engine setup, for example CLR function construction internal Intrinsics _originalIntrinsics = null!; @@ -129,6 +130,7 @@ public Engine(Action options) Options.Apply(this); CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0); + _stackGuard = new StackGuard(this); } private void Reset() diff --git a/Jint/Options.cs b/Jint/Options.cs index 9d5a1a79b6..157cf4247e 100644 --- a/Jint/Options.cs +++ b/Jint/Options.cs @@ -9,6 +9,7 @@ using Jint.Runtime.Debugger; using Jint.Runtime.Descriptors; using Jint.Runtime.Modules; +using Jint.Runtime.CallStack; namespace Jint { @@ -385,6 +386,16 @@ public class ConstraintOptions /// public int MaxRecursionDepth { get; set; } = -1; + /// + /// Maximum recursion stack count, defaults to -1 (as-is dotnet stacktrace). + /// + /// + /// Chrome and V8 based engines (ClearScript) that can handle 13955. + /// When set to a different value except -1, it can reduce slight performance/stack trace readability drawback. (after hitting the engine's own limit), + /// When max stack size to be exceeded, Engine throws an exception . + /// + public int MaxExecutionStackCount { get; set; } = StackGuard.Disabled; + /// /// Maximum time a Regex is allowed to run, defaults to 10 seconds. /// diff --git a/Jint/Runtime/CallStack/StackGuard.cs b/Jint/Runtime/CallStack/StackGuard.cs new file mode 100644 index 0000000000..2ddf5946a7 --- /dev/null +++ b/Jint/Runtime/CallStack/StackGuard.cs @@ -0,0 +1,87 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// https://github.com/dotnet/runtime/blob/a0964f9e3793cb36cc01d66c14a61e89ada5e7da/src/libraries/Microsoft.Extensions.DependencyInjection/src/ServiceLookup/StackGuard.cs + +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Jint.Runtime.CallStack; + +internal sealed class StackGuard +{ + public const int Disabled = -1; + + private readonly Engine _engine; + + public StackGuard(Engine engine) + { + _engine = engine; + } + + public bool TryEnterOnCurrentStack() + { + if (_engine.Options.Constraints.MaxExecutionStackCount == Disabled) + { + return true; + } + +#if NETFRAMEWORK || NETSTANDARD2_0 + try + { + RuntimeHelpers.EnsureSufficientExecutionStack(); + return true; + } + catch (InsufficientExecutionStackException) + { + } +#else + if (RuntimeHelpers.TryEnsureSufficientExecutionStack()) + { + return true; + } +#endif + + if (_engine.CallStack.Count > _engine.Options.Constraints.MaxExecutionStackCount) + { + ExceptionHelper.ThrowRangeError(_engine.Realm, "Maximum call stack size exceeded"); + } + + return false; + } + + public TR RunOnEmptyStack(Func action, T1 arg1) + { +#if NETFRAMEWORK || NETSTANDARD2_0 + return RunOnEmptyStackCore(static s => + { + var t = (Tuple, T1>) s; + return t.Item1(t.Item2); + }, Tuple.Create(action, arg1)); +#else + // Prefer ValueTuple when available to reduce dependencies on Tuple + return RunOnEmptyStackCore(static s => + { + var t = ((Func, T1)) s; + return t.Item1(t.Item2); + }, (action, arg1)); +#endif + + } + + private R RunOnEmptyStackCore(Func action, object state) + { + // Using default scheduler rather than picking up the current scheduler. + Task task = Task.Factory.StartNew((Func) action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); + + // Avoid AsyncWaitHandle lazy allocation of ManualResetEvent in the rare case we finish quickly. + if (!task.IsCompleted) + { + // Task.Wait has the potential of inlining the task's execution on the current thread; avoid this. + ((IAsyncResult) task).AsyncWaitHandle.WaitOne(); + } + + // Using awaiter here to propagate original exception + return task.GetAwaiter().GetResult(); + } +} diff --git a/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs index 6288967224..c1f1e0abfc 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintCallExpression.cs @@ -78,6 +78,11 @@ static bool CanSpread(Node? e) protected override object EvaluateInternal(EvaluationContext context) { + if (!context.Engine._stackGuard.TryEnterOnCurrentStack()) + { + return context.Engine._stackGuard.RunOnEmptyStack(EvaluateInternal, context); + } + if (_calleeExpression._expression.Type == Nodes.Super) { return SuperCall(context); From 43b635679377270e174b067355aeb048f6fe8f57 Mon Sep 17 00:00:00 2001 From: Filip Petersson <47211326+Zmarfan@users.noreply.github.com> Date: Sun, 9 Jul 2023 10:38:23 +0200 Subject: [PATCH 04/24] Readme Module section update (#1587) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 286ff2cdaa..55e8215b80 100644 --- a/README.md +++ b/README.md @@ -379,7 +379,7 @@ By default, the module resolution algorithm will be restricted to the base path Defining modules using JavaScript source code: ```c# -engine.CreateModule("user", "export const name = 'John';") +engine.AddModule("user", "export const name = 'John';"); var ns = engine.ImportModule("user"); @@ -390,13 +390,13 @@ Defining modules using the module builder, which allows you to export CLR classe ```c# // Create the module 'lib' with the class MyClass and the variable version -engine.CreateModule("lib", builder => builder +engine.AddModule("lib", builder => builder .ExportType() .ExportValue("version", 15) ); // Create a user-defined module and do something with 'lib' -engine.CreateModule("custom", @" +engine.AddModule("custom", @" import { MyClass, version } from 'lib'; const x = new MyClass(); export const result as x.doSomething(); From 4057029fe57d0ece28c5db6e4ef8e822af601771 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Thu, 27 Jul 2023 12:06:16 +0300 Subject: [PATCH 05/24] Update test262 test suite and fix issues (#1589) * Array.group and Array.groupToMap are now Object.groupBy and Map.groupBy * add new feature flags to ignore until implementation --- .../Test262Harness.settings.json | 4 +- Jint/JsValueExtensions.cs | 11 +++ Jint/Native/Array/ArrayPrototype.cs | 79 +------------------ Jint/Native/GroupByHelper.cs | 75 ++++++++++++++++++ Jint/Native/Map/MapConstructor.cs | 25 ++++++ Jint/Native/Object/ObjectConstructor.cs | 69 ++++++++++------ Jint/Native/Object/ObjectInstance.cs | 11 +-- NuGet.config | 2 + README.md | 2 +- 9 files changed, 163 insertions(+), 115 deletions(-) create mode 100644 Jint/Native/GroupByHelper.cs diff --git a/Jint.Tests.Test262/Test262Harness.settings.json b/Jint.Tests.Test262/Test262Harness.settings.json index 767943d29b..63d84c6d58 100644 --- a/Jint.Tests.Test262/Test262Harness.settings.json +++ b/Jint.Tests.Test262/Test262Harness.settings.json @@ -1,16 +1,18 @@ { - "SuiteGitSha": "9704d7f22f6342d6c4753ab9a8d62d6725de8c4e", + "SuiteGitSha": "9437cab774ab2f22c5cb971b11b8512eca705721", //"SuiteDirectory": "//mnt/c/work/test262", "TargetPath": "./Generated", "Namespace": "Jint.Tests.Test262", "Parallel": true, "ExcludedFeatures": [ "Array.fromAsync", + "arraybuffer-transfer", "async-iteration", "Atomics", "decorators", "generators", "import-assertions", + "iterator-helpers", "regexp-duplicate-named-groups", "regexp-lookbehind", "regexp-unicode-property-escapes", diff --git a/Jint/JsValueExtensions.cs b/Jint/JsValueExtensions.cs index 76d7abdb51..d84007e989 100644 --- a/Jint/JsValueExtensions.cs +++ b/Jint/JsValueExtensions.cs @@ -582,5 +582,16 @@ internal static BigInteger ToBigInteger(this JsValue value, Engine engine) return default; } } + + internal static ICallable GetCallable(this JsValue source, Realm realm) + { + if (source is ICallable callable) + { + return callable; + } + + ExceptionHelper.ThrowTypeError(realm, "Argument must be callable"); + return null; + } } } diff --git a/Jint/Native/Array/ArrayPrototype.cs b/Jint/Native/Array/ArrayPrototype.cs index 7c0ce6ed90..299223088a 100644 --- a/Jint/Native/Array/ArrayPrototype.cs +++ b/Jint/Native/Array/ArrayPrototype.cs @@ -1,7 +1,6 @@ using System.Linq; using Jint.Collections; using Jint.Native.Iterator; -using Jint.Native.Map; using Jint.Native.Number; using Jint.Native.Object; using Jint.Native.Symbol; @@ -37,7 +36,7 @@ internal ArrayPrototype( protected override void Initialize() { const PropertyFlag PropertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable; - var properties = new PropertyDictionary(40, checkExistingKeys: false) + var properties = new PropertyDictionary(38, checkExistingKeys: false) { ["constructor"] = new PropertyDescriptor(_constructor, PropertyFlag.NonEnumerable), @@ -55,8 +54,6 @@ protected override void Initialize() ["flat"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "flat", Flat, 0, PropertyFlag.Configurable), PropertyFlags), ["flatMap"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "flatMap", FlatMap, 1, PropertyFlag.Configurable), PropertyFlags), ["forEach"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "forEach", ForEach, 1, PropertyFlag.Configurable), PropertyFlags), - ["group"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "group", Group, 1, PropertyFlag.Configurable), PropertyFlags), - ["groupToMap"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "groupToMap", GroupToMap, 1, PropertyFlag.Configurable), PropertyFlags), ["includes"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "includes", Includes, 1, PropertyFlag.Configurable), PropertyFlags), ["indexOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "indexOf", IndexOf, 1, PropertyFlag.Configurable), PropertyFlags), ["join"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "join", Join, 1, PropertyFlag.Configurable), PropertyFlags), @@ -105,10 +102,6 @@ protected override void Initialize() unscopables.FastSetDataProperty("findLastIndex", JsBoolean.True); unscopables.FastSetDataProperty("flat", JsBoolean.True); unscopables.FastSetDataProperty("flatMap", JsBoolean.True); - unscopables.FastSetDataProperty("group", JsBoolean.True); - unscopables.FastSetDataProperty("groupBy", JsBoolean.True); - unscopables.FastSetDataProperty("groupByToMap", JsBoolean.True); - unscopables.FastSetDataProperty("groupToMap", JsBoolean.True); unscopables.FastSetDataProperty("includes", JsBoolean.True); unscopables.FastSetDataProperty("keys", JsBoolean.True); unscopables.FastSetDataProperty("toReversed", JsBoolean.True); @@ -1655,76 +1648,6 @@ public JsValue Pop(JsValue thisObject, JsValue[] arguments) return element; } - /// - /// https://tc39.es/proposal-array-grouping/#sec-array.prototype.group - /// - private JsValue Group(JsValue thisObject, JsValue[] arguments) - { - var grouping = BuildArrayGrouping(thisObject, arguments, mapMode: false); - - var obj = OrdinaryObjectCreate(_engine, null); - foreach (var pair in grouping) - { - obj.FastSetProperty(pair.Key, new PropertyDescriptor(pair.Value, PropertyFlag.ConfigurableEnumerableWritable)); - } - - return obj; - } - - /// - /// https://tc39.es/proposal-array-grouping/#sec-array.prototype.grouptomap - /// - private JsValue GroupToMap(JsValue thisObject, JsValue[] arguments) - { - var grouping = BuildArrayGrouping(thisObject, arguments, mapMode: true); - var map = (MapInstance) Construct(_realm.Intrinsics.Map); - foreach (var pair in grouping) - { - map.MapSet(pair.Key, pair.Value); - } - - return map; - } - - private Dictionary BuildArrayGrouping(JsValue thisObject, JsValue[] arguments, bool mapMode) - { - var o = ArrayOperations.For(_realm, thisObject); - var len = o.GetLongLength(); - var callbackfn = arguments.At(0); - var callable = GetCallable(callbackfn); - var thisArg = arguments.At(1); - - var result = new Dictionary(); - var args = _engine._jsValueArrayPool.RentArray(3); - args[2] = o.Target; - for (uint k = 0; k < len; k++) - { - var kValue = o.Get(k); - args[0] = kValue; - args[1] = k; - - var value = callable.Call(thisArg, args); - JsValue key; - if (mapMode) - { - key = (value as JsNumber)?.IsNegativeZero() == true ? JsNumber.PositiveZero : value; - } - else - { - key = TypeConverter.ToPropertyKey(value); - } - if (!result.TryGetValue(key, out var list)) - { - result[key] = list = new JsArray(_engine); - } - - list.SetIndexValue(list.GetLength(), kValue, updateLength: true); - } - - _engine._jsValueArrayPool.ReturnArray(args); - return result; - } - private object[] CreateBackingArray(ulong length) { ValidateArrayLength(length); diff --git a/Jint/Native/GroupByHelper.cs b/Jint/Native/GroupByHelper.cs new file mode 100644 index 0000000000..252e82132b --- /dev/null +++ b/Jint/Native/GroupByHelper.cs @@ -0,0 +1,75 @@ +using Jint.Native.Array; +using Jint.Native.Iterator; +using Jint.Runtime; + +namespace Jint.Native; + +internal static class GroupByHelper +{ + internal static Dictionary GroupBy( + Engine engine, + Realm realm, + JsValue items, + JsValue callbackfn, + bool mapMode) + { + var callable = callbackfn.GetCallable(realm); + var groups = new Dictionary(); + var iteratorRecord = items.GetIterator(realm); + new GroupByProtocol(engine, groups, iteratorRecord, callable, mapMode).Execute(); + return groups; + } + + private sealed class GroupByProtocol : IteratorProtocol + { + private readonly Engine _engine; + private readonly Dictionary _result; + private readonly ICallable _callable; + private readonly bool _mapMode; + private ulong _k; + private readonly JsValue[] _callArgs = new JsValue[2]; + + public GroupByProtocol( + Engine engine, + Dictionary result, + IteratorInstance iterator, + ICallable callable, + bool mapMode) : base(engine, iterator, 0) + { + _engine = engine; + _result = result; + _callable = callable; + _mapMode = mapMode; + } + + protected override void ProcessItem(JsValue[] args, JsValue currentValue) + { + if (_k >= ArrayOperations.MaxArrayLength) + { + ExceptionHelper.ThrowTypeError(_engine.Realm); + } + + _callArgs[0] = currentValue; + _callArgs[1] = _k; + + var value = _callable.Call(JsValue.Undefined, _callArgs); + JsValue key; + if (_mapMode) + { + key = (value as JsNumber)?.IsNegativeZero() == true ? JsNumber.PositiveZero : value; + } + else + { + key = TypeConverter.ToPropertyKey(value); + } + + if (!_result.TryGetValue(key, out var list)) + { + _result[key] = list = new JsArray(_engine); + } + + list.Push(currentValue); + _k++; + } + } +} diff --git a/Jint/Native/Map/MapConstructor.cs b/Jint/Native/Map/MapConstructor.cs index 648379be6b..bc26e46aef 100644 --- a/Jint/Native/Map/MapConstructor.cs +++ b/Jint/Native/Map/MapConstructor.cs @@ -30,6 +30,13 @@ internal MapConstructor( protected override void Initialize() { + const PropertyFlag PropertyFlags = PropertyFlag.Writable | PropertyFlag.Configurable; + var properties = new PropertyDictionary(1, checkExistingKeys: false) + { + ["groupBy"] = new(new ClrFunctionInstance(Engine, "groupBy", GroupBy, 2, PropertyFlag.Configurable), PropertyFlags), + }; + SetProperties(properties); + var symbols = new SymbolDictionary(1) { [GlobalSymbolRegistry.Species] = new GetSetPropertyDescriptor(get: new ClrFunctionInstance(_engine, "get [Symbol.species]", Species, 0, PropertyFlag.Configurable), set: Undefined, PropertyFlag.Configurable) @@ -67,4 +74,22 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) return map; } + + + /// + /// https://tc39.es/proposal-array-grouping/#sec-map.groupby + /// + private JsValue GroupBy(JsValue thisObject, JsValue[] arguments) + { + var items = arguments.At(0); + var callbackfn = arguments.At(1); + var grouping = GroupByHelper.GroupBy(_engine, _realm, items, callbackfn, mapMode: true); + var map = (MapInstance) Construct(_realm.Intrinsics.Map); + foreach (var pair in grouping) + { + map.MapSet(pair.Key, pair.Value); + } + + return map; + } } diff --git a/Jint/Native/Object/ObjectConstructor.cs b/Jint/Native/Object/ObjectConstructor.cs index 485bad39cc..0b9a17513c 100644 --- a/Jint/Native/Object/ObjectConstructor.cs +++ b/Jint/Native/Object/ObjectConstructor.cs @@ -26,32 +26,33 @@ protected override void Initialize() { _prototype = _realm.Intrinsics.Function.PrototypeObject; - const PropertyFlag propertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable; - const PropertyFlag lengthFlags = PropertyFlag.Configurable; - var properties = new PropertyDictionary(15, checkExistingKeys: false) + const PropertyFlag PropertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable; + const PropertyFlag LengthFlags = PropertyFlag.Configurable; + var properties = new PropertyDictionary(16, checkExistingKeys: false) { - ["assign"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "assign", Assign, 2, lengthFlags), propertyFlags), - ["entries"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "entries", Entries, 1, lengthFlags), propertyFlags), - ["fromEntries"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "fromEntries", FromEntries, 1, lengthFlags), propertyFlags), - ["getPrototypeOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getPrototypeOf", GetPrototypeOf, 1), propertyFlags), - ["getOwnPropertyDescriptor"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyDescriptor", GetOwnPropertyDescriptor, 2, lengthFlags), propertyFlags), - ["getOwnPropertyDescriptors"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyDescriptors", GetOwnPropertyDescriptors, 1, lengthFlags), propertyFlags), - ["getOwnPropertyNames"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyNames", GetOwnPropertyNames, 1), propertyFlags), - ["getOwnPropertySymbols"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertySymbols", GetOwnPropertySymbols, 1, lengthFlags), propertyFlags), - ["create"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "create", Create, 2), propertyFlags), - ["defineProperty"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "defineProperty", DefineProperty, 3), propertyFlags), - ["defineProperties"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "defineProperties", DefineProperties, 2), propertyFlags), - ["is"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "is", Is, 2, lengthFlags), propertyFlags), - ["seal"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "seal", Seal, 1, lengthFlags), propertyFlags), - ["freeze"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "freeze", Freeze, 1), propertyFlags), - ["preventExtensions"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "preventExtensions", PreventExtensions, 1), propertyFlags), - ["isSealed"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isSealed", IsSealed, 1), propertyFlags), - ["isFrozen"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isFrozen", IsFrozen, 1), propertyFlags), - ["isExtensible"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isExtensible", IsExtensible, 1), propertyFlags), - ["keys"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "keys", Keys, 1, lengthFlags), propertyFlags), - ["values"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "values", Values, 1, lengthFlags), propertyFlags), - ["setPrototypeOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setPrototypeOf", SetPrototypeOf, 2, lengthFlags), propertyFlags), - ["hasOwn"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "hasOwn", HasOwn, 2, lengthFlags), propertyFlags), + ["assign"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "assign", Assign, 2, LengthFlags), PropertyFlags), + ["entries"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "entries", Entries, 1, LengthFlags), PropertyFlags), + ["fromEntries"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "fromEntries", FromEntries, 1, LengthFlags), PropertyFlags), + ["getPrototypeOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getPrototypeOf", GetPrototypeOf, 1), PropertyFlags), + ["getOwnPropertyDescriptor"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyDescriptor", GetOwnPropertyDescriptor, 2, LengthFlags), PropertyFlags), + ["getOwnPropertyDescriptors"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyDescriptors", GetOwnPropertyDescriptors, 1, LengthFlags), PropertyFlags), + ["getOwnPropertyNames"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertyNames", GetOwnPropertyNames, 1), PropertyFlags), + ["getOwnPropertySymbols"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getOwnPropertySymbols", GetOwnPropertySymbols, 1, LengthFlags), PropertyFlags), + ["groupBy"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "groupBy", GroupBy, 2, PropertyFlag.Configurable), PropertyFlags), + ["create"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "create", Create, 2), PropertyFlags), + ["defineProperty"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "defineProperty", DefineProperty, 3), PropertyFlags), + ["defineProperties"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "defineProperties", DefineProperties, 2), PropertyFlags), + ["is"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "is", Is, 2, LengthFlags), PropertyFlags), + ["seal"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "seal", Seal, 1, LengthFlags), PropertyFlags), + ["freeze"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "freeze", Freeze, 1), PropertyFlags), + ["preventExtensions"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "preventExtensions", PreventExtensions, 1), PropertyFlags), + ["isSealed"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isSealed", IsSealed, 1), PropertyFlags), + ["isFrozen"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isFrozen", IsFrozen, 1), PropertyFlags), + ["isExtensible"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "isExtensible", IsExtensible, 1), PropertyFlags), + ["keys"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "keys", Keys, 1, LengthFlags), PropertyFlags), + ["values"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "values", Values, 1, LengthFlags), PropertyFlags), + ["setPrototypeOf"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setPrototypeOf", SetPrototypeOf, 2, LengthFlags), PropertyFlags), + ["hasOwn"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "hasOwn", HasOwn, 2, LengthFlags), PropertyFlags), }; SetProperties(properties); } @@ -525,6 +526,24 @@ private JsValue Values(JsValue thisObject, JsValue[] arguments) return o.EnumerableOwnPropertyNames(EnumerableOwnPropertyNamesKind.Value); } + /// + /// https://tc39.es/proposal-array-grouping/#sec-object.groupby + /// + private JsValue GroupBy(JsValue thisObject, JsValue[] arguments) + { + var items = arguments.At(0); + var callbackfn = arguments.At(1); + var grouping = GroupByHelper.GroupBy(_engine, _realm, items, callbackfn, mapMode: false); + + var obj = OrdinaryObjectCreate(_engine, null); + foreach (var pair in grouping) + { + obj.FastSetProperty(pair.Key, new PropertyDescriptor(pair.Value, PropertyFlag.ConfigurableEnumerableWritable)); + } + + return obj; + } + private sealed class CreateDataPropertyOnObject : ICallable { internal static readonly CreateDataPropertyOnObject Instance = new(); diff --git a/Jint/Native/Object/ObjectInstance.cs b/Jint/Native/Object/ObjectInstance.cs index 8db1094998..84d25dec63 100644 --- a/Jint/Native/Object/ObjectInstance.cs +++ b/Jint/Native/Object/ObjectInstance.cs @@ -1173,16 +1173,7 @@ bool TryGetValue(ulong idx, out JsValue jsValue) return false; } - internal ICallable GetCallable(JsValue source) - { - if (source is ICallable callable) - { - return callable; - } - - ExceptionHelper.ThrowTypeError(_engine.Realm, "Argument must be callable"); - return null; - } + internal ICallable GetCallable(JsValue source) => source.GetCallable(_engine.Realm); internal bool IsConcatSpreadable { diff --git a/NuGet.config b/NuGet.config index 32b42fc44c..c9af0eb814 100644 --- a/NuGet.config +++ b/NuGet.config @@ -3,7 +3,9 @@ + diff --git a/README.md b/README.md index 55e8215b80..edaaf5a8df 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ Following features are supported in version 3.x. #### ECMAScript Stage 3 (no version yet) -- ✔ Array.group and Array.groupToMap +- ✔ Array Grouping - `Object.groupBy` and `Map.groupBy` - ✔ ShadowRealm #### Other From 2ce134903933977e4810ea43932240530aa8b47c Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 28 Jul 2023 21:13:22 +0300 Subject: [PATCH 06/24] Rename ArrayBufferInstance to JsArrayBuffer and make it public (#1591) --- Jint.Tests.Test262/Test262Test.cs | 2 +- Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs | 4 ++-- Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs | 8 ++++---- .../{ArrayBufferInstance.cs => JsArrayBuffer.cs} | 6 +++--- Jint/Native/DataView/DataViewConstructor.cs | 2 +- Jint/Native/DataView/DataViewInstance.cs | 2 +- Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs | 8 ++++---- Jint/Native/TypedArray/TypedArrayConstructor.cs | 6 +++--- Jint/Native/TypedArray/TypedArrayInstance.cs | 4 ++-- 9 files changed, 21 insertions(+), 21 deletions(-) rename Jint/Native/ArrayBuffer/{ArrayBufferInstance.cs => JsArrayBuffer.cs} (98%) diff --git a/Jint.Tests.Test262/Test262Test.cs b/Jint.Tests.Test262/Test262Test.cs index 2d5f8f0dac..6bbac100e4 100644 --- a/Jint.Tests.Test262/Test262Test.cs +++ b/Jint.Tests.Test262/Test262Test.cs @@ -56,7 +56,7 @@ private Engine BuildTestExecutor(Test262File file) o.FastSetProperty("detachArrayBuffer", new PropertyDescriptor(new ClrFunctionInstance(engine, "detachArrayBuffer", (_, args) => { - var buffer = (ArrayBufferInstance) args.At(0); + var buffer = (JsArrayBuffer) args.At(0); buffer.DetachArrayBuffer(); return JsValue.Undefined; }), true, true, true)); diff --git a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs index abd4f9c2ef..03a549d1a4 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs @@ -76,12 +76,12 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) return AllocateArrayBuffer(newTarget, byteLength); } - internal ArrayBufferInstance AllocateArrayBuffer(JsValue constructor, ulong byteLength) + internal JsArrayBuffer AllocateArrayBuffer(JsValue constructor, ulong byteLength) { var obj = OrdinaryCreateFromConstructor( constructor, static intrinsics => intrinsics.ArrayBuffer.PrototypeObject, - static (engine, realm, state) => new ArrayBufferInstance(engine, (ulong) state!._value), + static (engine, realm, state) => new JsArrayBuffer(engine, (ulong) state!._value), JsNumber.Create(byteLength)); return obj; diff --git a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs index 0f118a0857..dcf9d8414c 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs @@ -44,7 +44,7 @@ protected override void Initialize() private JsValue Detached(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as ArrayBufferInstance; + var o = thisObj as JsArrayBuffer; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.detached called on incompatible receiver " + thisObj); @@ -63,7 +63,7 @@ private JsValue Detached(JsValue thisObj, JsValue[] arguments) /// private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as ArrayBufferInstance; + var o = thisObj as JsArrayBuffer; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.byteLength called on incompatible receiver " + thisObj); @@ -87,7 +87,7 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// private JsValue Slice(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as ArrayBufferInstance; + var o = thisObj as JsArrayBuffer; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.slice called on incompatible receiver " + thisObj); @@ -131,7 +131,7 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) var newLen = System.Math.Max(final - first, 0); var ctor = SpeciesConstructor(o, _realm.Intrinsics.ArrayBuffer); - var bufferInstance = Construct(ctor, new JsValue[] { JsNumber.Create(newLen) }) as ArrayBufferInstance; + var bufferInstance = Construct(ctor, new JsValue[] { JsNumber.Create(newLen) }) as JsArrayBuffer; if (bufferInstance is null) { diff --git a/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs b/Jint/Native/ArrayBuffer/JsArrayBuffer.cs similarity index 98% rename from Jint/Native/ArrayBuffer/ArrayBufferInstance.cs rename to Jint/Native/ArrayBuffer/JsArrayBuffer.cs index 2c17538fea..c745a66ce6 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferInstance.cs +++ b/Jint/Native/ArrayBuffer/JsArrayBuffer.cs @@ -7,7 +7,7 @@ namespace Jint.Native.ArrayBuffer /// /// https://tc39.es/ecma262/#sec-arraybuffer-objects /// - internal sealed class ArrayBufferInstance : ObjectInstance + public sealed class JsArrayBuffer : ObjectInstance { // so that we don't need to allocate while or reading setting values private readonly byte[] _workBuffer = new byte[8]; @@ -15,7 +15,7 @@ internal sealed class ArrayBufferInstance : ObjectInstance private byte[]? _arrayBufferData; private readonly JsValue _arrayBufferDetachKey = Undefined; - internal ArrayBufferInstance( + internal JsArrayBuffer( Engine engine, ulong byteLength) : base(engine) { @@ -57,7 +57,7 @@ internal void DetachArrayBuffer(JsValue? key = null) /// /// https://tc39.es/ecma262/#sec-clonearraybuffer /// - internal ArrayBufferInstance CloneArrayBuffer( + internal JsArrayBuffer CloneArrayBuffer( ArrayBufferConstructor constructor, int srcByteOffset, uint srcLength) diff --git a/Jint/Native/DataView/DataViewConstructor.cs b/Jint/Native/DataView/DataViewConstructor.cs index 4f940a7159..2d14e17e10 100644 --- a/Jint/Native/DataView/DataViewConstructor.cs +++ b/Jint/Native/DataView/DataViewConstructor.cs @@ -35,7 +35,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) ExceptionHelper.ThrowTypeError(_realm); } - var buffer = arguments.At(0) as ArrayBufferInstance; + var buffer = arguments.At(0) as JsArrayBuffer; var byteOffset = arguments.At(1); var byteLength = arguments.At(2); diff --git a/Jint/Native/DataView/DataViewInstance.cs b/Jint/Native/DataView/DataViewInstance.cs index 17f06d34f2..eff16b1ff4 100644 --- a/Jint/Native/DataView/DataViewInstance.cs +++ b/Jint/Native/DataView/DataViewInstance.cs @@ -8,7 +8,7 @@ namespace Jint.Native.DataView; /// internal sealed class DataViewInstance : ObjectInstance { - internal ArrayBufferInstance? _viewedArrayBuffer; + internal JsArrayBuffer? _viewedArrayBuffer; internal uint _byteLength; internal uint _byteOffset; diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs index 54c361eaac..89c8f5fcfc 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs @@ -1404,7 +1404,7 @@ private TypedArrayInstance TypedArrayCreateSameType(TypedArrayInstance exemplar, return compareFn; } - private static JsValue[] SortArray(ArrayBufferInstance buffer, ICallable? compareFn, TypedArrayInstance obj) + private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, TypedArrayInstance obj) { var comparer = TypedArrayComparer.WithFunction(buffer, compareFn); var operations = ArrayOperations.For(obj); @@ -1420,16 +1420,16 @@ private static JsValue[] SortArray(ArrayBufferInstance buffer, ICallable? compar private sealed class TypedArrayComparer : IComparer { - public static TypedArrayComparer WithFunction(ArrayBufferInstance buffer, ICallable? compare) + public static TypedArrayComparer WithFunction(JsArrayBuffer buffer, ICallable? compare) { return new TypedArrayComparer(buffer, compare); } - private readonly ArrayBufferInstance _buffer; + private readonly JsArrayBuffer _buffer; private readonly ICallable? _compare; private readonly JsValue[] _comparableArray = new JsValue[2]; - private TypedArrayComparer(ArrayBufferInstance buffer, ICallable? compare) + private TypedArrayComparer(JsArrayBuffer buffer, ICallable? compare) { _buffer = buffer; _compare = compare; diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.cs b/Jint/Native/TypedArray/TypedArrayConstructor.cs index d71943b0da..b25f7de3b9 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.cs @@ -78,7 +78,7 @@ public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) { InitializeTypedArrayFromTypedArray(o, typedArrayInstance); } - else if (firstArgument is ArrayBufferInstance arrayBuffer) + else if (firstArgument is JsArrayBuffer arrayBuffer) { var byteOffset = numberOfArgs > 1 ? args[1] : Undefined; var length = numberOfArgs > 2 ? args[2] : Undefined; @@ -137,7 +137,7 @@ private void InitializeTypedArrayFromTypedArray(TypedArrayInstance o, TypedArray var byteLength = elementSize * elementLength; var arrayBuffer = _realm.Intrinsics.ArrayBuffer; - ArrayBufferInstance data; + JsArrayBuffer data; if (elementType == srcType) { data = srcData.CloneArrayBuffer(arrayBuffer, srcByteOffset, byteLength); @@ -175,7 +175,7 @@ private void InitializeTypedArrayFromTypedArray(TypedArrayInstance o, TypedArray /// private void InitializeTypedArrayFromArrayBuffer( TypedArrayInstance o, - ArrayBufferInstance buffer, + JsArrayBuffer buffer, JsValue byteOffset, JsValue length) { diff --git a/Jint/Native/TypedArray/TypedArrayInstance.cs b/Jint/Native/TypedArray/TypedArrayInstance.cs index 153e4783ca..0295a96953 100644 --- a/Jint/Native/TypedArray/TypedArrayInstance.cs +++ b/Jint/Native/TypedArray/TypedArrayInstance.cs @@ -12,7 +12,7 @@ public sealed class TypedArrayInstance : ObjectInstance { internal readonly TypedArrayContentType _contentType; internal readonly TypedArrayElementType _arrayElementType; - internal ArrayBufferInstance _viewedArrayBuffer; + internal JsArrayBuffer _viewedArrayBuffer; internal uint _byteLength; internal int _byteOffset; private readonly Intrinsics _intrinsics; @@ -25,7 +25,7 @@ internal TypedArrayInstance( uint length) : base(engine) { _intrinsics = intrinsics; - _viewedArrayBuffer = new ArrayBufferInstance(engine, 0); + _viewedArrayBuffer = new JsArrayBuffer(engine, 0); _arrayElementType = type; _contentType = type != TypedArrayElementType.BigInt64 && type != TypedArrayElementType.BigUint64 From b48e7b7180513fb91a22ba501c3e61cc4458e060 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 28 Jul 2023 21:27:26 +0300 Subject: [PATCH 07/24] Rename TypedArrayInstance to JsTypedArray (#1592) --- Jint/JsValueExtensions.cs | 36 +++++++-------- Jint/Native/Array/ArrayIteratorPrototype.cs | 4 +- Jint/Native/Array/ArrayOperations.cs | 6 +-- .../ArrayBuffer/ArrayBufferConstructor.cs | 2 +- .../IntrinsicTypedArrayConstructor.cs | 4 +- .../IntrinsicTypedArrayPrototype.cs | 24 +++++----- ...{TypedArrayInstance.cs => JsTypedArray.cs} | 4 +- Jint/Native/TypedArray/TypeArrayHelper.cs | 4 +- .../TypedArray/TypedArrayConstructor.Types.cs | 44 +++++++++---------- .../TypedArray/TypedArrayConstructor.cs | 20 ++++----- 10 files changed, 74 insertions(+), 74 deletions(-) rename Jint/Native/TypedArray/{TypedArrayInstance.cs => JsTypedArray.cs} (99%) diff --git a/Jint/JsValueExtensions.cs b/Jint/JsValueExtensions.cs index d84007e989..0d8dc0074e 100644 --- a/Jint/JsValueExtensions.cs +++ b/Jint/JsValueExtensions.cs @@ -242,7 +242,7 @@ public static string AsString(this JsValue value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUint8Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Uint8 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -253,13 +253,13 @@ public static byte[] AsUint8Array(this JsValue value) ThrowWrongTypeException(value, "Uint8Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUint8ClampedArray(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Uint8C }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint8C }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -270,13 +270,13 @@ public static byte[] AsUint8ClampedArray(this JsValue value) ThrowWrongTypeException(value, "Uint8ClampedArray"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInt8Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Int8 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int8 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -287,13 +287,13 @@ public static sbyte[] AsInt8Array(this JsValue value) ThrowWrongTypeException(value, "Int8Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInt16Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Int16 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int16 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -304,13 +304,13 @@ public static short[] AsInt16Array(this JsValue value) ThrowWrongTypeException(value, "Int16Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUint16Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Uint16 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint16 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -321,13 +321,13 @@ public static ushort[] AsUint16Array(this JsValue value) ThrowWrongTypeException(value, "Uint16Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsInt32Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Int32 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Int32 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -338,13 +338,13 @@ public static int[] AsInt32Array(this JsValue value) ThrowWrongTypeException(value, "Int32Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsUint32Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.Uint32 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.Uint32 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -355,13 +355,13 @@ public static uint[] AsUint32Array(this JsValue value) ThrowWrongTypeException(value, "Uint32Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBigInt64Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.BigInt64 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigInt64 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -372,13 +372,13 @@ public static long[] AsBigInt64Array(this JsValue value) ThrowWrongTypeException(value, "BigInt64Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsBigUint64Array(this JsValue value) { - return value is TypedArrayInstance { _arrayElementType: TypedArrayElementType.BigUint64 }; + return value is JsTypedArray { _arrayElementType: TypedArrayElementType.BigUint64 }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] @@ -389,7 +389,7 @@ public static ulong[] AsBigUint64Array(this JsValue value) ThrowWrongTypeException(value, "BigUint64Array"); } - return ((TypedArrayInstance) value).ToNativeArray(); + return ((JsTypedArray) value).ToNativeArray(); } [Pure] diff --git a/Jint/Native/Array/ArrayIteratorPrototype.cs b/Jint/Native/Array/ArrayIteratorPrototype.cs index 30127c90fc..5744f9930b 100644 --- a/Jint/Native/Array/ArrayIteratorPrototype.cs +++ b/Jint/Native/Array/ArrayIteratorPrototype.cs @@ -86,7 +86,7 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) private sealed class ArrayLikeIterator : IteratorInstance { private readonly ArrayIteratorType _kind; - private readonly TypedArrayInstance? _typedArray; + private readonly JsTypedArray? _typedArray; private readonly ArrayOperations? _operations; private uint _position; private bool _closed; @@ -94,7 +94,7 @@ private sealed class ArrayLikeIterator : IteratorInstance public ArrayLikeIterator(Engine engine, ObjectInstance objectInstance, ArrayIteratorType kind) : base(engine) { _kind = kind; - _typedArray = objectInstance as TypedArrayInstance; + _typedArray = objectInstance as JsTypedArray; if (_typedArray is null) { _operations = ArrayOperations.For(objectInstance); diff --git a/Jint/Native/Array/ArrayOperations.cs b/Jint/Native/Array/ArrayOperations.cs index 1503e4bcd9..19493e32f9 100644 --- a/Jint/Native/Array/ArrayOperations.cs +++ b/Jint/Native/Array/ArrayOperations.cs @@ -19,7 +19,7 @@ public static ArrayOperations For(ObjectInstance instance) return new ArrayInstanceOperations(arrayInstance); } - if (instance is TypedArrayInstance typedArrayInstance) + if (instance is JsTypedArray typedArrayInstance) { return new TypedArrayInstanceOperations(typedArrayInstance); } @@ -277,9 +277,9 @@ public override void Set(ulong index, JsValue value, bool updateLength = false, private sealed class TypedArrayInstanceOperations : ArrayOperations { - private readonly TypedArrayInstance _target; + private readonly JsTypedArray _target; - public TypedArrayInstanceOperations(TypedArrayInstance target) + public TypedArrayInstanceOperations(JsTypedArray target) { _target = target; } diff --git a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs index 03a549d1a4..f141600baa 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs @@ -54,7 +54,7 @@ protected override void Initialize() private static JsValue IsView(JsValue thisObject, JsValue[] arguments) { var arg = arguments.At(0); - return arg is DataViewInstance or TypedArrayInstance; + return arg is DataViewInstance or JsTypedArray; } /// diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs index 1e6fc656c4..87d9163a92 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs @@ -147,7 +147,7 @@ private JsValue Of(JsValue thisObj, JsValue[] items) /// /// https://tc39.es/ecma262/#typedarray-species-create /// - internal TypedArrayInstance TypedArraySpeciesCreate(TypedArrayInstance exemplar, JsValue[] argumentList) + internal JsTypedArray TypedArraySpeciesCreate(JsTypedArray exemplar, JsValue[] argumentList) { var defaultConstructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics)!; var constructor = SpeciesConstructor(exemplar, defaultConstructor); @@ -163,7 +163,7 @@ internal TypedArrayInstance TypedArraySpeciesCreate(TypedArrayInstance exemplar, /// /// https://tc39.es/ecma262/#typedarray-create /// - internal static TypedArrayInstance TypedArrayCreate(Realm realm, IConstructor constructor, JsValue[] argumentList) + internal static JsTypedArray TypedArrayCreate(Realm realm, IConstructor constructor, JsValue[] argumentList) { var newTypedArray = Construct(constructor, argumentList).ValidateTypedArray(realm); if (argumentList.Length == 1 && argumentList[0] is JsNumber number) diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs index 89c8f5fcfc..51e37dfd45 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs @@ -89,7 +89,7 @@ protected override void Initialize() /// private JsValue Buffer(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as TypedArrayInstance; + var o = thisObj as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -103,7 +103,7 @@ private JsValue Buffer(JsValue thisObj, JsValue[] arguments) /// private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as TypedArrayInstance; + var o = thisObj as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -122,7 +122,7 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as TypedArrayInstance; + var o = thisObj as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -141,7 +141,7 @@ private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) /// private JsValue GetLength(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as TypedArrayInstance; + var o = thisObj as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -846,7 +846,7 @@ private ObjectInstance Reverse(JsValue thisObj, JsValue[] arguments) /// private JsValue Set(JsValue thisObj, JsValue[] arguments) { - var target = thisObj as TypedArrayInstance; + var target = thisObj as JsTypedArray; if (target is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -861,7 +861,7 @@ private JsValue Set(JsValue thisObj, JsValue[] arguments) ExceptionHelper.ThrowRangeError(_realm, "Invalid offset"); } - if (source is TypedArrayInstance typedArrayInstance) + if (source is JsTypedArray typedArrayInstance) { SetTypedArrayFromTypedArray(target, targetOffset, typedArrayInstance); } @@ -876,7 +876,7 @@ private JsValue Set(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-settypedarrayfromtypedarray /// - private void SetTypedArrayFromTypedArray(TypedArrayInstance target, double targetOffset, TypedArrayInstance source) + private void SetTypedArrayFromTypedArray(JsTypedArray target, double targetOffset, JsTypedArray source) { var targetBuffer = target._viewedArrayBuffer; targetBuffer.AssertNotDetached(); @@ -963,7 +963,7 @@ private void SetTypedArrayFromTypedArray(TypedArrayInstance target, double targe /// /// https://tc39.es/ecma262/#sec-settypedarrayfromarraylike /// - private void SetTypedArrayFromArrayLike(TypedArrayInstance target, int targetOffset, JsValue source) + private void SetTypedArrayFromArrayLike(JsTypedArray target, int targetOffset, JsValue source) { var targetBuffer = target._viewedArrayBuffer; targetBuffer.AssertNotDetached(); @@ -1170,7 +1170,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) /// private JsValue Subarray(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as TypedArrayInstance; + var o = thisObj as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -1299,7 +1299,7 @@ private JsValue Values(JsValue thisObj, JsValue[] arguments) /// private static JsValue ToStringTag(JsValue thisObj, JsValue[] arguments) { - if (thisObj is not TypedArrayInstance o) + if (thisObj is not JsTypedArray o) { return Undefined; } @@ -1381,7 +1381,7 @@ private ObjectInstance With(JsValue thisObj, JsValue[] arguments) return a; } - private TypedArrayInstance TypedArrayCreateSameType(TypedArrayInstance exemplar, JsValue[] argumentList) + private JsTypedArray TypedArrayCreateSameType(JsTypedArray exemplar, JsValue[] argumentList) { var constructor = exemplar._arrayElementType.GetConstructor(_realm.Intrinsics); var result = IntrinsicTypedArrayConstructor.TypedArrayCreate(_realm, constructor, argumentList); @@ -1404,7 +1404,7 @@ private TypedArrayInstance TypedArrayCreateSameType(TypedArrayInstance exemplar, return compareFn; } - private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, TypedArrayInstance obj) + private static JsValue[] SortArray(JsArrayBuffer buffer, ICallable? compareFn, JsTypedArray obj) { var comparer = TypedArrayComparer.WithFunction(buffer, compareFn); var operations = ArrayOperations.For(obj); diff --git a/Jint/Native/TypedArray/TypedArrayInstance.cs b/Jint/Native/TypedArray/JsTypedArray.cs similarity index 99% rename from Jint/Native/TypedArray/TypedArrayInstance.cs rename to Jint/Native/TypedArray/JsTypedArray.cs index 0295a96953..3991cc84d7 100644 --- a/Jint/Native/TypedArray/TypedArrayInstance.cs +++ b/Jint/Native/TypedArray/JsTypedArray.cs @@ -8,7 +8,7 @@ namespace Jint.Native.TypedArray { - public sealed class TypedArrayInstance : ObjectInstance + public sealed class JsTypedArray : ObjectInstance { internal readonly TypedArrayContentType _contentType; internal readonly TypedArrayElementType _arrayElementType; @@ -18,7 +18,7 @@ public sealed class TypedArrayInstance : ObjectInstance private readonly Intrinsics _intrinsics; internal uint _arrayLength; - internal TypedArrayInstance( + internal JsTypedArray( Engine engine, Intrinsics intrinsics, TypedArrayElementType type, diff --git a/Jint/Native/TypedArray/TypeArrayHelper.cs b/Jint/Native/TypedArray/TypeArrayHelper.cs index c9cf98dc4a..c9f49b1ba5 100644 --- a/Jint/Native/TypedArray/TypeArrayHelper.cs +++ b/Jint/Native/TypedArray/TypeArrayHelper.cs @@ -4,9 +4,9 @@ namespace Jint.Native.TypedArray; internal static class TypeArrayHelper { - internal static TypedArrayInstance ValidateTypedArray(this JsValue o, Realm realm) + internal static JsTypedArray ValidateTypedArray(this JsValue o, Realm realm) { - var typedArrayInstance = o as TypedArrayInstance; + var typedArrayInstance = o as JsTypedArray; if (typedArrayInstance is null) { ExceptionHelper.ThrowTypeError(realm); diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs b/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs index c3d00616a8..b565dab7d0 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.Types.cs @@ -12,9 +12,9 @@ internal Int8ArrayConstructor( { } - public TypedArrayInstance Construct(sbyte[] values) + public JsTypedArray Construct(sbyte[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -30,9 +30,9 @@ internal Uint8ArrayConstructor( { } - public TypedArrayInstance Construct(byte[] values) + public JsTypedArray Construct(byte[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -48,9 +48,9 @@ internal Uint8ClampedArrayConstructor( { } - public TypedArrayInstance Construct(byte[] values) + public JsTypedArray Construct(byte[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -66,9 +66,9 @@ internal Int16ArrayConstructor( { } - public TypedArrayInstance Construct(short[] values) + public JsTypedArray Construct(short[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -84,9 +84,9 @@ internal Uint16ArrayConstructor( { } - public TypedArrayInstance Construct(ushort[] values) + public JsTypedArray Construct(ushort[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -102,9 +102,9 @@ internal Int32ArrayConstructor( { } - public TypedArrayInstance Construct(int[] values) + public JsTypedArray Construct(int[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -120,9 +120,9 @@ internal Uint32ArrayConstructor( { } - public TypedArrayInstance Construct(uint[] values) + public JsTypedArray Construct(uint[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -138,9 +138,9 @@ internal Float32ArrayConstructor( { } - public TypedArrayInstance Construct(float[] values) + public JsTypedArray Construct(float[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -156,9 +156,9 @@ internal Float64ArrayConstructor( { } - public TypedArrayInstance Construct(double[] values) + public JsTypedArray Construct(double[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -174,9 +174,9 @@ internal BigInt64ArrayConstructor( { } - public TypedArrayInstance Construct(long[] values) + public JsTypedArray Construct(long[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } @@ -192,9 +192,9 @@ internal BigUint64ArrayConstructor( { } - public TypedArrayInstance Construct(ulong[] values) + public JsTypedArray Construct(ulong[] values) { - var array = (TypedArrayInstance) base.Construct(new JsValue[] { values.Length }, this); + var array = (JsTypedArray) base.Construct(new JsValue[] { values.Length }, this); FillTypedArrayInstance(array, values); return array; } diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.cs b/Jint/Native/TypedArray/TypedArrayConstructor.cs index b25f7de3b9..7887c49350 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.cs @@ -74,7 +74,7 @@ public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) if (firstArgument.IsObject()) { var o = AllocateTypedArray(newTarget, proto); - if (firstArgument is TypedArrayInstance typedArrayInstance) + if (firstArgument is JsTypedArray typedArrayInstance) { InitializeTypedArrayFromTypedArray(o, typedArrayInstance); } @@ -123,7 +123,7 @@ internal static List IterableToList(Realm realm, JsValue items, ICallab /// /// https://tc39.es/ecma262/#sec-initializetypedarrayfromtypedarray /// - private void InitializeTypedArrayFromTypedArray(TypedArrayInstance o, TypedArrayInstance srcArray) + private void InitializeTypedArrayFromTypedArray(JsTypedArray o, JsTypedArray srcArray) { var srcData = srcArray._viewedArrayBuffer; srcData.AssertNotDetached(); @@ -174,7 +174,7 @@ private void InitializeTypedArrayFromTypedArray(TypedArrayInstance o, TypedArray /// https://tc39.es/ecma262/#sec-initializetypedarrayfromarraybuffer /// private void InitializeTypedArrayFromArrayBuffer( - TypedArrayInstance o, + JsTypedArray o, JsArrayBuffer buffer, JsValue byteOffset, JsValue length) @@ -224,7 +224,7 @@ private void InitializeTypedArrayFromArrayBuffer( o._byteOffset = offset; } - private static void InitializeTypedArrayFromList(TypedArrayInstance o, List values) + private static void InitializeTypedArrayFromList(JsTypedArray o, List values) { var len = values.Count; o.AllocateTypedArrayBuffer((uint) len); @@ -237,7 +237,7 @@ private static void InitializeTypedArrayFromList(TypedArrayInstance o, List /// https://tc39.es/ecma262/#sec-initializetypedarrayfromarraylike /// - private static void InitializeTypedArrayFromArrayLike(TypedArrayInstance o, ObjectInstance arrayLike) + private static void InitializeTypedArrayFromArrayLike(JsTypedArray o, ObjectInstance arrayLike) { var operations = ArrayOperations.For(arrayLike); var len = operations.GetLongLength(); @@ -251,11 +251,11 @@ private static void InitializeTypedArrayFromArrayLike(TypedArrayInstance o, Obje /// /// https://tc39.es/ecma262/#sec-allocatetypedarray /// - private TypedArrayInstance AllocateTypedArray(JsValue newTarget, Func defaultProto, uint length = 0) + private JsTypedArray AllocateTypedArray(JsValue newTarget, Func defaultProto, uint length = 0) { var proto = GetPrototypeFromConstructor(newTarget, defaultProto); var realm = GetFunctionRealm(newTarget); - var obj = new TypedArrayInstance(_engine, realm.Intrinsics, _arrayElementType, length) + var obj = new JsTypedArray(_engine, realm.Intrinsics, _arrayElementType, length) { _prototype = proto }; @@ -267,7 +267,7 @@ private TypedArrayInstance AllocateTypedArray(JsValue newTarget, Func(TypedArrayInstance target, T[] values) + internal static void FillTypedArrayInstance(JsTypedArray target, T[] values) { for (var i = 0; i < values.Length; ++i) { @@ -275,7 +275,7 @@ internal static void FillTypedArrayInstance(TypedArrayInstance target, T[] va } } - internal static void FillTypedArrayInstance(TypedArrayInstance target, ulong[] values) + internal static void FillTypedArrayInstance(JsTypedArray target, ulong[] values) { for (var i = 0; i < values.Length; ++i) { @@ -283,7 +283,7 @@ internal static void FillTypedArrayInstance(TypedArrayInstance target, ulong[] v } } - internal static void FillTypedArrayInstance(TypedArrayInstance target, long[] values) + internal static void FillTypedArrayInstance(JsTypedArray target, long[] values) { for (var i = 0; i < values.Length; ++i) { From 0163e1a5b788e751dbe425d3cba7bc80540ed1a8 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 28 Jul 2023 21:46:58 +0300 Subject: [PATCH 08/24] Rename DataViewInstance to JsDataView (#1593) --- Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs | 2 +- Jint/Native/DataView/DataViewConstructor.cs | 4 ++-- Jint/Native/DataView/DataViewPrototype.cs | 10 +++++----- .../DataView/{DataViewInstance.cs => JsDataView.cs} | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) rename Jint/Native/DataView/{DataViewInstance.cs => JsDataView.cs} (72%) diff --git a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs index f141600baa..e2c49877f1 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferConstructor.cs @@ -54,7 +54,7 @@ protected override void Initialize() private static JsValue IsView(JsValue thisObject, JsValue[] arguments) { var arg = arguments.At(0); - return arg is DataViewInstance or JsTypedArray; + return arg is JsDataView or JsTypedArray; } /// diff --git a/Jint/Native/DataView/DataViewConstructor.cs b/Jint/Native/DataView/DataViewConstructor.cs index 2d14e17e10..5c2863b1df 100644 --- a/Jint/Native/DataView/DataViewConstructor.cs +++ b/Jint/Native/DataView/DataViewConstructor.cs @@ -26,7 +26,7 @@ internal DataViewConstructor( _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden); } - public DataViewPrototype PrototypeObject { get; } + private DataViewPrototype PrototypeObject { get; } public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) { @@ -74,7 +74,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var o = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.DataView.PrototypeObject, - static (Engine engine, Realm _, object? _) => new DataViewInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsDataView(engine)); if (buffer.IsDetachedBuffer) { diff --git a/Jint/Native/DataView/DataViewPrototype.cs b/Jint/Native/DataView/DataViewPrototype.cs index 2cd12b5ab9..1fcf80be47 100644 --- a/Jint/Native/DataView/DataViewPrototype.cs +++ b/Jint/Native/DataView/DataViewPrototype.cs @@ -70,7 +70,7 @@ protected override void Initialize() /// private JsValue Buffer(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as DataViewInstance; + var o = thisObj as JsDataView; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.buffer called on incompatible receiver " + thisObj); @@ -84,7 +84,7 @@ private JsValue Buffer(JsValue thisObj, JsValue[] arguments) /// private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as DataViewInstance; + var o = thisObj as JsDataView; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteLength called on incompatible receiver " + thisObj); @@ -101,7 +101,7 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) { - var o = thisObj as DataViewInstance; + var o = thisObj as JsDataView; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteOffset called on incompatible receiver " + thisObj); @@ -222,7 +222,7 @@ private JsValue GetViewValue( JsValue isLittleEndian, TypedArrayElementType type) { - var dataView = view as DataViewInstance; + var dataView = view as JsDataView; if (dataView is null) { ExceptionHelper.ThrowTypeError(_realm, "Method called on incompatible receiver " + view); @@ -256,7 +256,7 @@ private JsValue SetViewValue( TypedArrayElementType type, JsValue value) { - var dataView = view as DataViewInstance; + var dataView = view as JsDataView; if (dataView is null) { ExceptionHelper.ThrowTypeError(_realm, "Method called on incompatible receiver " + view); diff --git a/Jint/Native/DataView/DataViewInstance.cs b/Jint/Native/DataView/JsDataView.cs similarity index 72% rename from Jint/Native/DataView/DataViewInstance.cs rename to Jint/Native/DataView/JsDataView.cs index eff16b1ff4..4930b72d24 100644 --- a/Jint/Native/DataView/DataViewInstance.cs +++ b/Jint/Native/DataView/JsDataView.cs @@ -6,13 +6,13 @@ namespace Jint.Native.DataView; /// /// https://tc39.es/ecma262/#sec-properties-of-dataview-instances /// -internal sealed class DataViewInstance : ObjectInstance +internal sealed class JsDataView : ObjectInstance { internal JsArrayBuffer? _viewedArrayBuffer; internal uint _byteLength; internal uint _byteOffset; - internal DataViewInstance(Engine engine) : base(engine) + internal JsDataView(Engine engine) : base(engine) { } } From a41a0e3c67526e2b8cc68c37050055280438a97a Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 28 Jul 2023 22:07:01 +0300 Subject: [PATCH 09/24] Make ArgumentsInstance internal (#1594) --- Jint/Native/Argument/ArgumentsInstance.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jint/Native/Argument/ArgumentsInstance.cs b/Jint/Native/Argument/ArgumentsInstance.cs index ee161d21fc..41d83967a9 100644 --- a/Jint/Native/Argument/ArgumentsInstance.cs +++ b/Jint/Native/Argument/ArgumentsInstance.cs @@ -13,7 +13,7 @@ namespace Jint.Native.Argument /// /// http://www.ecma-international.org/ecma-262/5.1/#sec-10.6 /// - public sealed class ArgumentsInstance : ObjectInstance + internal sealed class ArgumentsInstance : ObjectInstance { // cache property container for array iteration for less allocations private static readonly ThreadLocal> _mappedNamed = new(() => new HashSet()); From 40f1f420a705d21ecf4221b1721a7961eb679e1a Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Fri, 28 Jul 2023 22:18:19 +0300 Subject: [PATCH 10/24] Rename RegExpInstance to JsRegExp (#1595) --- Jint.Tests/Runtime/JsValueConversionTests.cs | 2 +- Jint/JsValueExtensions.cs | 6 +- Jint/Native/Iterator/IteratorInstance.cs | 8 +-- Jint/Native/Object/ObjectInstance.cs | 2 +- .../RegExp/{RegExpInstance.cs => JsRegExp.cs} | 4 +- Jint/Native/RegExp/RegExpConstructor.cs | 16 ++--- Jint/Native/RegExp/RegExpExtensions.cs | 2 +- Jint/Native/RegExp/RegExpPrototype.cs | 72 +++++++++---------- Jint/Native/String/StringPrototype.cs | 8 +-- 9 files changed, 60 insertions(+), 60 deletions(-) rename Jint/Native/RegExp/{RegExpInstance.cs => JsRegExp.cs} (97%) diff --git a/Jint.Tests/Runtime/JsValueConversionTests.cs b/Jint.Tests/Runtime/JsValueConversionTests.cs index b28cd97a14..5e61c1df8e 100644 --- a/Jint.Tests/Runtime/JsValueConversionTests.cs +++ b/Jint.Tests/Runtime/JsValueConversionTests.cs @@ -119,7 +119,7 @@ public void ShouldBeAnObject() [Fact] public void ShouldBeARegExp() { - var value = new RegExpInstance(_engine); + var value = new JsRegExp(_engine); Assert.Equal(false, value.IsBoolean()); Assert.Equal(false, value.IsArray()); Assert.Equal(false, value.IsDate()); diff --git a/Jint/JsValueExtensions.cs b/Jint/JsValueExtensions.cs index 0d8dc0074e..b26975b940 100644 --- a/Jint/JsValueExtensions.cs +++ b/Jint/JsValueExtensions.cs @@ -69,7 +69,7 @@ public static bool IsRegExp(this JsValue value) return TypeConverter.ToBoolean(matcher); } - return value is RegExpInstance; + return value is JsRegExp; } [Pure] @@ -148,14 +148,14 @@ public static JsDate AsDate(this JsValue value) } [Pure] - public static RegExpInstance AsRegExp(this JsValue value) + public static JsRegExp AsRegExp(this JsValue value) { if (!value.IsRegExp()) { ExceptionHelper.ThrowArgumentException("The value is not a regex"); } - return (RegExpInstance) value; + return (JsRegExp) value; } [Pure] diff --git a/Jint/Native/Iterator/IteratorInstance.cs b/Jint/Native/Iterator/IteratorInstance.cs index 12605c1869..fd8c86ef4e 100644 --- a/Jint/Native/Iterator/IteratorInstance.cs +++ b/Jint/Native/Iterator/IteratorInstance.cs @@ -132,7 +132,7 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) internal sealed class RegExpStringIterator : IteratorInstance { - private readonly RegExpInstance _iteratingRegExp; + private readonly JsRegExp _iteratingRegExp; private readonly string _s; private readonly bool _global; private readonly bool _unicode; @@ -141,7 +141,7 @@ internal sealed class RegExpStringIterator : IteratorInstance public RegExpStringIterator(Engine engine, ObjectInstance iteratingRegExp, string iteratedString, bool global, bool unicode) : base(engine) { - var r = iteratingRegExp as RegExpInstance; + var r = iteratingRegExp as JsRegExp; if (r is null) { ExceptionHelper.ThrowTypeError(engine.Realm); @@ -174,9 +174,9 @@ public override bool TryIteratorStep(out ObjectInstance nextItem) var macthStr = TypeConverter.ToString(match.Get(JsString.NumberZeroString)); if (macthStr == "") { - var thisIndex = TypeConverter.ToLength(_iteratingRegExp.Get(RegExpInstance.PropertyLastIndex)); + var thisIndex = TypeConverter.ToLength(_iteratingRegExp.Get(JsRegExp.PropertyLastIndex)); var nextIndex = thisIndex + 1; - _iteratingRegExp.Set(RegExpInstance.PropertyLastIndex, nextIndex, true); + _iteratingRegExp.Set(JsRegExp.PropertyLastIndex, nextIndex, true); } } else diff --git a/Jint/Native/Object/ObjectInstance.cs b/Jint/Native/Object/ObjectInstance.cs index 84d25dec63..4bdb5fba63 100644 --- a/Jint/Native/Object/ObjectInstance.cs +++ b/Jint/Native/Object/ObjectInstance.cs @@ -1024,7 +1024,7 @@ private object ToObject(ObjectTraverseStack stack) break; case ObjectClass.RegExp: - if (this is RegExpInstance regeExpInstance) + if (this is JsRegExp regeExpInstance) { converted = regeExpInstance.Value; } diff --git a/Jint/Native/RegExp/RegExpInstance.cs b/Jint/Native/RegExp/JsRegExp.cs similarity index 97% rename from Jint/Native/RegExp/RegExpInstance.cs rename to Jint/Native/RegExp/JsRegExp.cs index adcf4d1d97..bacd74c5cb 100644 --- a/Jint/Native/RegExp/RegExpInstance.cs +++ b/Jint/Native/RegExp/JsRegExp.cs @@ -5,7 +5,7 @@ namespace Jint.Native.RegExp { - public sealed class RegExpInstance : ObjectInstance + public sealed class JsRegExp : ObjectInstance { internal const string regExpForMatchingAllCharacters = "(?:)"; internal static readonly JsString PropertyLastIndex = new("lastIndex"); @@ -14,7 +14,7 @@ public sealed class RegExpInstance : ObjectInstance private PropertyDescriptor _prototypeDescriptor = null!; - public RegExpInstance(Engine engine) + public JsRegExp(Engine engine) : base(engine, ObjectClass.RegExp) { Source = regExpForMatchingAllCharacters; diff --git a/Jint/Native/RegExp/RegExpConstructor.cs b/Jint/Native/RegExp/RegExpConstructor.cs index 63bc12021a..8142cf9427 100644 --- a/Jint/Native/RegExp/RegExpConstructor.cs +++ b/Jint/Native/RegExp/RegExpConstructor.cs @@ -72,7 +72,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) JsValue p; JsValue f; - if (pattern is RegExpInstance regExpInstance) + if (pattern is JsRegExp regExpInstance) { p = regExpInstance.Source; f = flags.IsUndefined() ? regExpInstance.Flags : flags; @@ -92,7 +92,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) return RegExpInitialize(r, p, f); } - private ObjectInstance RegExpInitialize(RegExpInstance r, JsValue pattern, JsValue flags) + private ObjectInstance RegExpInitialize(JsRegExp r, JsValue pattern, JsValue flags) { var p = pattern.IsUndefined() ? "" : TypeConverter.ToString(pattern); if (string.IsNullOrEmpty(p)) @@ -129,18 +129,18 @@ private ObjectInstance RegExpInitialize(RegExpInstance r, JsValue pattern, JsVal return r; } - private RegExpInstance RegExpAlloc(JsValue newTarget) + private JsRegExp RegExpAlloc(JsValue newTarget) { var r = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.RegExp.PrototypeObject, - static (Engine engine, Realm _, object? _) => new RegExpInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsRegExp(engine)); return r; } - public RegExpInstance Construct(Regex regExp, string source, string flags) + public JsRegExp Construct(Regex regExp, string source, string flags) { - var r = new RegExpInstance(Engine); + var r = new JsRegExp(Engine); r._prototype = PrototypeObject; r.Flags = flags; @@ -161,9 +161,9 @@ public RegExpInstance Construct(Regex regExp, string source, string flags) return r; } - private static void RegExpInitialize(RegExpInstance r) + private static void RegExpInitialize(JsRegExp r) { - r.SetOwnProperty(RegExpInstance.PropertyLastIndex, new PropertyDescriptor(0, PropertyFlag.OnlyWritable)); + r.SetOwnProperty(JsRegExp.PropertyLastIndex, new PropertyDescriptor(0, PropertyFlag.OnlyWritable)); } } } diff --git a/Jint/Native/RegExp/RegExpExtensions.cs b/Jint/Native/RegExp/RegExpExtensions.cs index 0d29054732..927f8be297 100644 --- a/Jint/Native/RegExp/RegExpExtensions.cs +++ b/Jint/Native/RegExp/RegExpExtensions.cs @@ -12,7 +12,7 @@ internal static bool TryGetDefaultRegExpExec(this ObjectInstance? o, [NotNullWhe return prototype.TryGetDefaultExec(prototype, out exec); } - if (o is RegExpInstance instance) + if (o is JsRegExp instance) { exec = default; return instance.Properties == null diff --git a/Jint/Native/RegExp/RegExpPrototype.cs b/Jint/Native/RegExp/RegExpPrototype.cs index c079937a82..8e2e8a09c5 100644 --- a/Jint/Native/RegExp/RegExpPrototype.cs +++ b/Jint/Native/RegExp/RegExpPrototype.cs @@ -42,7 +42,7 @@ protected override void Initialize() { const PropertyFlag lengthFlags = PropertyFlag.Configurable; - GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func valueExtractor, JsValue? protoValue = null) + GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func valueExtractor, JsValue? protoValue = null) { return new GetSetPropertyDescriptor( get: new ClrFunctionInstance(Engine, name, (thisObj, arguments) => @@ -52,7 +52,7 @@ GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func= s.Length && s.Length > 0) { return JsBoolean.False; @@ -639,10 +639,10 @@ private JsValue Test(JsValue thisObj, JsValue[] arguments) var m = R.Value.Match(s, lastIndex); if (!m.Success || (R.Sticky && m.Index != lastIndex)) { - R.Set(RegExpInstance.PropertyLastIndex, 0, throwOnError: true); + R.Set(JsRegExp.PropertyLastIndex, 0, throwOnError: true); return JsBoolean.False; } - R.Set(RegExpInstance.PropertyLastIndex, m.Index + m.Length, throwOnError: true); + R.Set(JsRegExp.PropertyLastIndex, m.Index + m.Length, throwOnError: true); return JsBoolean.True; } @@ -658,17 +658,17 @@ private JsValue Search(JsValue thisObj, JsValue[] arguments) var rx = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.search"); var s = TypeConverter.ToString(arguments.At(0)); - var previousLastIndex = rx.Get(RegExpInstance.PropertyLastIndex); + var previousLastIndex = rx.Get(JsRegExp.PropertyLastIndex); if (!SameValue(previousLastIndex, 0)) { - rx.Set(RegExpInstance.PropertyLastIndex, 0, true); + rx.Set(JsRegExp.PropertyLastIndex, 0, true); } var result = RegExpExec(rx, s); - var currentLastIndex = rx.Get(RegExpInstance.PropertyLastIndex); + var currentLastIndex = rx.Get(JsRegExp.PropertyLastIndex); if (!SameValue(currentLastIndex, previousLastIndex)) { - rx.Set(RegExpInstance.PropertyLastIndex, previousLastIndex, true); + rx.Set(JsRegExp.PropertyLastIndex, previousLastIndex, true); } if (result.IsNull()) @@ -695,10 +695,10 @@ private JsValue Match(JsValue thisObj, JsValue[] arguments) } var fullUnicode = flags.IndexOf('u') != -1; - rx.Set(RegExpInstance.PropertyLastIndex, JsNumber.PositiveZero, true); + rx.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); if (!fullUnicode - && rx is RegExpInstance rei + && rx is JsRegExp rei && rei.TryGetDefaultRegExpExec(out _)) { // fast path @@ -762,9 +762,9 @@ private JsValue MatchSlow(ObjectInstance rx, string s, bool fullUnicode) a.SetIndexValue(n, matchStr, updateLength: false); if (matchStr == "") { - var thisIndex = TypeConverter.ToLength(rx.Get(RegExpInstance.PropertyLastIndex)); + var thisIndex = TypeConverter.ToLength(rx.Get(JsRegExp.PropertyLastIndex)); var nextIndex = AdvanceStringIndex(s, thisIndex, fullUnicode); - rx.Set(RegExpInstance.PropertyLastIndex, nextIndex, true); + rx.Set(JsRegExp.PropertyLastIndex, nextIndex, true); } n++; @@ -788,8 +788,8 @@ private JsValue MatchAll(JsValue thisObj, JsValue[] arguments) flags }); - var lastIndex = TypeConverter.ToLength(r.Get(RegExpInstance.PropertyLastIndex)); - matcher.Set(RegExpInstance.PropertyLastIndex, lastIndex, true); + var lastIndex = TypeConverter.ToLength(r.Get(JsRegExp.PropertyLastIndex)); + matcher.Set(JsRegExp.PropertyLastIndex, lastIndex, true); var global = flags.IndexOf('g') != -1; var fullUnicode = flags.IndexOf('u') != -1; @@ -833,7 +833,7 @@ internal static JsValue RegExpExec(ObjectInstance r, string s) return result; } - var ri = r as RegExpInstance; + var ri = r as JsRegExp; if (ri is null) { ExceptionHelper.ThrowTypeError(r.Engine.Realm); @@ -857,10 +857,10 @@ internal bool TryGetDefaultExec(ObjectInstance o, [NotNullWhen((true))] out Func /// /// https://tc39.es/ecma262/#sec-regexpbuiltinexec /// - private static JsValue RegExpBuiltinExec(RegExpInstance R, string s) + private static JsValue RegExpBuiltinExec(JsRegExp R, string s) { var length = (ulong) s.Length; - var lastIndex = TypeConverter.ToLength(R.Get(RegExpInstance.PropertyLastIndex)); + var lastIndex = TypeConverter.ToLength(R.Get(JsRegExp.PropertyLastIndex)); var global = R.Global; var sticky = R.Sticky; @@ -869,7 +869,7 @@ private static JsValue RegExpBuiltinExec(RegExpInstance R, string s) lastIndex = 0; } - if (R.Source == RegExpInstance.regExpForMatchingAllCharacters) // Reg Exp is really "" + if (R.Source == JsRegExp.regExpForMatchingAllCharacters) // Reg Exp is really "" { if (lastIndex > (ulong) s.Length) { @@ -906,7 +906,7 @@ private static JsValue RegExpBuiltinExec(RegExpInstance R, string s) { if (lastIndex > length) { - R.Set(RegExpInstance.PropertyLastIndex, JsNumber.PositiveZero, true); + R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); return Null; } @@ -914,7 +914,7 @@ private static JsValue RegExpBuiltinExec(RegExpInstance R, string s) var success = match.Success && (!sticky || match.Index == (int) lastIndex); if (!success) { - R.Set(RegExpInstance.PropertyLastIndex, JsNumber.PositiveZero, true); + R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); return Null; } @@ -929,7 +929,7 @@ private static JsValue RegExpBuiltinExec(RegExpInstance R, string s) if (global || sticky) { - R.Set(RegExpInstance.PropertyLastIndex, e, true); + R.Set(JsRegExp.PropertyLastIndex, e, true); } return CreateReturnValueArray(R.Engine, matcher, match, s, fullUnicode, hasIndices); @@ -1085,7 +1085,7 @@ private static JsValue GetMatchIndexPair(Engine engine, string s, JsNumber[] mat private JsValue Exec(JsValue thisObj, JsValue[] arguments) { - var r = thisObj as RegExpInstance; + var r = thisObj as JsRegExp; if (r is null) { ExceptionHelper.ThrowTypeError(_engine.Realm); diff --git a/Jint/Native/String/StringPrototype.cs b/Jint/Native/String/StringPrototype.cs index cf41656e1f..82f584f2ec 100644 --- a/Jint/Native/String/StringPrototype.cs +++ b/Jint/Native/String/StringPrototype.cs @@ -350,7 +350,7 @@ private JsValue Split(JsValue thisObj, JsValue[] arguments) var limit = arguments.At(1); // fast path for empty regexp - if (separator is RegExpInstance R && R.Source == RegExpInstance.regExpForMatchingAllCharacters) + if (separator is JsRegExp R && R.Source == JsRegExp.regExpForMatchingAllCharacters) { separator = JsString.Empty; } @@ -518,7 +518,7 @@ private JsValue Search(JsValue thisObj, JsValue[] arguments) } } - var rx = (RegExpInstance) _realm.Intrinsics.RegExp.Construct(new[] {regex}); + var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex}); var s = TypeConverter.ToJsString(thisObj); return _engine.Invoke(rx, GlobalSymbolRegistry.Search, new JsValue[] { s }); } @@ -686,7 +686,7 @@ private JsValue Match(JsValue thisObj, JsValue[] arguments) } } - var rx = (RegExpInstance) _realm.Intrinsics.RegExp.Construct(new[] {regex}); + var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex}); var s = TypeConverter.ToJsString(thisObj); return _engine.Invoke(rx, GlobalSymbolRegistry.Match, new JsValue[] { s }); @@ -716,7 +716,7 @@ private JsValue MatchAll(JsValue thisObj, JsValue[] arguments) } var s = TypeConverter.ToJsString(thisObj); - var rx = (RegExpInstance) _realm.Intrinsics.RegExp.Construct(new[] { regex, "g" }); + var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] { regex, "g" }); return _engine.Invoke(rx, GlobalSymbolRegistry.MatchAll, new JsValue[] { s }); } From ac1cec85dc576f2ffec87772f03eb68c1d9feac5 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sat, 29 Jul 2023 22:16:32 +0300 Subject: [PATCH 11/24] Upgrade to Esprima 3.0.0-rc-03 (#1596) Co-authored-by: adams85 <31276480+adams85@users.noreply.github.com> --- Jint.Repl/Program.cs | 2 +- .../Test262Harness.settings.json | 49 +++++-------------- Jint.Tests.Test262/Test262ModuleLoader.cs | 2 +- Jint.Tests.Test262/Test262Test.cs | 2 +- Jint.Tests/Runtime/ErrorTests.cs | 4 +- Jint/Engine.cs | 15 ++++-- Jint/Jint.csproj | 2 +- Jint/ModuleBuilder.cs | 5 +- .../Function/FunctionInstance.Dynamic.cs | 6 ++- Jint/Native/RegExp/RegExpConstructor.cs | 30 +++--------- Jint/Native/ShadowRealm/ShadowRealm.cs | 7 ++- .../Expressions/JintLiteralExpression.cs | 7 ++- 12 files changed, 58 insertions(+), 73 deletions(-) diff --git a/Jint.Repl/Program.cs b/Jint.Repl/Program.cs index 0bbc024b27..d906454cec 100644 --- a/Jint.Repl/Program.cs +++ b/Jint.Repl/Program.cs @@ -48,7 +48,7 @@ private static void Main(string[] args) var parserOptions = new ParserOptions { Tolerant = true, - AdaptRegexp = true + RegExpParseMode = RegExpParseMode.AdaptToInterpreted }; var serializer = new JsonSerializer(engine); diff --git a/Jint.Tests.Test262/Test262Harness.settings.json b/Jint.Tests.Test262/Test262Harness.settings.json index 63d84c6d58..0140de4ee3 100644 --- a/Jint.Tests.Test262/Test262Harness.settings.json +++ b/Jint.Tests.Test262/Test262Harness.settings.json @@ -30,26 +30,20 @@ "intl402" ], "ExcludedFiles": [ - // Esprima problem for regex, https://github.com/sebastienros/esprima-dotnet/pull/364 - "built-ins/RegExp/S15.10.4.1_A9_T3.js", // Currently quite impossible to detect if assignment target is CoverParenthesizedExpression "language/expressions/assignment/fn-name-lhs-cover.js", - // Unicode support not built-in to .NET the same way, requires more work - "built-ins/RegExp/prototype/Symbol.match/builtin-infer-unicode.js", - "built-ins/RegExp/prototype/Symbol.search/u-lastindex-advance.js", - "built-ins/RegExp/prototype/exec/u-lastindex-adv.js", - "built-ins/RegExp/unicode_character_class_backspace_escape.js", - "built-ins/RegExp/unicode_restricted_identity_escape_alpha.js", - "built-ins/RegExp/unicode_restricted_identity_escape_c.js", - "built-ins/RegExp/unicode_restricted_identity_escape_u.js", - "built-ins/RegExp/unicode_restricted_identity_escape_x.js", - "language/literals/regexp/u-astral-char-class-invert.js", - "language/literals/regexp/u-astral.js", - "language/literals/regexp/u-case-mapping.js", + // RegExp conversion limitations + "built-ins/RegExp/S15.10.2.11_A1_T5.js", + "built-ins/RegExp/S15.10.2.11_A1_T7.js", + "built-ins/RegExp/S15.10.2.5_A1_T4.js", + "built-ins/RegExp/named-groups/non-unicode-references.js", + "built-ins/RegExp/named-groups/unicode-references.js", + "built-ins/RegExp/quantifier-integer-limit.js", + "language/literals/regexp/named-groups/forward-reference.js", - // cannot have characters like 𝒜 as group name or something starting with $ in .NET, other .NET limitations + // RegExp handling problems "built-ins/RegExp/match-indices/indices-array-unicode-property-names.js", "built-ins/RegExp/named-groups/non-unicode-match.js", "built-ins/RegExp/named-groups/non-unicode-property-names-valid.js", @@ -58,17 +52,10 @@ "built-ins/RegExp/named-groups/unicode-property-names-valid.js", "built-ins/RegExp/named-groups/unicode-property-names.js", "built-ins/RegExp/prototype/Symbol.replace/named-groups.js", - "built-ins/RegExp/quantifier-integer-limit.js", - - // more validation and cleanup needed - "built-ins/RegExp/S15.10.2.13_A1_T1.js", - "built-ins/RegExp/S15.10.2.13_A1_T2.js", - "built-ins/RegExp/character-class-escape-non-whitespace.js", - "built-ins/RegExp/unicode_character_class_backspace_escape.js", - "built-ins/RegExp/unicode_identity_escape.js", - "built-ins/RegExp/unicode_restricted_character_class_escape.js", - "built-ins/RegExp/unicode_restricted_identity_escape.js", - "built-ins/RegExp/unicode_restricted_quantifiable_assertion.js", + "built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T6.js", + "built-ins/String/prototype/split/separator-regexp.js", + "language/literals/regexp/u-case-mapping.js", + "language/literals/regexp/u-surrogate-pairs-atom-escape-decimal.js", // requires investigation how to process complex function name evaluation for property "built-ins/Function/prototype/toString/method-computed-property-name.js", @@ -77,13 +64,6 @@ // http://www.ecma-international.org/ecma-262/#sec-block-level-function-declarations-web-legacy-compatibility-semantics not implemented (block level functions) "language/statements/let/block-local-closure-set-before-initialization.js", - // Logic difference in .NET RegExp / skipped in ECMA tests too - "built-ins/RegExp/S15.10.2.11_A1_T5.js", - "built-ins/RegExp/S15.10.2.11_A1_T7.js", - "built-ins/RegExp/S15.10.4.1_A8_T2.js", - "built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T6.js", - "built-ins/RegExp/S15.10.2.5_A1_T4.js", - // Windows line ending differences "built-ins/String/raw/special-characters.js", @@ -128,14 +108,11 @@ "language/module-code/instn-local-bndng-export-gen.js", // Esprima problem - "built-ins/String/prototype/split/separator-regexp.js", "language/expressions/object/let-non-strict-access.js", "language/expressions/object/let-non-strict-syntax.js", "language/expressions/object/yield-non-strict-access.js", "language/expressions/object/yield-non-strict-syntax.js", "language/expressions/tagged-template/invalid-escape-sequences.js", - "language/literals/regexp/u-surrogate-pairs-atom-escape-decimal.js", - "language/literals/regexp/u-unicode-esc.js", "language/statements/for-of/dstr-obj-id-identifier-yield-ident-valid.js", "language/statements/for/head-lhs-let.js", diff --git a/Jint.Tests.Test262/Test262ModuleLoader.cs b/Jint.Tests.Test262/Test262ModuleLoader.cs index 4baa4ce271..0ec50ddb0f 100644 --- a/Jint.Tests.Test262/Test262ModuleLoader.cs +++ b/Jint.Tests.Test262/Test262ModuleLoader.cs @@ -39,7 +39,7 @@ public Module LoadModule(Engine engine, ResolvedSpecifier resolved) var parserOptions = new ParserOptions { - AdaptRegexp = true, + RegExpParseMode = RegExpParseMode.AdaptToInterpreted, Tolerant = true }; diff --git a/Jint.Tests.Test262/Test262Test.cs b/Jint.Tests.Test262/Test262Test.cs index 6bbac100e4..18abc38a04 100644 --- a/Jint.Tests.Test262/Test262Test.cs +++ b/Jint.Tests.Test262/Test262Test.cs @@ -38,7 +38,7 @@ private Engine BuildTestExecutor(Test262File file) throw new Exception("only script parsing supported"); } - var options = new ParserOptions { AdaptRegexp = true, Tolerant = false }; + var options = new ParserOptions { RegExpParseMode = RegExpParseMode.AdaptToInterpreted, Tolerant = false }; var parser = new JavaScriptParser(options); var script = parser.ParseScript(args.At(0).AsString()); diff --git a/Jint.Tests/Runtime/ErrorTests.cs b/Jint.Tests/Runtime/ErrorTests.cs index 05639ec6e4..0f9e04c840 100644 --- a/Jint.Tests/Runtime/ErrorTests.cs +++ b/Jint.Tests/Runtime/ErrorTests.cs @@ -297,7 +297,7 @@ public void StackTraceCollectedForImmediatelyInvokedFunctionExpression() var parserOptions = new ParserOptions { - AdaptRegexp = true, + RegExpParseMode = RegExpParseMode.AdaptToInterpreted, Tolerant = true }; var ex = Assert.Throws(() => engine.Execute(script, "get-item.js", parserOptions)); @@ -388,7 +388,7 @@ static ParserOptions CreateParserOptions() { return new ParserOptions { - AdaptRegexp = true, + RegExpParseMode = RegExpParseMode.AdaptToInterpreted, Tolerant = true }; } diff --git a/Jint/Engine.cs b/Jint/Engine.cs index 0cbad545f1..0d58d105c6 100644 --- a/Jint/Engine.cs +++ b/Jint/Engine.cs @@ -26,11 +26,8 @@ namespace Jint /// public sealed partial class Engine : IDisposable { - private static readonly ParserOptions _defaultParserOptions = ParserOptions.Default with - { - AllowReturnOutsideFunction = true - }; - private readonly JavaScriptParser _defaultParser = new(_defaultParserOptions); + private readonly ParserOptions _defaultParserOptions; + private readonly JavaScriptParser _defaultParser; internal readonly ExecutionContextStack _executionContexts; private JsValue _completionValue = JsValue.Undefined; @@ -131,6 +128,14 @@ public Engine(Action options) CallStack = new JintCallStack(Options.Constraints.MaxRecursionDepth >= 0); _stackGuard = new StackGuard(this); + + _defaultParserOptions = ParserOptions.Default with + { + AllowReturnOutsideFunction = true, + RegexTimeout = Options.Constraints.RegexTimeout + }; + + _defaultParser = new JavaScriptParser(_defaultParserOptions); } private void Reset() diff --git a/Jint/Jint.csproj b/Jint/Jint.csproj index 01b7f6da55..5dfab6951e 100644 --- a/Jint/Jint.csproj +++ b/Jint/Jint.csproj @@ -16,7 +16,7 @@ - + diff --git a/Jint/ModuleBuilder.cs b/Jint/ModuleBuilder.cs index e1c18e5ee3..08c26dda8c 100644 --- a/Jint/ModuleBuilder.cs +++ b/Jint/ModuleBuilder.cs @@ -20,7 +20,10 @@ internal ModuleBuilder(Engine engine, string specifier) { _engine = engine; _specifier = specifier; - _options = new ParserOptions(); + _options = new ParserOptions + { + RegexTimeout = engine.Options.Constraints.RegexTimeout + }; } public ModuleBuilder AddSource(string code) diff --git a/Jint/Native/Function/FunctionInstance.Dynamic.cs b/Jint/Native/Function/FunctionInstance.Dynamic.cs index fb6317005a..162428b981 100644 --- a/Jint/Native/Function/FunctionInstance.Dynamic.cs +++ b/Jint/Native/Function/FunctionInstance.Dynamic.cs @@ -138,7 +138,11 @@ internal FunctionInstance CreateDynamicFunction( } } - JavaScriptParser parser = new(new ParserOptions { Tolerant = false }); + JavaScriptParser parser = new(new ParserOptions + { + Tolerant = false, + RegexTimeout = _engine.Options.Constraints.RegexTimeout + }); function = (IFunction) parser.ParseScript(functionExpression, source: null, _engine._isStrict).Body[0]; } catch (ParserException ex) diff --git a/Jint/Native/RegExp/RegExpConstructor.cs b/Jint/Native/RegExp/RegExpConstructor.cs index 8142cf9427..3a339fc672 100644 --- a/Jint/Native/RegExp/RegExpConstructor.cs +++ b/Jint/Native/RegExp/RegExpConstructor.cs @@ -104,17 +104,14 @@ private ObjectInstance RegExpInitialize(JsRegExp r, JsValue pattern, JsValue fla try { - var options = new ScannerOptions(); - var scanner = new Scanner("/" + p + "/" + flags, options); + var regExp = Scanner.AdaptRegExp(p, f, compiled: false, _engine.Options.Constraints.RegexTimeout); - // seems valid - r.Value = scanner.ParseRegex(p, f, options.RegexTimeout); - - var timeout = _engine.Options.Constraints.RegexTimeout; - if (timeout.Ticks > 0) + if (regExp is null) { - r.Value = new Regex(r.Value.ToString(), r.Value.Options, timeout); + ExceptionHelper.ThrowSyntaxError(_realm, $"Unsupported regular expression: '/{p}/{flags}'"); } + + r.Value = regExp; } catch (Exception ex) { @@ -140,21 +137,10 @@ private JsRegExp RegExpAlloc(JsValue newTarget) public JsRegExp Construct(Regex regExp, string source, string flags) { - var r = new JsRegExp(Engine); - r._prototype = PrototypeObject; - - r.Flags = flags; + var r = RegExpAlloc(this); + r.Value = regExp; r.Source = source; - - var timeout = _engine.Options.Constraints.RegexTimeout; - if (timeout.Ticks > 0) - { - r.Value = new Regex(regExp.ToString(), regExp.Options, timeout); - } - else - { - r.Value = regExp; - } + r.Flags = flags; RegExpInitialize(r); diff --git a/Jint/Native/ShadowRealm/ShadowRealm.cs b/Jint/Native/ShadowRealm/ShadowRealm.cs index a41cf456c4..1794feae5a 100644 --- a/Jint/Native/ShadowRealm/ShadowRealm.cs +++ b/Jint/Native/ShadowRealm/ShadowRealm.cs @@ -17,12 +17,17 @@ namespace Jint.Native.ShadowRealm; /// public sealed class ShadowRealm : ObjectInstance { - private readonly JavaScriptParser _parser = new(new ParserOptions { Tolerant = false }); + private readonly JavaScriptParser _parser; internal readonly Realm _shadowRealm; private readonly ExecutionContext _executionContext; internal ShadowRealm(Engine engine, ExecutionContext executionContext, Realm shadowRealm) : base(engine) { + _parser = new(new ParserOptions + { + Tolerant = false, + RegexTimeout = engine.Options.Constraints.RegexTimeout + }); _executionContext = executionContext; _shadowRealm = shadowRealm; } diff --git a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs index 20cd2cd70d..de5de54832 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs @@ -76,7 +76,12 @@ private JsValue ResolveValue(EvaluationContext context) if (expression.TokenType == TokenType.RegularExpression) { var regExpLiteral = (RegExpLiteral) _expression; - return context.Engine.Realm.Intrinsics.RegExp.Construct((System.Text.RegularExpressions.Regex) regExpLiteral.Value!, regExpLiteral.Regex.Pattern, regExpLiteral.Regex.Flags); + if (regExpLiteral.Value is System.Text.RegularExpressions.Regex regex) + { + return context.Engine.Realm.Intrinsics.RegExp.Construct(regex, regExpLiteral.Regex.Pattern, regExpLiteral.Regex.Flags); + } + + ExceptionHelper.ThrowSyntaxError(context.Engine.Realm, $"Unsupported regular expression: '{regExpLiteral.Regex.Pattern}/{regExpLiteral.Regex.Flags}'"); } return JsValue.FromObject(context.Engine, expression.Value); From 2ec677c1a1f97e40b735985a334617663311dde0 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 20:53:58 +0300 Subject: [PATCH 12/24] Rename thisObj to thisObject and args as arguments in parameter names (#1597) --- Jint.Tests/Runtime/Domain/UuidPrototype.cs | 11 +- Jint/Native/Array/ArrayConstructor.cs | 24 +- Jint/Native/Array/ArrayPrototype.cs | 156 ++++++------ .../ArrayBuffer/ArrayBufferPrototype.cs | 18 +- Jint/Native/BigInt/BigIntConstructor.cs | 4 +- Jint/Native/BigInt/BigIntPrototype.cs | 8 +- Jint/Native/Boolean/BooleanPrototype.cs | 12 +- Jint/Native/DataView/DataViewPrototype.cs | 98 ++++---- Jint/Native/Date/DateConstructor.cs | 6 +- Jint/Native/Date/DatePrototype.cs | 220 ++++++++-------- .../FinalizationRegistryPrototype.cs | 30 +-- .../Function/FunctionInstance.Dynamic.cs | 12 +- Jint/Native/Function/FunctionPrototype.cs | 14 +- Jint/Native/Global/GlobalObject.cs | 4 +- Jint/Native/GroupByHelper.cs | 2 +- Jint/Native/Iterator/IteratorProtocol.cs | 2 +- Jint/Native/Iterator/IteratorPrototype.cs | 8 +- Jint/Native/Map/MapPrototype.cs | 52 ++-- Jint/Native/Number/NumberConstructor.cs | 8 +- Jint/Native/Number/NumberPrototype.cs | 28 +-- Jint/Native/Promise/PromiseConstructor.cs | 56 ++--- Jint/Native/Promise/PromiseInstance.cs | 4 +- Jint/Native/Promise/PromisePrototype.cs | 12 +- Jint/Native/RegExp/RegExpPrototype.cs | 42 ++-- Jint/Native/Set/SetPrototype.cs | 44 ++-- .../ShadowRealm/ShadowRealmPrototype.cs | 18 +- Jint/Native/String/StringConstructor.cs | 4 +- Jint/Native/String/StringPrototype.cs | 234 +++++++++--------- Jint/Native/Symbol/SymbolConstructor.cs | 4 +- .../IntrinsicTypedArrayConstructor.cs | 12 +- .../IntrinsicTypedArrayPrototype.cs | 146 +++++------ .../TypedArray/TypedArrayConstructor.cs | 10 +- Jint/Native/WeakMap/WeakMapPrototype.cs | 28 +-- Jint/Native/WeakRef/WeakRefPrototype.cs | 4 +- Jint/Native/WeakSet/WeakSetPrototype.cs | 24 +- .../Environments/FunctionEnvironmentRecord.cs | 2 +- Jint/Runtime/Interop/ObjectWrapper.cs | 8 +- .../Expressions/JintArrayExpression.cs | 2 +- .../Interpreter/Expressions/JintExpression.cs | 2 +- Jint/Runtime/Modules/CyclicModuleRecord.cs | 6 +- 40 files changed, 686 insertions(+), 693 deletions(-) diff --git a/Jint.Tests/Runtime/Domain/UuidPrototype.cs b/Jint.Tests/Runtime/Domain/UuidPrototype.cs index 9d887218a9..6a1fb8335b 100644 --- a/Jint.Tests/Runtime/Domain/UuidPrototype.cs +++ b/Jint.Tests/Runtime/Domain/UuidPrototype.cs @@ -11,17 +11,14 @@ private UuidPrototype(Engine engine) : base(engine) { } - private UuidInstance EnsureUuidInstance(JsValue thisObj) + private UuidInstance EnsureUuidInstance(JsValue thisObject) { - return thisObj.TryCast(value => - { - throw new JavaScriptException(Engine.Realm.Intrinsics.TypeError, "Invalid Uuid"); - }); + return thisObject.TryCast(value => throw new JavaScriptException(Engine.Realm.Intrinsics.TypeError, "Invalid Uuid")); } - private JsValue ToGuidString(JsValue thisObj, JsValue[] arguments) => EnsureUuidInstance(thisObj).PrimitiveValue.ToString(); + private JsValue ToGuidString(JsValue thisObject, JsValue[] arguments) => EnsureUuidInstance(thisObject).PrimitiveValue.ToString(); - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) => EnsureUuidInstance(thisObj).PrimitiveValue; + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) => EnsureUuidInstance(thisObject).PrimitiveValue; public static UuidPrototype CreatePrototypeObject(Engine engine, UuidConstructor ctor) { diff --git a/Jint/Native/Array/ArrayConstructor.cs b/Jint/Native/Array/ArrayConstructor.cs index a4783f81e2..52de03cb64 100644 --- a/Jint/Native/Array/ArrayConstructor.cs +++ b/Jint/Native/Array/ArrayConstructor.cs @@ -49,7 +49,7 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-array.from /// - private JsValue From(JsValue thisObj, JsValue[] arguments) + private JsValue From(JsValue thisObject, JsValue[] arguments) { var items = arguments.At(0); var mapFunction = arguments.At(1); @@ -65,9 +65,9 @@ private JsValue From(JsValue thisObj, JsValue[] arguments) if (usingIterator is not null) { ObjectInstance instance; - if (!ReferenceEquals(this, thisObj) && thisObj is IConstructor constructor) + if (!ReferenceEquals(this, thisObject) && thisObject is IConstructor constructor) { - instance = constructor.Construct(System.Array.Empty(), thisObj); + instance = constructor.Construct(System.Array.Empty(), thisObject); } else { @@ -86,7 +86,7 @@ private JsValue From(JsValue thisObj, JsValue[] arguments) return ConstructArrayFromIEnumerable(enumerable); } - return ConstructArrayFromArrayLike(thisObj, objectInstance, callable, thisArg); + return ConstructArrayFromArrayLike(thisObject, objectInstance, callable, thisArg); } private ObjectInstance ConstructArrayFromArrayLike( @@ -160,15 +160,15 @@ public ArrayProtocol( _callable = callable; } - protected override void ProcessItem(JsValue[] args, JsValue currentValue) + protected override void ProcessItem(JsValue[] arguments, JsValue currentValue) { _index++; JsValue jsValue; if (!ReferenceEquals(_callable, null)) { - args[0] = currentValue; - args[1] = _index; - jsValue = _callable.Call(_thisArg, args); + arguments[0] = currentValue; + arguments[1] = _index; + jsValue = _callable.Call(_thisArg, arguments); } else { @@ -184,13 +184,13 @@ protected override void IterationEnd() } } - private JsValue Of(JsValue thisObj, JsValue[] arguments) + private JsValue Of(JsValue thisObject, JsValue[] arguments) { var len = arguments.Length; ObjectInstance a; - if (thisObj.IsConstructor) + if (thisObject.IsConstructor) { - a = ((IConstructor) thisObj).Construct(new JsValue[] { len }, thisObj); + a = ((IConstructor) thisObject).Construct(new JsValue[] { len }, thisObject); } else { @@ -227,7 +227,7 @@ private static JsValue Species(JsValue thisObject, JsValue[] arguments) return thisObject; } - private static JsValue IsArray(JsValue thisObj, JsValue[] arguments) + private static JsValue IsArray(JsValue thisObject, JsValue[] arguments) { var o = arguments.At(0); diff --git a/Jint/Native/Array/ArrayPrototype.cs b/Jint/Native/Array/ArrayPrototype.cs index 299223088a..1d48f6e3eb 100644 --- a/Jint/Native/Array/ArrayPrototype.cs +++ b/Jint/Native/Array/ArrayPrototype.cs @@ -115,9 +115,9 @@ protected override void Initialize() SetSymbols(symbols); } - private ObjectInstance Keys(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Keys(JsValue thisObject, JsValue[] arguments) { - if (thisObj is ObjectInstance oi && oi.IsArrayLike) + if (thisObject is ObjectInstance oi && oi.IsArrayLike) { return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Key); } @@ -126,9 +126,9 @@ private ObjectInstance Keys(JsValue thisObj, JsValue[] arguments) return null; } - internal ObjectInstance Values(JsValue thisObj, JsValue[] arguments) + internal ObjectInstance Values(JsValue thisObject, JsValue[] arguments) { - if (thisObj is ObjectInstance oi && oi.IsArrayLike) + if (thisObject is ObjectInstance oi && oi.IsArrayLike) { return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.Value); } @@ -137,9 +137,9 @@ internal ObjectInstance Values(JsValue thisObj, JsValue[] arguments) return null; } - private ObjectInstance With(JsValue thisObj, JsValue[] arguments) + private ObjectInstance With(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj)); + var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject)); var len = o.GetLongLength(); var relativeIndex = TypeConverter.ToIntegerOrInfinity(arguments.At(0)); var value = arguments.At(1); @@ -169,9 +169,9 @@ private ObjectInstance With(JsValue thisObj, JsValue[] arguments) return new JsArray(_engine, a); } - private ObjectInstance Entries(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Entries(JsValue thisObject, JsValue[] arguments) { - if (thisObj is ObjectInstance oi && oi.IsArrayLike) + if (thisObject is ObjectInstance oi && oi.IsArrayLike) { return _realm.Intrinsics.ArrayIteratorPrototype.Construct(oi, ArrayIteratorType.KeyAndValue); } @@ -183,13 +183,13 @@ private ObjectInstance Entries(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.fill /// - private JsValue Fill(JsValue thisObj, JsValue[] arguments) + private JsValue Fill(JsValue thisObject, JsValue[] arguments) { var value = arguments.At(0); var start = arguments.At(1); var end = arguments.At(2); - var o = TypeConverter.ToObject(_realm, thisObj); + var o = TypeConverter.ToObject(_realm, thisObject); var operations = ArrayOperations.For(o); var length = operations.GetLongLength(); @@ -236,9 +236,9 @@ private JsValue Fill(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.copywithin /// - private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments) + private JsValue CopyWithin(JsValue thisObject, JsValue[] arguments) { - var o = TypeConverter.ToObject(_realm, thisObj); + var o = TypeConverter.ToObject(_realm, thisObject); JsValue target = arguments.At(0); JsValue start = arguments.At(1); @@ -319,9 +319,9 @@ private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.lastindexof /// - private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); if (len == 0) { @@ -372,12 +372,12 @@ private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.reduce /// - private JsValue Reduce(JsValue thisObj, JsValue[] arguments) + private JsValue Reduce(JsValue thisObject, JsValue[] arguments) { var callbackfn = arguments.At(0); var initialValue = arguments.At(1); - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLength(); var callable = GetCallable(callbackfn); @@ -434,17 +434,17 @@ private JsValue Reduce(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.filter /// - private JsValue Filter(JsValue thisObj, JsValue[] arguments) + private JsValue Filter(JsValue thisObject, JsValue[] arguments) { var callbackfn = arguments.At(0); var thisArg = arguments.At(1); - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLength(); var callable = GetCallable(callbackfn); - var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), 0); + var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0); var operations = ArrayOperations.For(a); uint to = 0; @@ -474,15 +474,15 @@ private JsValue Filter(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.map /// - private JsValue Map(JsValue thisObj, JsValue[] arguments) + private JsValue Map(JsValue thisObject, JsValue[] arguments) { - if (thisObj is JsArray { CanUseFastAccess: true } arrayInstance + if (thisObject is JsArray { CanUseFastAccess: true } arrayInstance && !arrayInstance.HasOwnProperty(CommonProperties.Constructor)) { return arrayInstance.Map(arguments); } - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); if (len > ArrayOperations.MaxArrayLength) @@ -494,7 +494,7 @@ private JsValue Map(JsValue thisObj, JsValue[] arguments) var thisArg = arguments.At(1); var callable = GetCallable(callbackfn); - var a = ArrayOperations.For(_realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), (uint) len)); + var a = ArrayOperations.For(_realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), (uint) len)); var args = _engine._jsValueArrayPool.RentArray(3); args[2] = o.Target; for (uint k = 0; k < len; k++) @@ -514,9 +514,9 @@ private JsValue Map(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.flat /// - private JsValue Flat(JsValue thisObj, JsValue[] arguments) + private JsValue Flat(JsValue thisObject, JsValue[] arguments) { - var O = TypeConverter.ToObject(_realm, thisObj); + var O = TypeConverter.ToObject(_realm, thisObject); var operations = ArrayOperations.For(O); var sourceLen = operations.GetLength(); double depthNum = 1; @@ -539,9 +539,9 @@ private JsValue Flat(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.flatmap /// - private JsValue FlatMap(JsValue thisObj, JsValue[] arguments) + private JsValue FlatMap(JsValue thisObject, JsValue[] arguments) { - var O = TypeConverter.ToObject(_realm, thisObj); + var O = TypeConverter.ToObject(_realm, thisObject); var mapperFunction = arguments.At(0); var thisArg = arguments.At(1); @@ -632,12 +632,12 @@ private long FlattenIntoArray( return targetIndex; } - private JsValue ForEach(JsValue thisObj, JsValue[] arguments) + private JsValue ForEach(JsValue thisObject, JsValue[] arguments) { var callbackfn = arguments.At(0); var thisArg = arguments.At(1); - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLength(); var callable = GetCallable(callbackfn); @@ -661,9 +661,9 @@ private JsValue ForEach(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.includes /// - private JsValue Includes(JsValue thisObj, JsValue[] arguments) + private JsValue Includes(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = (long) o.GetLongLength(); if (len == 0) @@ -709,18 +709,18 @@ private JsValue Includes(JsValue thisObj, JsValue[] arguments) return false; } - private JsValue Some(JsValue thisObj, JsValue[] arguments) + private JsValue Some(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); return target.FindWithCallback(arguments, out _, out _, false); } /// /// https://tc39.es/ecma262/#sec-array.prototype.every /// - private JsValue Every(JsValue thisObj, JsValue[] arguments) + private JsValue Every(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); ulong len = o.GetLongLength(); if (len == 0) @@ -755,9 +755,9 @@ private JsValue Every(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.indexof /// - private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue IndexOf(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); if (len == 0) { @@ -821,9 +821,9 @@ private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.find /// - private JsValue Find(JsValue thisObj, JsValue[] arguments) + private JsValue Find(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true); return value; } @@ -831,9 +831,9 @@ private JsValue Find(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.findindex /// - private JsValue FindIndex(JsValue thisObj, JsValue[] arguments) + private JsValue FindIndex(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true)) { return index; @@ -841,16 +841,16 @@ private JsValue FindIndex(JsValue thisObj, JsValue[] arguments) return -1; } - private JsValue FindLast(JsValue thisObj, JsValue[] arguments) + private JsValue FindLast(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); target.FindWithCallback(arguments, out _, out var value, visitUnassigned: true, fromEnd: true); return value; } - private JsValue FindLastIndex(JsValue thisObj, JsValue[] arguments) + private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); if (target.FindWithCallback(arguments, out var index, out _, visitUnassigned: true, fromEnd: true)) { return index; @@ -861,9 +861,9 @@ private JsValue FindLastIndex(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/proposal-relative-indexing-method/#sec-array-prototype-additions /// - private JsValue At(JsValue thisObj, JsValue[] arguments) + private JsValue At(JsValue thisObject, JsValue[] arguments) { - var target = TypeConverter.ToObject(_realm, thisObj); + var target = TypeConverter.ToObject(_realm, thisObject); var len = target.Length; var relativeIndex = TypeConverter.ToInteger(arguments.At(0)); @@ -888,12 +888,12 @@ private JsValue At(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.splice /// - private JsValue Splice(JsValue thisObj, JsValue[] arguments) + private JsValue Splice(JsValue thisObject, JsValue[] arguments) { var start = arguments.At(0); var deleteCount = arguments.At(1); - var obj = TypeConverter.ToObject(_realm, thisObj); + var obj = TypeConverter.ToObject(_realm, thisObject); var o = ArrayOperations.For(_realm, obj); var len = o.GetLongLength(); var relativeStart = TypeConverter.ToInteger(start); @@ -1008,9 +1008,9 @@ private JsValue Splice(JsValue thisObj, JsValue[] arguments) /// /// /https://tc39.es/ecma262/#sec-array.prototype.unshift /// - private JsValue Unshift(JsValue thisObj, JsValue[] arguments) + private JsValue Unshift(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); var argCount = (uint) arguments.Length; @@ -1047,9 +1047,9 @@ private JsValue Unshift(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.sort /// - private JsValue Sort(JsValue thisObj, JsValue[] arguments) + private JsValue Sort(JsValue thisObject, JsValue[] arguments) { - var objectInstance = TypeConverter.ToObject(_realm, thisObj); + var objectInstance = TypeConverter.ToObject(_realm, thisObject); var obj = ArrayOperations.For(objectInstance); var compareFn = GetCompareFunction(arguments.At(0)); @@ -1097,12 +1097,12 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.slice /// - private JsValue Slice(JsValue thisObj, JsValue[] arguments) + private JsValue Slice(JsValue thisObject, JsValue[] arguments) { var start = arguments.At(0); var end = arguments.At(1); - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); var relativeStart = TypeConverter.ToInteger(start); @@ -1140,8 +1140,8 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) } var length = (uint) System.Math.Max(0, (long) final - (long) k); - var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), length); - if (thisObj is JsArray ai && a is JsArray a2) + var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), length); + if (thisObject is JsArray ai && a is JsArray a2) { a2.CopyValues(ai, (uint) k, 0, length); } @@ -1160,9 +1160,9 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) return a; } - private JsValue Shift(JsValue thisObj, JsValue[] arg2) + private JsValue Shift(JsValue thisObject, JsValue[] arg2) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLength(); if (len == 0) { @@ -1193,9 +1193,9 @@ private JsValue Shift(JsValue thisObj, JsValue[] arg2) /// /// https://tc39.es/ecma262/#sec-array.prototype.reverse /// - private JsValue Reverse(JsValue thisObj, JsValue[] arguments) + private JsValue Reverse(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLongLength(); var middle = (ulong) System.Math.Floor(len / 2.0); uint lower = 0; @@ -1236,10 +1236,10 @@ private JsValue Reverse(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.join /// - private JsValue Join(JsValue thisObj, JsValue[] arguments) + private JsValue Join(JsValue thisObject, JsValue[] arguments) { var separator = arguments.At(0); - var o = ArrayOperations.For(_realm, thisObj); + var o = ArrayOperations.For(_realm, thisObject); var len = o.GetLength(); var sep = TypeConverter.ToString(separator.IsUndefined() ? JsString.CommaString : separator); @@ -1277,9 +1277,9 @@ static string StringFromJsValue(JsValue value) return sb.ToString(); } - private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments) { - var array = ArrayOperations.For(_realm, thisObj); + var array = ArrayOperations.For(_realm, thisObject); var len = array.GetLength(); const string Separator = ","; if (len == 0) @@ -1318,14 +1318,14 @@ private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-array.prototype.concat /// - private JsValue Concat(JsValue thisObj, JsValue[] arguments) + private JsValue Concat(JsValue thisObject, JsValue[] arguments) { - var o = TypeConverter.ToObject(_realm, thisObj); + var o = TypeConverter.ToObject(_realm, thisObject); var items = new List(arguments.Length + 1) {o}; items.AddRange(arguments); uint n = 0; - var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObj), 0); + var a = _realm.Intrinsics.Array.ArraySpeciesCreate(TypeConverter.ToObject(_realm, thisObject), 0); var aOperations = ArrayOperations.For(a); for (var i = 0; i < items.Count; i++) { @@ -1369,9 +1369,9 @@ private JsValue Concat(JsValue thisObj, JsValue[] arguments) return a; } - internal JsValue ToString(JsValue thisObj, JsValue[] arguments) + internal JsValue ToString(JsValue thisObject, JsValue[] arguments) { - var array = TypeConverter.ToObject(_realm, thisObj); + var array = TypeConverter.ToObject(_realm, thisObject); Func func; if (array.Get("join") is ICallable joinFunc) @@ -1386,9 +1386,9 @@ internal JsValue ToString(JsValue thisObj, JsValue[] arguments) return func(array, Arguments.Empty); } - private JsValue ToReversed(JsValue thisObj, JsValue[] arguments) + private JsValue ToReversed(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj)); + var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject)); var len = o.GetLongLength(); @@ -1407,9 +1407,9 @@ private JsValue ToReversed(JsValue thisObj, JsValue[] arguments) return new JsArray(_engine, a); } - private JsValue ToSorted(JsValue thisObj, JsValue[] arguments) + private JsValue ToSorted(JsValue thisObject, JsValue[] arguments) { - var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj)); + var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject)); var compareFn = GetCompareFunction(arguments.At(0)); var len = o.GetLongLength(); @@ -1427,12 +1427,12 @@ private JsValue ToSorted(JsValue thisObj, JsValue[] arguments) return new JsArray(_engine, array); } - private JsValue ToSpliced(JsValue thisObj, JsValue[] arguments) + private JsValue ToSpliced(JsValue thisObject, JsValue[] arguments) { var start = arguments.At(0); var deleteCount = arguments.At(1); - var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObj)); + var o = ArrayOperations.For(_realm, TypeConverter.ToObject(_realm, thisObject)); var len = o.GetLongLength(); var relativeStart = TypeConverter.ToIntegerOrInfinity(start); @@ -1547,12 +1547,12 @@ private JsValue[] SortArray(IEnumerable array, ICallable? compareFn) /// /// https://tc39.es/ecma262/#sec-array.prototype.reduceright /// - private JsValue ReduceRight(JsValue thisObj, JsValue[] arguments) + private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments) { var callbackfn = arguments.At(0); var initialValue = arguments.At(1); - var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObj)); + var o = ArrayOperations.For(TypeConverter.ToObject(_realm, thisObject)); var len = o.GetLongLength(); var callable = GetCallable(callbackfn); diff --git a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs index dcf9d8414c..ae7aab0533 100644 --- a/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs +++ b/Jint/Native/ArrayBuffer/ArrayBufferPrototype.cs @@ -42,12 +42,12 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Detached(JsValue thisObj, JsValue[] arguments) + private JsValue Detached(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsArrayBuffer; + var o = thisObject as JsArrayBuffer; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.detached called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.detached called on incompatible receiver " + thisObject); } if (o.IsSharedArrayBuffer) @@ -61,12 +61,12 @@ private JsValue Detached(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-arraybuffer.prototype.bytelength /// - private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) + private JsValue ByteLength(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsArrayBuffer; + var o = thisObject as JsArrayBuffer; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.byteLength called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.byteLength called on incompatible receiver " + thisObject); } if (o.IsSharedArrayBuffer) @@ -85,12 +85,12 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice /// - private JsValue Slice(JsValue thisObj, JsValue[] arguments) + private JsValue Slice(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsArrayBuffer; + var o = thisObject as JsArrayBuffer; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.slice called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method ArrayBuffer.prototype.slice called on incompatible receiver " + thisObject); } if (o.IsSharedArrayBuffer) diff --git a/Jint/Native/BigInt/BigIntConstructor.cs b/Jint/Native/BigInt/BigIntConstructor.cs index 6bdb9a1ba5..d5971124b1 100644 --- a/Jint/Native/BigInt/BigIntConstructor.cs +++ b/Jint/Native/BigInt/BigIntConstructor.cs @@ -41,7 +41,7 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-bigint.asintn /// - private JsValue AsIntN(JsValue thisObj, JsValue[] arguments) + private JsValue AsIntN(JsValue thisObject, JsValue[] arguments) { var bits = (int) TypeConverter.ToIndex(_realm, arguments.At(0)); var bigint = arguments.At(1).ToBigInteger(_engine); @@ -58,7 +58,7 @@ private JsValue AsIntN(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-bigint.asuintn /// - private JsValue AsUintN(JsValue thisObj, JsValue[] arguments) + private JsValue AsUintN(JsValue thisObject, JsValue[] arguments) { var bits = (int) TypeConverter.ToIndex(_realm, arguments.At(0)); var bigint = arguments.At(1).ToBigInteger(_engine); diff --git a/Jint/Native/BigInt/BigIntPrototype.cs b/Jint/Native/BigInt/BigIntPrototype.cs index b19d88a8ab..8d801fce9a 100644 --- a/Jint/Native/BigInt/BigIntPrototype.cs +++ b/Jint/Native/BigInt/BigIntPrototype.cs @@ -61,16 +61,16 @@ private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-bigint.prototype.valueof /// - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) { - if (thisObj is BigIntInstance ni) + if (thisObject is BigIntInstance ni) { return ni.BigIntData; } - if (thisObj is JsBigInt) + if (thisObject is JsBigInt) { - return thisObj; + return thisObject; } ExceptionHelper.ThrowTypeError(_realm); diff --git a/Jint/Native/Boolean/BooleanPrototype.cs b/Jint/Native/Boolean/BooleanPrototype.cs index f9be47db54..2379426429 100644 --- a/Jint/Native/Boolean/BooleanPrototype.cs +++ b/Jint/Native/Boolean/BooleanPrototype.cs @@ -36,14 +36,14 @@ protected override void Initialize() SetProperties(properties); } - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) { - if (thisObj._type == InternalTypes.Boolean) + if (thisObject._type == InternalTypes.Boolean) { - return thisObj; + return thisObject; } - if (thisObj is BooleanInstance bi) + if (thisObject is BooleanInstance bi) { return bi.BooleanData; } @@ -52,9 +52,9 @@ private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) return Undefined; } - private JsValue ToBooleanString(JsValue thisObj, JsValue[] arguments) + private JsValue ToBooleanString(JsValue thisObject, JsValue[] arguments) { - var b = ValueOf(thisObj, Arguments.Empty); + var b = ValueOf(thisObject, Arguments.Empty); return ((JsBoolean) b)._value ? JsString.TrueString : JsString.FalseString; } } diff --git a/Jint/Native/DataView/DataViewPrototype.cs b/Jint/Native/DataView/DataViewPrototype.cs index 1fcf80be47..304de07084 100644 --- a/Jint/Native/DataView/DataViewPrototype.cs +++ b/Jint/Native/DataView/DataViewPrototype.cs @@ -68,12 +68,12 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-get-dataview.prototype.buffer /// - private JsValue Buffer(JsValue thisObj, JsValue[] arguments) + private JsValue Buffer(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsDataView; + var o = thisObject as JsDataView; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.buffer called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.buffer called on incompatible receiver " + thisObject); } return o._viewedArrayBuffer!; @@ -82,12 +82,12 @@ private JsValue Buffer(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-dataview.prototype.bytelength /// - private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) + private JsValue ByteLength(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsDataView; + var o = thisObject as JsDataView; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteLength called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteLength called on incompatible receiver " + thisObject); } var buffer = o._viewedArrayBuffer!; @@ -99,12 +99,12 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-dataview.prototype.byteoffset /// - private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) + private JsValue ByteOffset(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsDataView; + var o = thisObject as JsDataView; if (o is null) { - ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteOffset called on incompatible receiver " + thisObj); + ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteOffset called on incompatible receiver " + thisObject); } var buffer = o._viewedArrayBuffer!; @@ -113,104 +113,104 @@ private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) return JsNumber.Create(o._byteOffset); } - private JsValue GetBigInt64(JsValue thisObj, JsValue[] arguments) + private JsValue GetBigInt64(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1), TypedArrayElementType.BigInt64); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1), TypedArrayElementType.BigInt64); } - private JsValue GetBigUint64(JsValue thisObj, JsValue[] arguments) + private JsValue GetBigUint64(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1), TypedArrayElementType.BigUint64); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1), TypedArrayElementType.BigUint64); } - private JsValue GetFloat32(JsValue thisObj, JsValue[] arguments) + private JsValue GetFloat32(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float32); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float32); } - private JsValue GetFloat64(JsValue thisObj, JsValue[] arguments) + private JsValue GetFloat64(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float64); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float64); } - private JsValue GetInt8(JsValue thisObj, JsValue[] arguments) + private JsValue GetInt8(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8); + return GetViewValue(thisObject, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8); } - private JsValue GetInt16(JsValue thisObj, JsValue[] arguments) + private JsValue GetInt16(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int16); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int16); } - private JsValue GetInt32(JsValue thisObj, JsValue[] arguments) + private JsValue GetInt32(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int32); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int32); } - private JsValue GetUint8(JsValue thisObj, JsValue[] arguments) + private JsValue GetUint8(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8); + return GetViewValue(thisObject, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8); } - private JsValue GetUint16(JsValue thisObj, JsValue[] arguments) + private JsValue GetUint16(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint16); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint16); } - private JsValue GetUint32(JsValue thisObj, JsValue[] arguments) + private JsValue GetUint32(JsValue thisObject, JsValue[] arguments) { - return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint32); + return GetViewValue(thisObject, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint32); } - private JsValue SetBigInt64(JsValue thisObj, JsValue[] arguments) + private JsValue SetBigInt64(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2), TypedArrayElementType.BigInt64, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2), TypedArrayElementType.BigInt64, arguments.At(1)); } - private JsValue SetBigUint64(JsValue thisObj, JsValue[] arguments) + private JsValue SetBigUint64(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2), TypedArrayElementType.BigUint64, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2), TypedArrayElementType.BigUint64, arguments.At(1)); } - private JsValue SetFloat32 (JsValue thisObj, JsValue[] arguments) + private JsValue SetFloat32 (JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float32, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float32, arguments.At(1)); } - private JsValue SetFloat64(JsValue thisObj, JsValue[] arguments) + private JsValue SetFloat64(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float64, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float64, arguments.At(1)); } - private JsValue SetInt8 (JsValue thisObj, JsValue[] arguments) + private JsValue SetInt8 (JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8, arguments.At(1)); } - private JsValue SetInt16(JsValue thisObj, JsValue[] arguments) + private JsValue SetInt16(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int16, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int16, arguments.At(1)); } - private JsValue SetInt32(JsValue thisObj, JsValue[] arguments) + private JsValue SetInt32(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int32, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int32, arguments.At(1)); } - private JsValue SetUint8(JsValue thisObj, JsValue[] arguments) + private JsValue SetUint8(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8, arguments.At(1)); } - private JsValue SetUint16(JsValue thisObj, JsValue[] arguments) + private JsValue SetUint16(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint16, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint16, arguments.At(1)); } - private JsValue SetUint32(JsValue thisObj, JsValue[] arguments) + private JsValue SetUint32(JsValue thisObject, JsValue[] arguments) { - return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint32, arguments.At(1)); + return SetViewValue(thisObject, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint32, arguments.At(1)); } /// diff --git a/Jint/Native/Date/DateConstructor.cs b/Jint/Native/Date/DateConstructor.cs index f900c7b3d8..144162d420 100644 --- a/Jint/Native/Date/DateConstructor.cs +++ b/Jint/Native/Date/DateConstructor.cs @@ -49,7 +49,7 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-date.parse /// - private JsValue Parse(JsValue thisObj, JsValue[] arguments) + private JsValue Parse(JsValue thisObject, JsValue[] arguments) { var dateString = TypeConverter.ToString(arguments.At(0)); var date = ParseFromString(dateString); @@ -73,7 +73,7 @@ private DatePresentation ParseFromString(string date) /// /// https://tc39.es/ecma262/#sec-date.utc /// - private static JsValue Utc(JsValue thisObj, JsValue[] arguments) + private static JsValue Utc(JsValue thisObject, JsValue[] arguments) { var y = TypeConverter.ToNumber(arguments.At(0)); var m = TypeConverter.ToNumber(arguments.At(1, JsNumber.PositiveZero)); @@ -96,7 +96,7 @@ private static JsValue Utc(JsValue thisObj, JsValue[] arguments) return finalDate.TimeClip().ToJsValue(); } - private static JsValue Now(JsValue thisObj, JsValue[] arguments) + private static JsValue Now(JsValue thisObject, JsValue[] arguments) { return (long) (DateTime.UtcNow - Epoch).TotalMilliseconds; } diff --git a/Jint/Native/Date/DatePrototype.cs b/Jint/Native/Date/DatePrototype.cs index a557f66faf..16796707d9 100644 --- a/Jint/Native/Date/DatePrototype.cs +++ b/Jint/Native/Date/DatePrototype.cs @@ -131,17 +131,17 @@ private JsValue ToPrimitive(JsValue thisObject, JsValue[] arguments) return TypeConverter.OrdinaryToPrimitive(oi, tryFirst); } - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) { - return ThisTimeValue(thisObj).ToJsValue(); + return ThisTimeValue(thisObject).ToJsValue(); } /// /// https://tc39.es/ecma262/#thistimevalue /// - private DatePresentation ThisTimeValue(JsValue thisObj) + private DatePresentation ThisTimeValue(JsValue thisObject) { - if (thisObj is JsDate dateInstance) + if (thisObject is JsDate dateInstance) { return dateInstance._dateValue; } @@ -153,18 +153,18 @@ private DatePresentation ThisTimeValue(JsValue thisObj) /// /// https://tc39.es/ecma262/#sec-date.prototype.tostring /// - internal JsValue ToString(JsValue thisObj, JsValue[] arg2) + internal JsValue ToString(JsValue thisObject, JsValue[] arg2) { - var tv = ThisTimeValue(thisObj); + var tv = ThisTimeValue(thisObject); return ToDateString(tv); } /// /// https://tc39.es/ecma262/#sec-date.prototype.todatestring /// - private JsValue ToDateString(JsValue thisObj, JsValue[] arguments) + private JsValue ToDateString(JsValue thisObject, JsValue[] arguments) { - var tv = ThisTimeValue(thisObj); + var tv = ThisTimeValue(thisObject); if (tv.IsNaN) { @@ -192,9 +192,9 @@ private JsValue ToDateString(DatePresentation tv) /// /// https://tc39.es/ecma262/#sec-date.prototype.totimestring /// - private JsValue ToTimeString(JsValue thisObj, JsValue[] arguments) + private JsValue ToTimeString(JsValue thisObject, JsValue[] arguments) { - var tv = ThisTimeValue(thisObj); + var tv = ThisTimeValue(thisObject); if (tv.IsNaN) { @@ -209,9 +209,9 @@ private JsValue ToTimeString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.tolocalestring /// - private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments) { - var dateInstance = ThisTimeValue(thisObj); + var dateInstance = ThisTimeValue(thisObject); if (dateInstance.IsNaN) { @@ -224,9 +224,9 @@ private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.tolocaledatestring /// - private JsValue ToLocaleDateString(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleDateString(JsValue thisObject, JsValue[] arguments) { - var dateInstance = ThisTimeValue(thisObj); + var dateInstance = ThisTimeValue(thisObject); if (dateInstance.IsNaN) { @@ -239,9 +239,9 @@ private JsValue ToLocaleDateString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.tolocaletimestring /// - private JsValue ToLocaleTimeString(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleTimeString(JsValue thisObject, JsValue[] arguments) { - var dateInstance = ThisTimeValue(thisObj); + var dateInstance = ThisTimeValue(thisObject); if (dateInstance.IsNaN) { @@ -251,9 +251,9 @@ private JsValue ToLocaleTimeString(JsValue thisObj, JsValue[] arguments) return ToLocalTime(dateInstance).ToString("T", Engine.Options.Culture); } - private JsValue GetTime(JsValue thisObj, JsValue[] arguments) + private JsValue GetTime(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -261,9 +261,9 @@ private JsValue GetTime(JsValue thisObj, JsValue[] arguments) return t.ToJsValue(); } - private JsValue GetFullYear(JsValue thisObj, JsValue[] arguments) + private JsValue GetFullYear(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -271,9 +271,9 @@ private JsValue GetFullYear(JsValue thisObj, JsValue[] arguments) return YearFromTime(LocalTime(t)); } - private JsValue GetYear(JsValue thisObj, JsValue[] arguments) + private JsValue GetYear(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -281,9 +281,9 @@ private JsValue GetYear(JsValue thisObj, JsValue[] arguments) return YearFromTime(LocalTime(t)) - 1900; } - private JsValue GetUTCFullYear(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCFullYear(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -291,9 +291,9 @@ private JsValue GetUTCFullYear(JsValue thisObj, JsValue[] arguments) return YearFromTime(t); } - private JsValue GetMonth(JsValue thisObj, JsValue[] arguments) + private JsValue GetMonth(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -304,9 +304,9 @@ private JsValue GetMonth(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.getutcmonth /// - private JsValue GetUTCMonth(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCMonth(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -317,9 +317,9 @@ private JsValue GetUTCMonth(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.getdate /// - private JsValue GetDate(JsValue thisObj, JsValue[] arguments) + private JsValue GetDate(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -327,9 +327,9 @@ private JsValue GetDate(JsValue thisObj, JsValue[] arguments) return DateFromTime(LocalTime(t)); } - private JsValue GetUTCDate(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCDate(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -337,9 +337,9 @@ private JsValue GetUTCDate(JsValue thisObj, JsValue[] arguments) return DateFromTime(t); } - private JsValue GetDay(JsValue thisObj, JsValue[] arguments) + private JsValue GetDay(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -347,9 +347,9 @@ private JsValue GetDay(JsValue thisObj, JsValue[] arguments) return WeekDay(LocalTime(t)); } - private JsValue GetUTCDay(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCDay(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -357,9 +357,9 @@ private JsValue GetUTCDay(JsValue thisObj, JsValue[] arguments) return WeekDay(t); } - private JsValue GetHours(JsValue thisObj, JsValue[] arguments) + private JsValue GetHours(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -367,9 +367,9 @@ private JsValue GetHours(JsValue thisObj, JsValue[] arguments) return HourFromTime(LocalTime(t)); } - private JsValue GetUTCHours(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCHours(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -377,9 +377,9 @@ private JsValue GetUTCHours(JsValue thisObj, JsValue[] arguments) return HourFromTime(t); } - private JsValue GetMinutes(JsValue thisObj, JsValue[] arguments) + private JsValue GetMinutes(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -387,9 +387,9 @@ private JsValue GetMinutes(JsValue thisObj, JsValue[] arguments) return MinFromTime(LocalTime(t)); } - private JsValue GetUTCMinutes(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCMinutes(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -397,9 +397,9 @@ private JsValue GetUTCMinutes(JsValue thisObj, JsValue[] arguments) return MinFromTime(t); } - private JsValue GetSeconds(JsValue thisObj, JsValue[] arguments) + private JsValue GetSeconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -407,9 +407,9 @@ private JsValue GetSeconds(JsValue thisObj, JsValue[] arguments) return SecFromTime(LocalTime(t)); } - private JsValue GetUTCSeconds(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCSeconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -417,9 +417,9 @@ private JsValue GetUTCSeconds(JsValue thisObj, JsValue[] arguments) return SecFromTime(t); } - private JsValue GetMilliseconds(JsValue thisObj, JsValue[] arguments) + private JsValue GetMilliseconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -427,9 +427,9 @@ private JsValue GetMilliseconds(JsValue thisObj, JsValue[] arguments) return MsFromTime(LocalTime(t)); } - private JsValue GetUTCMilliseconds(JsValue thisObj, JsValue[] arguments) + private JsValue GetUTCMilliseconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -437,9 +437,9 @@ private JsValue GetUTCMilliseconds(JsValue thisObj, JsValue[] arguments) return MsFromTime(t); } - private JsValue GetTimezoneOffset(JsValue thisObj, JsValue[] arguments) + private JsValue GetTimezoneOffset(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); if (t.IsNaN) { return JsNumber.DoubleNaN; @@ -450,22 +450,22 @@ private JsValue GetTimezoneOffset(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.settime /// - private JsValue SetTime(JsValue thisObj, JsValue[] arguments) + private JsValue SetTime(JsValue thisObject, JsValue[] arguments) { - ThisTimeValue(thisObj); + ThisTimeValue(thisObject); var t = TypeConverter.ToNumber(arguments.At(0)); var v = t.TimeClip(); - ((JsDate) thisObj)._dateValue = t; + ((JsDate) thisObject)._dateValue = t; return v.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setmilliseconds /// - private JsValue SetMilliseconds(JsValue thisObj, JsValue[] arguments) + private JsValue SetMilliseconds(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var ms = TypeConverter.ToNumber(arguments.At(0)); if (t.IsNaN) @@ -475,16 +475,16 @@ private JsValue SetMilliseconds(JsValue thisObj, JsValue[] arguments) var time = MakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), ms); var u = Utc(MakeDate(Day(t), time)).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcmilliseconds /// - private JsValue SetUTCMilliseconds(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCMilliseconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var milli = TypeConverter.ToNumber(arguments.At(0)); if (t.IsNaN) @@ -494,16 +494,16 @@ private JsValue SetUTCMilliseconds(JsValue thisObj, JsValue[] arguments) var time = MakeTime(HourFromTime(t), MinFromTime(t), SecFromTime(t), milli); var u = MakeDate(Day(t), time).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setseconds /// - private JsValue SetSeconds(JsValue thisObj, JsValue[] arguments) + private JsValue SetSeconds(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var s = TypeConverter.ToNumber(arguments.At(0)); var milli = arguments.Length <= 1 ? MsFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); @@ -514,16 +514,16 @@ private JsValue SetSeconds(JsValue thisObj, JsValue[] arguments) var date = MakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli)); var u = Utc(date).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcseconds /// - private JsValue SetUTCSeconds(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCSeconds(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var s = TypeConverter.ToNumber(arguments.At(0)); var milli = arguments.Length <= 1 ? MsFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); @@ -534,16 +534,16 @@ private JsValue SetUTCSeconds(JsValue thisObj, JsValue[] arguments) var date = MakeDate(Day(t), MakeTime(HourFromTime(t), MinFromTime(t), s, milli)); var u = date.TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setminutes /// - private JsValue SetMinutes(JsValue thisObj, JsValue[] arguments) + private JsValue SetMinutes(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var m = TypeConverter.ToNumber(arguments.At(0)); var s = arguments.Length <= 1 ? SecFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); var milli = arguments.Length <= 2 ? MsFromTime(t) : TypeConverter.ToNumber(arguments.At(2)); @@ -555,16 +555,16 @@ private JsValue SetMinutes(JsValue thisObj, JsValue[] arguments) var date = MakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli)); var u = Utc(date).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcminutes /// - private JsValue SetUTCMinutes(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCMinutes(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var m = TypeConverter.ToNumber(arguments.At(0)); var s = arguments.Length <= 1 ? SecFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); var milli = arguments.Length <= 2 ? MsFromTime(t) : TypeConverter.ToNumber(arguments.At(2)); @@ -576,16 +576,16 @@ private JsValue SetUTCMinutes(JsValue thisObj, JsValue[] arguments) var date = MakeDate(Day(t), MakeTime(HourFromTime(t), m, s, milli)); var u = date.TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.sethours /// - private JsValue SetHours(JsValue thisObj, JsValue[] arguments) + private JsValue SetHours(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var h = TypeConverter.ToNumber(arguments.At(0)); var m = arguments.Length <= 1 ? MinFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); var s = arguments.Length <= 2 ? SecFromTime(t) : TypeConverter.ToNumber(arguments.At(2)); @@ -598,16 +598,16 @@ private JsValue SetHours(JsValue thisObj, JsValue[] arguments) var date = MakeDate(Day(t), MakeTime(h, m, s, milli)); var u = Utc(date).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutchours /// - private JsValue SetUTCHours(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCHours(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var h = TypeConverter.ToNumber(arguments.At(0)); var m = arguments.Length <= 1 ? MinFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); var s = arguments.Length <= 2 ? SecFromTime(t) : TypeConverter.ToNumber(arguments.At(2)); @@ -620,16 +620,16 @@ private JsValue SetUTCHours(JsValue thisObj, JsValue[] arguments) var newDate = MakeDate(Day(t), MakeTime(h, m, s, milli)); var v = newDate.TimeClip(); - ((JsDate) thisObj)._dateValue = v; + ((JsDate) thisObject)._dateValue = v; return v.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setdate /// - private JsValue SetDate(JsValue thisObj, JsValue[] arguments) + private JsValue SetDate(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var dt = TypeConverter.ToNumber(arguments.At(0)); if (t.IsNaN) @@ -640,16 +640,16 @@ private JsValue SetDate(JsValue thisObj, JsValue[] arguments) var (year, month, __) = YearMonthDayFromTime(t); var newDate = MakeDate(MakeDay(year, month, dt), TimeWithinDay(t)); var u = Utc(newDate).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcdate /// - private JsValue SetUTCDate(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCDate(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var dt = TypeConverter.ToNumber(arguments.At(0)); if (t.IsNaN) @@ -659,16 +659,16 @@ private JsValue SetUTCDate(JsValue thisObj, JsValue[] arguments) var newDate = MakeDate(MakeDay(YearFromTime(t), MonthFromTime(t), dt), TimeWithinDay(t)); var u = newDate.TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setmonth /// - private JsValue SetMonth(JsValue thisObj, JsValue[] arguments) + private JsValue SetMonth(JsValue thisObject, JsValue[] arguments) { - var t = LocalTime(ThisTimeValue(thisObj)); + var t = LocalTime(ThisTimeValue(thisObject)); var m = TypeConverter.ToNumber(arguments.At(0)); var dt = arguments.Length <= 1 ? DateFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); @@ -679,16 +679,16 @@ private JsValue SetMonth(JsValue thisObj, JsValue[] arguments) var newDate = MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)); var u = Utc(newDate).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcmonth /// - private JsValue SetUTCMonth(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCMonth(JsValue thisObject, JsValue[] arguments) { - var t = ThisTimeValue(thisObj); + var t = ThisTimeValue(thisObject); var m = TypeConverter.ToNumber(arguments.At(0)); var dt = arguments.Length <= 1 ? DateFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); @@ -699,16 +699,16 @@ private JsValue SetUTCMonth(JsValue thisObj, JsValue[] arguments) var newDate = MakeDate(MakeDay(YearFromTime(t), m, dt), TimeWithinDay(t)); var u = newDate.TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setfullyear /// - private JsValue SetFullYear(JsValue thisObj, JsValue[] arguments) + private JsValue SetFullYear(JsValue thisObject, JsValue[] arguments) { - var thisTime = ThisTimeValue(thisObj); + var thisTime = ThisTimeValue(thisObject); var t = thisTime.IsNaN ? 0 : LocalTime(thisTime); var y = TypeConverter.ToNumber(arguments.At(0)); var m = arguments.Length <= 1 ? MonthFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); @@ -716,21 +716,21 @@ private JsValue SetFullYear(JsValue thisObj, JsValue[] arguments) var newDate = MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)); var u = Utc(newDate).TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setyear /// - private JsValue SetYear(JsValue thisObj, JsValue[] arguments) + private JsValue SetYear(JsValue thisObject, JsValue[] arguments) { - var thisTime = ThisTimeValue(thisObj); + var thisTime = ThisTimeValue(thisObject); var t = thisTime.IsNaN ? 0 : LocalTime(thisTime); var y = TypeConverter.ToNumber(arguments.At(0)); if (double.IsNaN(y)) { - ((JsDate) thisObj)._dateValue = double.NaN; + ((JsDate) thisObject)._dateValue = double.NaN; return JsNumber.DoubleNaN; } @@ -742,32 +742,32 @@ private JsValue SetYear(JsValue thisObj, JsValue[] arguments) var newDate = MakeDay(fy, MonthFromTime(t), DateFromTime(t)); var u = Utc(MakeDate(newDate, TimeWithinDay(t))); - ((JsDate) thisObj)._dateValue = u.TimeClip(); + ((JsDate) thisObject)._dateValue = u.TimeClip(); return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.setutcfullyear /// - private JsValue SetUTCFullYear(JsValue thisObj, JsValue[] arguments) + private JsValue SetUTCFullYear(JsValue thisObject, JsValue[] arguments) { - var thisTime = ThisTimeValue(thisObj); + var thisTime = ThisTimeValue(thisObject); var t = thisTime.IsNaN ? 0 : thisTime; var y = TypeConverter.ToNumber(arguments.At(0)); var m = arguments.Length <= 1 ? MonthFromTime(t) : TypeConverter.ToNumber(arguments.At(1)); var dt = arguments.Length <= 2 ? DateFromTime(t) : TypeConverter.ToNumber(arguments.At(2)); var newDate = MakeDate(MakeDay(y, m, dt), TimeWithinDay(t)); var u = newDate.TimeClip(); - ((JsDate) thisObj)._dateValue = u; + ((JsDate) thisObject)._dateValue = u; return u.ToJsValue(); } /// /// https://tc39.es/ecma262/#sec-date.prototype.toutcstring /// - private JsValue ToUtcString(JsValue thisObj, JsValue[] arguments) + private JsValue ToUtcString(JsValue thisObject, JsValue[] arguments) { - var tv = ThisTimeValue(thisObj); + var tv = ThisTimeValue(thisObject); if (!IsFinite(tv)) { return "Invalid Date"; @@ -785,16 +785,16 @@ private JsValue ToUtcString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-date.prototype.toisostring /// - private JsValue ToISOString(JsValue thisObj, JsValue[] arguments) + private JsValue ToISOString(JsValue thisObject, JsValue[] arguments) { - var thisTime = ThisTimeValue(thisObj); + var thisTime = ThisTimeValue(thisObject); var t = thisTime; if (t.IsNaN) { ExceptionHelper.ThrowRangeError(_realm); } - if (((JsDate) thisObj).DateTimeRangeValid) + if (((JsDate) thisObject).DateTimeRangeValid) { // shortcut var dt = thisTime.ToDateTime(); @@ -822,9 +822,9 @@ private JsValue ToISOString(JsValue thisObj, JsValue[] arguments) return formatted; } - private JsValue ToJson(JsValue thisObj, JsValue[] arguments) + private JsValue ToJson(JsValue thisObject, JsValue[] arguments) { - var o = TypeConverter.ToObject(_realm, thisObj); + var o = TypeConverter.ToObject(_realm, thisObject); var tv = TypeConverter.ToPrimitive(o, Types.Number); if (tv.IsNumber() && !IsFinite(((JsNumber) tv)._value)) { diff --git a/Jint/Native/FinalizationRegistry/FinalizationRegistryPrototype.cs b/Jint/Native/FinalizationRegistry/FinalizationRegistryPrototype.cs index bf9918220a..0f39c5e6dd 100644 --- a/Jint/Native/FinalizationRegistry/FinalizationRegistryPrototype.cs +++ b/Jint/Native/FinalizationRegistry/FinalizationRegistryPrototype.cs @@ -29,10 +29,7 @@ protected override void Initialize() const PropertyFlag PropertyFlags = PropertyFlag.NonEnumerable; var properties = new PropertyDictionary(4, checkExistingKeys: false) { - [KnownKeys.Constructor] = new(_constructor, PropertyFlag.NonEnumerable), - ["register"] = new(new ClrFunctionInstance(Engine, "register", Register, 2, PropertyFlag.Configurable), PropertyFlags), - ["unregister"] = new(new ClrFunctionInstance(Engine, "unregister", Unregister, 1, PropertyFlag.Configurable), PropertyFlags), - ["cleanupSome"] = new(new ClrFunctionInstance(Engine, "cleanupSome", CleanupSome, 0, PropertyFlag.Configurable), PropertyFlags), + [KnownKeys.Constructor] = new(_constructor, PropertyFlag.NonEnumerable), ["register"] = new(new ClrFunctionInstance(Engine, "register", Register, 2, PropertyFlag.Configurable), PropertyFlags), ["unregister"] = new(new ClrFunctionInstance(Engine, "unregister", Unregister, 1, PropertyFlag.Configurable), PropertyFlags), ["cleanupSome"] = new(new ClrFunctionInstance(Engine, "cleanupSome", CleanupSome, 0, PropertyFlag.Configurable), PropertyFlags), }; SetProperties(properties); @@ -43,9 +40,9 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-finalization-registry.prototype.register /// - private JsValue Register(JsValue thisObj, JsValue[] arguments) + private JsValue Register(JsValue thisObject, JsValue[] arguments) { - var finalizationRegistry = AssertFinalizationRegistryInstance(thisObj); + var finalizationRegistry = AssertFinalizationRegistryInstance(thisObject); var target = arguments.At(0); var heldValue = arguments.At(1); @@ -67,8 +64,8 @@ private JsValue Register(JsValue thisObj, JsValue[] arguments) { ExceptionHelper.ThrowTypeError(_realm, unregisterToken + " must be an object"); } - } + var cell = new Cell(target, heldValue, unregisterToken); finalizationRegistry.AddCell(cell); return Undefined; @@ -77,9 +74,9 @@ private JsValue Register(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-finalization-registry.prototype.unregister /// - private JsValue Unregister(JsValue thisObj, JsValue[] arguments) + private JsValue Unregister(JsValue thisObject, JsValue[] arguments) { - var finalizationRegistry = AssertFinalizationRegistryInstance(thisObj); + var finalizationRegistry = AssertFinalizationRegistryInstance(thisObject); var unregisterToken = arguments.At(0); @@ -91,9 +88,9 @@ private JsValue Unregister(JsValue thisObj, JsValue[] arguments) return finalizationRegistry.Remove(unregisterToken); } - private JsValue CleanupSome(JsValue thisObj, JsValue[] arguments) + private JsValue CleanupSome(JsValue thisObject, JsValue[] arguments) { - var finalizationRegistry = AssertFinalizationRegistryInstance(thisObj); + var finalizationRegistry = AssertFinalizationRegistryInstance(thisObject); var callback = arguments.At(0); if (!callback.IsUndefined() && callback is not ICallable) @@ -106,15 +103,14 @@ private JsValue CleanupSome(JsValue thisObj, JsValue[] arguments) return Undefined; } - private FinalizationRegistryInstance AssertFinalizationRegistryInstance(JsValue thisObj) + private FinalizationRegistryInstance AssertFinalizationRegistryInstance(JsValue thisObject) { - if (thisObj is not FinalizationRegistryInstance finalizationRegistryInstance) + if (thisObject is FinalizationRegistryInstance finalizationRegistryInstance) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a FinalizationRegistry"); - return null; + return finalizationRegistryInstance; } - return finalizationRegistryInstance; + ExceptionHelper.ThrowTypeError(_realm, "object must be a FinalizationRegistry"); + return default; } } - diff --git a/Jint/Native/Function/FunctionInstance.Dynamic.cs b/Jint/Native/Function/FunctionInstance.Dynamic.cs index 162428b981..b3537b833c 100644 --- a/Jint/Native/Function/FunctionInstance.Dynamic.cs +++ b/Jint/Native/Function/FunctionInstance.Dynamic.cs @@ -18,7 +18,7 @@ internal FunctionInstance CreateDynamicFunction( ObjectInstance constructor, JsValue newTarget, FunctionKind kind, - JsValue[] args) + JsValue[] arguments) { // TODO var callerContext = _engine.GetExecutionContext(1); var callerContext = _engine.ExecutionContext; @@ -48,25 +48,25 @@ internal FunctionInstance CreateDynamicFunction( break; } - var argCount = args.Length; + var argCount = arguments.Length; var p = ""; var body = ""; if (argCount == 1) { - body = TypeConverter.ToString(args[0]); + body = TypeConverter.ToString(arguments[0]); } else if (argCount > 1) { - var firstArg = args[0]; + var firstArg = arguments[0]; p = TypeConverter.ToString(firstArg); for (var k = 1; k < argCount - 1; k++) { - var nextArg = args[k]; + var nextArg = arguments[k]; p += "," + TypeConverter.ToString(nextArg); } - body = TypeConverter.ToString(args[argCount - 1]); + body = TypeConverter.ToString(arguments[argCount - 1]); } IFunction? function = null; diff --git a/Jint/Native/Function/FunctionPrototype.cs b/Jint/Native/Function/FunctionPrototype.cs index 193f93fd8d..7ea20ac7e5 100644 --- a/Jint/Native/Function/FunctionPrototype.cs +++ b/Jint/Native/Function/FunctionPrototype.cs @@ -49,17 +49,17 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-function.prototype-@@hasinstance /// - private static JsValue HasInstance(JsValue thisObj, JsValue[] arguments) + private static JsValue HasInstance(JsValue thisObject, JsValue[] arguments) { - return thisObj.OrdinaryHasInstance(arguments.At(0)); + return thisObject.OrdinaryHasInstance(arguments.At(0)); } /// /// https://tc39.es/ecma262/#sec-function.prototype.bind /// - private JsValue Bind(JsValue thisObj, JsValue[] arguments) + private JsValue Bind(JsValue thisObject, JsValue[] arguments) { - if (thisObj is not (ICallable and ObjectInstance oi)) + if (thisObject is not (ICallable and ObjectInstance oi)) { ExceptionHelper.ThrowTypeError(_realm, "Bind must be called on a function"); return default; @@ -127,11 +127,11 @@ private BindFunctionInstance BoundFunctionCreate(ObjectInstance targetFunction, /// /// https://tc39.es/ecma262/#sec-function.prototype.tostring /// - private JsValue ToString(JsValue thisObj, JsValue[] arguments) + private JsValue ToString(JsValue thisObject, JsValue[] arguments) { - if (thisObj.IsObject() && thisObj.IsCallable) + if (thisObject.IsObject() && thisObject.IsCallable) { - return thisObj.ToString(); + return thisObject.ToString(); } ExceptionHelper.ThrowTypeError(_realm, "Function.prototype.toString requires that 'this' be a Function"); diff --git a/Jint/Native/Global/GlobalObject.cs b/Jint/Native/Global/GlobalObject.cs index dc8ae33c1f..5390fc0e05 100644 --- a/Jint/Native/Global/GlobalObject.cs +++ b/Jint/Native/Global/GlobalObject.cs @@ -132,9 +132,9 @@ protected override void Initialize() SetProperties(properties); } - private JsValue ToStringString(JsValue thisObj, JsValue[] arguments) + private JsValue ToStringString(JsValue thisObject, JsValue[] arguments) { - return _realm.Intrinsics.Object.PrototypeObject.ToObjectString(thisObj, Arguments.Empty); + return _realm.Intrinsics.Object.PrototypeObject.ToObjectString(thisObject, Arguments.Empty); } /// diff --git a/Jint/Native/GroupByHelper.cs b/Jint/Native/GroupByHelper.cs index 252e82132b..78289b388a 100644 --- a/Jint/Native/GroupByHelper.cs +++ b/Jint/Native/GroupByHelper.cs @@ -42,7 +42,7 @@ public GroupByProtocol( _mapMode = mapMode; } - protected override void ProcessItem(JsValue[] args, JsValue currentValue) + protected override void ProcessItem(JsValue[] arguments, JsValue currentValue) { if (_k >= ArrayOperations.MaxArrayLength) { diff --git a/Jint/Native/Iterator/IteratorProtocol.cs b/Jint/Native/Iterator/IteratorProtocol.cs index 0848cdf846..73218d2675 100644 --- a/Jint/Native/Iterator/IteratorProtocol.cs +++ b/Jint/Native/Iterator/IteratorProtocol.cs @@ -66,7 +66,7 @@ protected virtual void IterationEnd() { } - protected abstract void ProcessItem(JsValue[] args, JsValue currentValue); + protected abstract void ProcessItem(JsValue[] arguments, JsValue currentValue); internal static void AddEntriesFromIterable(ObjectInstance target, IteratorInstance iterable, object adder) { diff --git a/Jint/Native/Iterator/IteratorPrototype.cs b/Jint/Native/Iterator/IteratorPrototype.cs index de1b23959e..4a98e177eb 100644 --- a/Jint/Native/Iterator/IteratorPrototype.cs +++ b/Jint/Native/Iterator/IteratorPrototype.cs @@ -28,14 +28,14 @@ protected override void Initialize() SetSymbols(symbols); } - private static JsValue ToIterator(JsValue thisObj, JsValue[] arguments) + private static JsValue ToIterator(JsValue thisObject, JsValue[] arguments) { - return thisObj; + return thisObject; } - internal JsValue Next(JsValue thisObj, JsValue[] arguments) + internal JsValue Next(JsValue thisObject, JsValue[] arguments) { - var iterator = thisObj as IteratorInstance; + var iterator = thisObject as IteratorInstance; if (iterator is null) { ExceptionHelper.ThrowTypeError(_engine.Realm); diff --git a/Jint/Native/Map/MapPrototype.cs b/Jint/Native/Map/MapPrototype.cs index b06cb317c2..f0726243cd 100644 --- a/Jint/Native/Map/MapPrototype.cs +++ b/Jint/Native/Map/MapPrototype.cs @@ -52,51 +52,51 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Size(JsValue thisObj, JsValue[] arguments) + private JsValue Size(JsValue thisObject, JsValue[] arguments) { - AssertMapInstance(thisObj); + AssertMapInstance(thisObject); return JsNumber.Create(0); } - private JsValue Get(JsValue thisObj, JsValue[] arguments) + private JsValue Get(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.MapGet(arguments.At(0)); } - private JsValue Clear(JsValue thisObj, JsValue[] arguments) + private JsValue Clear(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); map.Clear(); return Undefined; } - private JsValue Delete(JsValue thisObj, JsValue[] arguments) + private JsValue Delete(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.MapDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue Set(JsValue thisObj, JsValue[] arguments) + private JsValue Set(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); map.MapSet(arguments.At(0), arguments.At(1)); - return thisObj; + return thisObject; } - private JsValue Has(JsValue thisObj, JsValue[] arguments) + private JsValue Has(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.Has(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue ForEach(JsValue thisObj, JsValue[] arguments) + private JsValue ForEach(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); var callbackfn = arguments.At(0); var thisArg = arguments.At(1); @@ -107,32 +107,32 @@ private JsValue ForEach(JsValue thisObj, JsValue[] arguments) return Undefined; } - private ObjectInstance Entries(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Entries(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.Iterator(); } - private ObjectInstance Keys(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Keys(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.Keys(); } - private ObjectInstance Values(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Values(JsValue thisObject, JsValue[] arguments) { - var map = AssertMapInstance(thisObj); + var map = AssertMapInstance(thisObject); return map.Values(); } - private MapInstance AssertMapInstance(JsValue thisObj) + private MapInstance AssertMapInstance(JsValue thisObject) { - var map = thisObj as MapInstance; - if (map is null) + if (thisObject is MapInstance map) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a Map"); + return map; } - return map; + ExceptionHelper.ThrowTypeError(_realm, "object must be a Map"); + return default; } } diff --git a/Jint/Native/Number/NumberConstructor.cs b/Jint/Native/Number/NumberConstructor.cs index c50524493b..69da694f85 100644 --- a/Jint/Native/Number/NumberConstructor.cs +++ b/Jint/Native/Number/NumberConstructor.cs @@ -53,7 +53,7 @@ protected override void Initialize() SetProperties(properties); } - private static JsValue IsFinite(JsValue thisObj, JsValue[] arguments) + private static JsValue IsFinite(JsValue thisObject, JsValue[] arguments) { if (!(arguments.At(0) is JsNumber num)) { @@ -63,7 +63,7 @@ private static JsValue IsFinite(JsValue thisObj, JsValue[] arguments) return double.IsInfinity(num._value) || double.IsNaN(num._value) ? JsBoolean.False : JsBoolean.True; } - private static JsValue IsInteger(JsValue thisObj, JsValue[] arguments) + private static JsValue IsInteger(JsValue thisObject, JsValue[] arguments) { if (!(arguments.At(0) is JsNumber num)) { @@ -80,7 +80,7 @@ private static JsValue IsInteger(JsValue thisObj, JsValue[] arguments) return integer == num._value; } - private static JsValue IsNaN(JsValue thisObj, JsValue[] arguments) + private static JsValue IsNaN(JsValue thisObject, JsValue[] arguments) { if (!(arguments.At(0) is JsNumber num)) { @@ -90,7 +90,7 @@ private static JsValue IsNaN(JsValue thisObj, JsValue[] arguments) return double.IsNaN(num._value); } - private static JsValue IsSafeInteger(JsValue thisObj, JsValue[] arguments) + private static JsValue IsSafeInteger(JsValue thisObject, JsValue[] arguments) { if (!(arguments.At(0) is JsNumber num)) { diff --git a/Jint/Native/Number/NumberPrototype.cs b/Jint/Native/Number/NumberPrototype.cs index 00d9eb4d2d..af302d7e5a 100644 --- a/Jint/Native/Number/NumberPrototype.cs +++ b/Jint/Native/Number/NumberPrototype.cs @@ -83,16 +83,16 @@ private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments) return m.ToString("n", Engine.Options.Culture); } - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) { - if (thisObj is NumberInstance ni) + if (thisObject is NumberInstance ni) { return ni.NumberData; } - if (thisObj is JsNumber) + if (thisObject is JsNumber) { - return thisObj; + return thisObject; } ExceptionHelper.ThrowTypeError(_realm); @@ -101,7 +101,7 @@ private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) private const double Ten21 = 1e21; - private JsValue ToFixed(JsValue thisObj, JsValue[] arguments) + private JsValue ToFixed(JsValue thisObject, JsValue[] arguments) { var f = (int) TypeConverter.ToInteger(arguments.At(0, 0)); if (f < 0 || f > 100) @@ -115,7 +115,7 @@ private JsValue ToFixed(JsValue thisObj, JsValue[] arguments) ExceptionHelper.ThrowRangeError(_realm, "100 fraction digits is not supported due to .NET format specifier limitation"); } - var x = TypeConverter.ToNumber(thisObj); + var x = TypeConverter.ToNumber(thisObject); if (double.IsNaN(x)) { @@ -139,14 +139,14 @@ private JsValue ToFixed(JsValue thisObj, JsValue[] arguments) /// /// https://www.ecma-international.org/ecma-262/6.0/#sec-number.prototype.toexponential /// - private JsValue ToExponential(JsValue thisObj, JsValue[] arguments) + private JsValue ToExponential(JsValue thisObject, JsValue[] arguments) { - if (!thisObj.IsNumber() && ReferenceEquals(thisObj.TryCast(), null)) + if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast(), null)) { ExceptionHelper.ThrowTypeError(_realm); } - var x = TypeConverter.ToNumber(thisObj); + var x = TypeConverter.ToNumber(thisObject); var fractionDigits = arguments.At(0); if (fractionDigits.IsUndefined()) { @@ -162,7 +162,7 @@ private JsValue ToExponential(JsValue thisObj, JsValue[] arguments) if (double.IsInfinity(x)) { - return thisObj.ToString(); + return thisObject.ToString(); } if (f < 0 || f > 100) @@ -216,14 +216,14 @@ private JsValue ToExponential(JsValue thisObj, JsValue[] arguments) return result; } - private JsValue ToPrecision(JsValue thisObj, JsValue[] arguments) + private JsValue ToPrecision(JsValue thisObject, JsValue[] arguments) { - if (!thisObj.IsNumber() && ReferenceEquals(thisObj.TryCast(), null)) + if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast(), null)) { ExceptionHelper.ThrowTypeError(_realm); } - var x = TypeConverter.ToNumber(thisObj); + var x = TypeConverter.ToNumber(thisObject); var precisionArgument = arguments.At(0); if (precisionArgument.IsUndefined()) @@ -240,7 +240,7 @@ private JsValue ToPrecision(JsValue thisObj, JsValue[] arguments) if (double.IsInfinity(x)) { - return thisObj.ToString(); + return thisObject.ToString(); } if (p < 1 || p > 100) diff --git a/Jint/Native/Promise/PromiseConstructor.cs b/Jint/Native/Promise/PromiseConstructor.cs index d88c71d40d..bd1c1259cb 100644 --- a/Jint/Native/Promise/PromiseConstructor.cs +++ b/Jint/Native/Promise/PromiseConstructor.cs @@ -97,37 +97,37 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) /// /// https://tc39.es/ecma262/#sec-promise.resolve /// - internal JsValue Resolve(JsValue thisObj, JsValue[] arguments) + internal JsValue Resolve(JsValue thisObject, JsValue[] arguments) { - if (!thisObj.IsObject()) + if (!thisObject.IsObject()) { ExceptionHelper.ThrowTypeError(_realm, "PromiseResolve called on non-object"); } - if (thisObj is not IConstructor) + if (thisObject is not IConstructor) { ExceptionHelper.ThrowTypeError(_realm, "Promise.resolve invoked on a non-constructor value"); } var x = arguments.At(0); - return PromiseResolve(thisObj, x); + return PromiseResolve(thisObject, x); } /// /// https://tc39.es/ecma262/#sec-promise-resolve /// - private JsValue PromiseResolve(JsValue thisObj, JsValue x) + private JsValue PromiseResolve(JsValue thisObject, JsValue x) { if (x.IsPromise()) { var xConstructor = x.Get(CommonProperties.Constructor); - if (SameValue(xConstructor, thisObj)) + if (SameValue(xConstructor, thisObject)) { return x; } } - var (instance, resolve, _, _, _) = NewPromiseCapability(_engine, thisObj); + var (instance, resolve, _, _, _) = NewPromiseCapability(_engine, thisObject); resolve.Call(Undefined, new[] { x }); @@ -137,21 +137,21 @@ private JsValue PromiseResolve(JsValue thisObj, JsValue x) /// /// https://tc39.es/ecma262/#sec-promise.reject /// - private JsValue Reject(JsValue thisObj, JsValue[] arguments) + private JsValue Reject(JsValue thisObject, JsValue[] arguments) { - if (!thisObj.IsObject()) + if (!thisObject.IsObject()) { ExceptionHelper.ThrowTypeError(_realm, "Promise.reject called on non-object"); } - if (thisObj is not IConstructor) + if (thisObject is not IConstructor) { ExceptionHelper.ThrowTypeError(_realm, "Promise.reject invoked on a non-constructor value"); } var r = arguments.At(0); - var (instance, _, reject, _, _) = NewPromiseCapability(_engine, thisObj); + var (instance, _, reject, _, _) = NewPromiseCapability(_engine, thisObject); reject.Call(Undefined, new[] { r }); @@ -161,22 +161,22 @@ private JsValue Reject(JsValue thisObj, JsValue[] arguments) // This helper methods executes the first 6 steps in the specs belonging to static Promise methods like all, any etc. // If it returns false, that means it has an error and it is already rejected // If it returns true, the logic specific to the calling function should continue executing - private bool TryGetPromiseCapabilityAndIterator(JsValue thisObj, JsValue[] arguments, string callerName, out PromiseCapability capability, out ICallable promiseResolve, out IteratorInstance iterator) + private bool TryGetPromiseCapabilityAndIterator(JsValue thisObject, JsValue[] arguments, string callerName, out PromiseCapability capability, out ICallable promiseResolve, out IteratorInstance iterator) { - if (!thisObj.IsObject()) + if (!thisObject.IsObject()) { ExceptionHelper.ThrowTypeError(_realm, $"{callerName} called on non-object"); } //2. Let promiseCapability be ? NewPromiseCapability(C). - capability = NewPromiseCapability(_engine, thisObj); + capability = NewPromiseCapability(_engine, thisObject); var reject = capability.Reject; //3. Let promiseResolve be GetPromiseResolve(C). // 4. IfAbruptRejectPromise(promiseResolve, promiseCapability). try { - promiseResolve = GetPromiseResolve(thisObj); + promiseResolve = GetPromiseResolve(thisObject); } catch (JavaScriptException e) { @@ -212,9 +212,9 @@ private bool TryGetPromiseCapabilityAndIterator(JsValue thisObj, JsValue[] argum } // https://tc39.es/ecma262/#sec-promise.all - private JsValue All(JsValue thisObj, JsValue[] arguments) + private JsValue All(JsValue thisObject, JsValue[] arguments) { - if (!TryGetPromiseCapabilityAndIterator(thisObj, arguments, "Promise.all", out var capability, out var promiseResolve, out var iterator)) + if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.all", out var capability, out var promiseResolve, out var iterator)) return capability.PromiseInstance; var (resultingPromise, resolve, reject, _, rejectObj) = capability; @@ -267,7 +267,7 @@ void ResolveIfFinished() // In F# it would be Option results.Add(null!); - var item = promiseResolve.Call(thisObj, new JsValue[] { value }); + var item = promiseResolve.Call(thisObject, new JsValue[] { value }); var thenProps = item.Get("then"); if (thenProps is ICallable thenFunc) { @@ -308,9 +308,9 @@ void ResolveIfFinished() } // https://tc39.es/ecma262/#sec-promise.allsettled - private JsValue AllSettled(JsValue thisObj, JsValue[] arguments) + private JsValue AllSettled(JsValue thisObject, JsValue[] arguments) { - if (!TryGetPromiseCapabilityAndIterator(thisObj, arguments, "Promise.allSettled", out var capability, out var promiseResolve, out var iterator)) + if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.allSettled", out var capability, out var promiseResolve, out var iterator)) return capability.PromiseInstance; var (resultingPromise, resolve, reject, _, rejectObj) = capability; @@ -363,7 +363,7 @@ void ResolveIfFinished() // In F# it would be Option results.Add(null!); - var item = promiseResolve.Call(thisObj, new JsValue[] { value }); + var item = promiseResolve.Call(thisObject, new JsValue[] { value }); var thenProps = item.Get("then"); if (thenProps is ICallable thenFunc) { @@ -426,9 +426,9 @@ void ResolveIfFinished() } // https://tc39.es/ecma262/#sec-promise.any - private JsValue Any(JsValue thisObj, JsValue[] arguments) + private JsValue Any(JsValue thisObject, JsValue[] arguments) { - if (!TryGetPromiseCapabilityAndIterator(thisObj, arguments, "Promise.any", out var capability, out var promiseResolve, out var iterator)) + if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.any", out var capability, out var promiseResolve, out var iterator)) { return capability.PromiseInstance; } @@ -488,7 +488,7 @@ void RejectIfAllRejected() // In F# it would be Option errors.Add(null!); - var item = promiseResolve.Call(thisObj, new JsValue[] { value }); + var item = promiseResolve.Call(thisObject, new JsValue[] { value }); var thenProps = item.Get("then"); if (thenProps is ICallable thenFunc) { @@ -530,9 +530,9 @@ void RejectIfAllRejected() } // https://tc39.es/ecma262/#sec-promise.race - private JsValue Race(JsValue thisObj, JsValue[] arguments) + private JsValue Race(JsValue thisObject, JsValue[] arguments) { - if (!TryGetPromiseCapabilityAndIterator(thisObj, arguments, "Promise.race", out var capability, out var promiseResolve, out var iterator)) + if (!TryGetPromiseCapabilityAndIterator(thisObject, arguments, "Promise.race", out var capability, out var promiseResolve, out var iterator)) return capability.PromiseInstance; var (resultingPromise, resolve, reject, _, rejectObj) = capability; @@ -561,7 +561,7 @@ private JsValue Race(JsValue thisObj, JsValue[] arguments) } // h. Let nextPromise be ? Call(promiseResolve, constructor, « nextValue »). - var nextPromise = promiseResolve.Call(thisObj, new JsValue[] { nextValue }); + var nextPromise = promiseResolve.Call(thisObject, new JsValue[] { nextValue }); // i. Perform ? Invoke(nextPromise, "then", « resultCapability.[[Resolve]], resultCapability.[[Reject]] »). @@ -633,7 +633,7 @@ internal static PromiseCapability NewPromiseCapability(Engine engine, JsValue c) JsValue? resolveArg = null; JsValue? rejectArg = null; - JsValue Executor(JsValue thisObj, JsValue[] arguments) + JsValue Executor(JsValue thisObject, JsValue[] arguments) { // 25.4.1.5.1 GetCapabilitiesExecutor Functions // 3. If promiseCapability.[[Resolve]] is not undefined, throw a TypeError exception. diff --git a/Jint/Native/Promise/PromiseInstance.cs b/Jint/Native/Promise/PromiseInstance.cs index e4e4329f54..6d0c2057e4 100644 --- a/Jint/Native/Promise/PromiseInstance.cs +++ b/Jint/Native/Promise/PromiseInstance.cs @@ -83,7 +83,7 @@ internal ResolvingFunctions CreateResolvingFunctions() } // https://tc39.es/ecma262/#sec-promise-resolve-functions - private JsValue Resolve(JsValue thisObj, JsValue[] arguments) + private JsValue Resolve(JsValue thisObject, JsValue[] arguments) { var result = arguments.At(0); return Resolve(result); @@ -126,7 +126,7 @@ internal JsValue Resolve(JsValue result) } // https://tc39.es/ecma262/#sec-promise-reject-functions - private JsValue Reject(JsValue thisObj, JsValue[] arguments) + private JsValue Reject(JsValue thisObject, JsValue[] arguments) { // Note that alreadyResolved logic lives in CreateResolvingFunctions method diff --git a/Jint/Native/Promise/PromisePrototype.cs b/Jint/Native/Promise/PromisePrototype.cs index a061e33166..36cf1692b8 100644 --- a/Jint/Native/Promise/PromisePrototype.cs +++ b/Jint/Native/Promise/PromisePrototype.cs @@ -50,7 +50,7 @@ protected override void Initialize() // 3. Let C be ? SpeciesConstructor(promise, %Promise%). // 4. Let resultCapability be ? NewPromiseCapability(C). // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability). - private JsValue Then(JsValue thisValue, JsValue[] args) + private JsValue Then(JsValue thisValue, JsValue[] arguments) { // 1. Let promise be the this value. // 2. If IsPromise(promise) is false, throw a TypeError exception. @@ -67,7 +67,7 @@ private JsValue Then(JsValue thisValue, JsValue[] args) var capability = PromiseConstructor.NewPromiseCapability(_engine, (JsValue) ctor); // 5. Return PerformPromiseThen(promise, onFulfilled, onRejected, resultCapability). - return PromiseOperations.PerformPromiseThen(_engine, promise, args.At(0), args.At(1), capability); + return PromiseOperations.PerformPromiseThen(_engine, promise, arguments.At(0), arguments.At(1), capability); } // https://tc39.es/ecma262/#sec-promise.prototype.catch @@ -77,11 +77,11 @@ private JsValue Then(JsValue thisValue, JsValue[] args) // // 1. Let promise be the this value. // 2. Return ? Invoke(promise, "then", « undefined, onRejected »). - private JsValue Catch(JsValue thisValue, JsValue[] args) => - _engine.Invoke(thisValue, "then", new[] {Undefined, args.At(0)}); + private JsValue Catch(JsValue thisValue, JsValue[] arguments) => + _engine.Invoke(thisValue, "then", new[] {Undefined, arguments.At(0)}); // https://tc39.es/ecma262/#sec-promise.prototype.finally - private JsValue Finally(JsValue thisValue, JsValue[] args) + private JsValue Finally(JsValue thisValue, JsValue[] arguments) { // 1. Let promise be the this value. // 2. If Type(promise) is not Object, throw a TypeError exception. @@ -97,7 +97,7 @@ private JsValue Finally(JsValue thisValue, JsValue[] args) JsValue thenFinally; JsValue catchFinally; - var onFinally = args.At(0); + var onFinally = arguments.At(0); // 5. If IsCallable(onFinally) is false, then if (onFinally is not ICallable onFinallyFunc) diff --git a/Jint/Native/RegExp/RegExpPrototype.cs b/Jint/Native/RegExp/RegExpPrototype.cs index 8e2e8a09c5..265b6fb9f1 100644 --- a/Jint/Native/RegExp/RegExpPrototype.cs +++ b/Jint/Native/RegExp/RegExpPrototype.cs @@ -98,14 +98,14 @@ GetSetPropertyDescriptor CreateGetAccessorDescriptor(string name, Func /// https://tc39.es/ecma262/#sec-get-regexp.prototype.source /// - private JsValue Source(JsValue thisObj, JsValue[] arguments) + private JsValue Source(JsValue thisObject, JsValue[] arguments) { - if (ReferenceEquals(thisObj, this)) + if (ReferenceEquals(thisObject, this)) { return DefaultSource; } - var r = thisObj as JsRegExp; + var r = thisObject as JsRegExp; if (r is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -126,9 +126,9 @@ private JsValue Source(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-regexp.prototype-@@replace /// - private JsValue Replace(JsValue thisObj, JsValue[] arguments) + private JsValue Replace(JsValue thisObject, JsValue[] arguments) { - var rx = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.replace"); + var rx = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.replace"); var s = TypeConverter.ToString(arguments.At(0)); var lengthS = s.Length; var replaceValue = arguments.At(1); @@ -428,9 +428,9 @@ internal static string GetSubstitution( /// /// https://tc39.es/ecma262/#sec-regexp.prototype-@@split /// - private JsValue Split(JsValue thisObj, JsValue[] arguments) + private JsValue Split(JsValue thisObject, JsValue[] arguments) { - var rx = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.split"); + var rx = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.split"); var s = TypeConverter.ToString(arguments.At(0)); var limit = arguments.At(1); var c = SpeciesConstructor(rx, _realm.Intrinsics.RegExp); @@ -585,9 +585,9 @@ private JsValue SplitSlow(string s, ObjectInstance splitter, bool unicodeMatchin return a; } - private JsValue Flags(JsValue thisObj, JsValue[] arguments) + private JsValue Flags(JsValue thisObject, JsValue[] arguments) { - var r = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.flags"); + var r = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.flags"); static string AddFlagIfPresent(JsValue o, JsValue p, char flag, string s) { @@ -606,9 +606,9 @@ static string AddFlagIfPresent(JsValue o, JsValue p, char flag, string s) return result; } - private JsValue ToRegExpString(JsValue thisObj, JsValue[] arguments) + private JsValue ToRegExpString(JsValue thisObject, JsValue[] arguments) { - var r = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.toString"); + var r = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.toString"); var pattern = TypeConverter.ToString(r.Get(PropertySource)); var flags = TypeConverter.ToString(r.Get(PropertyFlags)); @@ -616,9 +616,9 @@ private JsValue ToRegExpString(JsValue thisObj, JsValue[] arguments) return "/" + pattern + "/" + flags; } - private JsValue Test(JsValue thisObj, JsValue[] arguments) + private JsValue Test(JsValue thisObject, JsValue[] arguments) { - var r = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.test"); + var r = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.test"); var s = TypeConverter.ToString(arguments.At(0)); // check couple fast paths @@ -653,9 +653,9 @@ private JsValue Test(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-regexp.prototype-@@search /// - private JsValue Search(JsValue thisObj, JsValue[] arguments) + private JsValue Search(JsValue thisObject, JsValue[] arguments) { - var rx = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.search"); + var rx = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.search"); var s = TypeConverter.ToString(arguments.At(0)); var previousLastIndex = rx.Get(JsRegExp.PropertyLastIndex); @@ -682,9 +682,9 @@ private JsValue Search(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-regexp.prototype-@@match /// - private JsValue Match(JsValue thisObj, JsValue[] arguments) + private JsValue Match(JsValue thisObject, JsValue[] arguments) { - var rx = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.match"); + var rx = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.match"); var s = TypeConverter.ToString(arguments.At(0)); var flags = TypeConverter.ToString(rx.Get(PropertyFlags)); @@ -774,9 +774,9 @@ private JsValue MatchSlow(ObjectInstance rx, string s, bool fullUnicode) /// /// https://tc39.es/ecma262/#sec-regexp-prototype-matchall /// - private JsValue MatchAll(JsValue thisObj, JsValue[] arguments) + private JsValue MatchAll(JsValue thisObject, JsValue[] arguments) { - var r = AssertThisIsObjectInstance(thisObj, "RegExp.prototype.matchAll"); + var r = AssertThisIsObjectInstance(thisObject, "RegExp.prototype.matchAll"); var s = TypeConverter.ToString(arguments.At(0)); var c = SpeciesConstructor(r, _realm.Intrinsics.RegExp); @@ -1083,9 +1083,9 @@ private static JsValue GetMatchIndexPair(Engine engine, string s, JsNumber[] mat return groupNameFromNumber; } - private JsValue Exec(JsValue thisObj, JsValue[] arguments) + private JsValue Exec(JsValue thisObject, JsValue[] arguments) { - var r = thisObj as JsRegExp; + var r = thisObject as JsRegExp; if (r is null) { ExceptionHelper.ThrowTypeError(_engine.Realm); diff --git a/Jint/Native/Set/SetPrototype.cs b/Jint/Native/Set/SetPrototype.cs index ac6ea615e7..fd670e00ab 100644 --- a/Jint/Native/Set/SetPrototype.cs +++ b/Jint/Native/Set/SetPrototype.cs @@ -50,59 +50,59 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Size(JsValue thisObj, JsValue[] arguments) + private JsValue Size(JsValue thisObject, JsValue[] arguments) { - AssertSetInstance(thisObj); + AssertSetInstance(thisObject); return JsNumber.Create(0); } - private JsValue Add(JsValue thisObj, JsValue[] arguments) + private JsValue Add(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); var value = arguments.At(0); if (value is JsNumber number && number.IsNegativeZero()) { value = JsNumber.PositiveZero; } set.Add(value); - return thisObj; + return thisObject; } - private JsValue Clear(JsValue thisObj, JsValue[] arguments) + private JsValue Clear(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); set.Clear(); return Undefined; } - private JsValue Delete(JsValue thisObj, JsValue[] arguments) + private JsValue Delete(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); return set.SetDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue Has(JsValue thisObj, JsValue[] arguments) + private JsValue Has(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); return set.Has(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue Entries(JsValue thisObj, JsValue[] arguments) + private JsValue Entries(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); return set.Entries(); } - private JsValue ForEach(JsValue thisObj, JsValue[] arguments) + private JsValue ForEach(JsValue thisObject, JsValue[] arguments) { var callbackfn = arguments.At(0); var thisArg = arguments.At(1); - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); var callable = GetCallable(callbackfn); set.ForEach(callable, thisArg); @@ -110,20 +110,20 @@ private JsValue ForEach(JsValue thisObj, JsValue[] arguments) return Undefined; } - private ObjectInstance Values(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Values(JsValue thisObject, JsValue[] arguments) { - var set = AssertSetInstance(thisObj); + var set = AssertSetInstance(thisObject); return set.Values(); } - private SetInstance AssertSetInstance(JsValue thisObj) + private SetInstance AssertSetInstance(JsValue thisObject) { - var set = thisObj as SetInstance; - if (set is null) + if (thisObject is SetInstance set) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a Set"); + return set; } - return set; + ExceptionHelper.ThrowTypeError(_realm, "object must be a Set"); + return default; } } diff --git a/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs b/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs index 5da949e2ef..75eaa59333 100644 --- a/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs +++ b/Jint/Native/ShadowRealm/ShadowRealmPrototype.cs @@ -43,9 +43,9 @@ protected override void Initialize() /// /// https://tc39.es/proposal-shadowrealm/#sec-shadowrealm.prototype.evaluate /// - private JsValue Evaluate(JsValue thisObj, JsValue[] arguments) + private JsValue Evaluate(JsValue thisObject, JsValue[] arguments) { - var shadowRealm = ValidateShadowRealmObject(thisObj); + var shadowRealm = ValidateShadowRealmObject(thisObject); var sourceText = arguments.At(0); if (!sourceText.IsString()) @@ -59,12 +59,12 @@ private JsValue Evaluate(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/proposal-shadowrealm/#sec-shadowrealm.prototype.importvalue /// - private JsValue ImportValue(JsValue thisObj, JsValue[] arguments) + private JsValue ImportValue(JsValue thisObject, JsValue[] arguments) { var specifier = arguments.At(0); var exportName = arguments.At(1); - var O = ValidateShadowRealmObject(thisObj); + var O = ValidateShadowRealmObject(thisObject); var specifierString = TypeConverter.ToJsString(specifier); if (!specifier.IsString()) { @@ -80,14 +80,14 @@ private JsValue ImportValue(JsValue thisObj, JsValue[] arguments) return O.ShadowRealmImportValue(specifierString.ToString(), exportName.ToString(), callerRealm); } - private ShadowRealm ValidateShadowRealmObject(JsValue thisObj) + private ShadowRealm ValidateShadowRealmObject(JsValue thisObject) { - var instance = thisObj as ShadowRealm; - if (instance is null) + if (thisObject is ShadowRealm shadowRealm) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a ShadowRealm"); + return shadowRealm; } - return instance; + ExceptionHelper.ThrowTypeError(_realm, "object must be a ShadowRealm"); + return default; } } diff --git a/Jint/Native/String/StringConstructor.cs b/Jint/Native/String/StringConstructor.cs index 0eb4af28d3..28caa2cc20 100644 --- a/Jint/Native/String/StringConstructor.cs +++ b/Jint/Native/String/StringConstructor.cs @@ -74,7 +74,7 @@ private static JsValue FromCharCode(JsValue? thisObj, JsValue[] arguments) return JsString.Create(new string(elements)); } - private JsValue FromCodePoint(JsValue thisObj, JsValue[] arguments) + private JsValue FromCodePoint(JsValue thisObject, JsValue[] arguments) { var codeUnits = new List(); string result = ""; @@ -117,7 +117,7 @@ private JsValue FromCodePoint(JsValue thisObj, JsValue[] arguments) /// /// https://www.ecma-international.org/ecma-262/6.0/#sec-string.raw /// - private JsValue Raw(JsValue thisObj, JsValue[] arguments) + private JsValue Raw(JsValue thisObject, JsValue[] arguments) { var cooked = TypeConverter.ToObject(_realm, arguments.At(0)); var raw = TypeConverter.ToObject(_realm, cooked.Get(JintTaggedTemplateExpression.PropertyRaw)); diff --git a/Jint/Native/String/StringPrototype.cs b/Jint/Native/String/StringPrototype.cs index 82f584f2ec..c781875a96 100644 --- a/Jint/Native/String/StringPrototype.cs +++ b/Jint/Native/String/StringPrototype.cs @@ -90,21 +90,21 @@ protected override void Initialize() SetSymbols(symbols); } - private ObjectInstance Iterator(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Iterator(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var str = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var str = TypeConverter.ToString(thisObject); return _realm.Intrinsics.StringIteratorPrototype.Construct(str); } - private JsValue ToStringString(JsValue thisObj, JsValue[] arguments) + private JsValue ToStringString(JsValue thisObject, JsValue[] arguments) { - if (thisObj.IsString()) + if (thisObject.IsString()) { - return thisObj; + return thisObject; } - var s = TypeConverter.ToObject(_realm, thisObj) as StringInstance; + var s = TypeConverter.ToObject(_realm, thisObject) as StringInstance; if (ReferenceEquals(s, null)) { ExceptionHelper.ThrowTypeError(_realm); @@ -185,10 +185,10 @@ internal static string TrimEx(string s) /// https://tc39.es/ecma262/#sec-string.prototype.trim /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - private JsValue Trim(JsValue thisObj, JsValue[] arguments) + private JsValue Trim(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToJsString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToJsString(thisObject); if (s.Length == 0 || (!IsWhiteSpaceEx(s[0]) && !IsWhiteSpaceEx(s[s.Length - 1]))) { return s; @@ -199,10 +199,10 @@ private JsValue Trim(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.trimstart /// - private JsValue TrimStart(JsValue thisObj, JsValue[] arguments) + private JsValue TrimStart(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToJsString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToJsString(thisObject); if (s.Length == 0 || !IsWhiteSpaceEx(s[0])) { return s; @@ -213,10 +213,10 @@ private JsValue TrimStart(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.trimend /// - private JsValue TrimEnd(JsValue thisObj, JsValue[] arguments) + private JsValue TrimEnd(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToJsString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToJsString(thisObject); if (s.Length == 0 || !IsWhiteSpaceEx(s[s.Length - 1])) { return s; @@ -224,31 +224,31 @@ private JsValue TrimEnd(JsValue thisObj, JsValue[] arguments) return TrimEndEx(s.ToString()); } - private JsValue ToLocaleUpperCase(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleUpperCase(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); return new JsString(s.ToUpper()); } - private JsValue ToUpperCase(JsValue thisObj, JsValue[] arguments) + private JsValue ToUpperCase(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); return new JsString(s.ToUpperInvariant()); } - private JsValue ToLocaleLowerCase(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleLowerCase(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); return new JsString(s.ToLower()); } - private JsValue ToLowerCase(JsValue thisObj, JsValue[] arguments) + private JsValue ToLowerCase(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); return s.ToLowerInvariant(); } @@ -273,11 +273,11 @@ private static int ToIntegerSupportInfinityUnlikely(JsValue numberVal) return intVal; } - private JsValue Substring(JsValue thisObj, JsValue[] arguments) + private JsValue Substring(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToString(thisObj); + var s = TypeConverter.ToString(thisObject); var start = TypeConverter.ToNumber(arguments.At(0)); var end = TypeConverter.ToNumber(arguments.At(1)); @@ -315,9 +315,9 @@ private JsValue Substring(JsValue thisObj, JsValue[] arguments) return new JsString(s.Substring(from, length)); } - private static JsValue Substr(JsValue thisObj, JsValue[] arguments) + private static JsValue Substr(JsValue thisObject, JsValue[] arguments) { - var s = TypeConverter.ToString(thisObj); + var s = TypeConverter.ToString(thisObject); var start = TypeConverter.ToInteger(arguments.At(0)); var length = arguments.At(1).IsUndefined() ? double.PositiveInfinity @@ -342,9 +342,9 @@ private static JsValue Substr(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.split /// - private JsValue Split(JsValue thisObj, JsValue[] arguments) + private JsValue Split(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var separator = arguments.At(0); var limit = arguments.At(1); @@ -360,11 +360,11 @@ private JsValue Split(JsValue thisObj, JsValue[] arguments) var splitter = GetMethod(_realm, oi, GlobalSymbolRegistry.Split); if (splitter != null) { - return splitter.Call(separator, new[] { thisObj, limit }); + return splitter.Call(separator, new[] { thisObject, limit }); } } - var s = TypeConverter.ToString(thisObj); + var s = TypeConverter.ToString(thisObject); // Coerce into a number, true will become 1 var lim = limit.IsUndefined() ? uint.MaxValue : TypeConverter.ToUint32(limit); @@ -435,12 +435,12 @@ internal static JsValue SplitWithStringSeparator(Realm realm, JsValue separator, /// /// https://tc39.es/proposal-relative-indexing-method/#sec-string-prototype-additions /// - private JsValue At(JsValue thisObj, JsValue[] arguments) + private JsValue At(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); var start = arguments.At(0); - var o = thisObj.ToString(); + var o = thisObject.ToString(); long len = o.Length; var relativeIndex = TypeConverter.ToInteger(start); @@ -463,9 +463,9 @@ private JsValue At(JsValue thisObj, JsValue[] arguments) return o[k]; } - private JsValue Slice(JsValue thisObj, JsValue[] arguments) + private JsValue Slice(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var start = TypeConverter.ToNumber(arguments.At(0)); if (double.IsNegativeInfinity(start)) @@ -477,7 +477,7 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) return JsString.Empty; } - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var end = TypeConverter.ToNumber(arguments.At(1)); if (double.IsPositiveInfinity(end)) { @@ -504,9 +504,9 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) return s.Substring(from, span); } - private JsValue Search(JsValue thisObj, JsValue[] arguments) + private JsValue Search(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var regex = arguments.At(0); if (regex is ObjectInstance oi) @@ -514,21 +514,21 @@ private JsValue Search(JsValue thisObj, JsValue[] arguments) var searcher = GetMethod(_realm, oi, GlobalSymbolRegistry.Search); if (searcher != null) { - return searcher.Call(regex, new[] { thisObj }); + return searcher.Call(regex, new[] { thisObject }); } } var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex}); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); return _engine.Invoke(rx, GlobalSymbolRegistry.Search, new JsValue[] { s }); } /// /// https://tc39.es/ecma262/#sec-string.prototype.replace /// - private JsValue Replace(JsValue thisObj, JsValue[] arguments) + private JsValue Replace(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var searchValue = arguments.At(0); var replaceValue = arguments.At(1); @@ -538,11 +538,11 @@ private JsValue Replace(JsValue thisObj, JsValue[] arguments) var replacer = GetMethod(_realm, searchValue, GlobalSymbolRegistry.Replace); if (replacer != null) { - return replacer.Call(searchValue, thisObj, replaceValue); + return replacer.Call(searchValue, thisObject, replaceValue); } } - var thisString = TypeConverter.ToJsString(thisObj); + var thisString = TypeConverter.ToJsString(thisObject); var searchString = TypeConverter.ToString(searchValue); var functionalReplace = replaceValue is ICallable; @@ -578,9 +578,9 @@ private JsValue Replace(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.replaceall /// - private JsValue ReplaceAll(JsValue thisObj, JsValue[] arguments) + private JsValue ReplaceAll(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var searchValue = arguments.At(0); var replaceValue = arguments.At(1); @@ -600,11 +600,11 @@ private JsValue ReplaceAll(JsValue thisObj, JsValue[] arguments) var replacer = GetMethod(_realm, searchValue, GlobalSymbolRegistry.Replace); if (replacer != null) { - return replacer.Call(searchValue, thisObj, replaceValue); + return replacer.Call(searchValue, thisObject, replaceValue); } } - var thisString = TypeConverter.ToString(thisObj); + var thisString = TypeConverter.ToString(thisObject); var searchString = TypeConverter.ToString(searchValue); var functionalReplace = replaceValue is ICallable; @@ -672,9 +672,9 @@ static int StringIndexOf(string s, string search, int fromIndex) return result.ToString(); } - private JsValue Match(JsValue thisObj, JsValue[] arguments) + private JsValue Match(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); var regex = arguments.At(0); if (regex is ObjectInstance oi) @@ -682,19 +682,19 @@ private JsValue Match(JsValue thisObj, JsValue[] arguments) var matcher = GetMethod(_realm, oi, GlobalSymbolRegistry.Match); if (matcher != null) { - return matcher.Call(regex, new[] { thisObj }); + return matcher.Call(regex, new[] { thisObject }); } } var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] {regex}); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); return _engine.Invoke(rx, GlobalSymbolRegistry.Match, new JsValue[] { s }); } - private JsValue MatchAll(JsValue thisObj, JsValue[] arguments) + private JsValue MatchAll(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); var regex = arguments.At(0); if (!regex.IsNullOrUndefined()) @@ -711,21 +711,21 @@ private JsValue MatchAll(JsValue thisObj, JsValue[] arguments) var matcher = GetMethod(_realm, (ObjectInstance) regex, GlobalSymbolRegistry.MatchAll); if (matcher != null) { - return matcher.Call(regex, new[] { thisObj }); + return matcher.Call(regex, new[] { thisObject }); } } - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var rx = (JsRegExp) _realm.Intrinsics.RegExp.Construct(new[] { regex, "g" }); return _engine.Invoke(rx, GlobalSymbolRegistry.MatchAll, new JsValue[] { s }); } - private JsValue LocaleCompare(JsValue thisObj, JsValue[] arguments) + private JsValue LocaleCompare(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToString(thisObj); + var s = TypeConverter.ToString(thisObject); var that = TypeConverter.ToString(arguments.At(0)); return string.CompareOrdinal(s.Normalize(NormalizationForm.FormKD), that.Normalize(NormalizationForm.FormKD)); @@ -734,11 +734,11 @@ private JsValue LocaleCompare(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.lastindexof /// - private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var jsString = TypeConverter.ToJsString(thisObj); + var jsString = TypeConverter.ToJsString(thisObject); var searchStr = TypeConverter.ToString(arguments.At(0)); double numPos = double.NaN; if (arguments.Length > 1 && !arguments[1].IsUndefined()) @@ -790,11 +790,11 @@ private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.indexof /// - private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue IndexOf(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var searchStr = TypeConverter.ToString(arguments.At(0)); double pos = 0; if (arguments.Length > 1 && !arguments[1].IsUndefined()) @@ -815,13 +815,13 @@ private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) return s.IndexOf(searchStr, (int) pos); } - private JsValue Concat(JsValue thisObj, JsValue[] arguments) + private JsValue Concat(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - if (thisObj is not JsString jsString) + if (thisObject is not JsString jsString) { - jsString = new JsString.ConcatenatedString(TypeConverter.ToString(thisObj)); + jsString = new JsString.ConcatenatedString(TypeConverter.ToString(thisObject)); } else { @@ -836,12 +836,12 @@ private JsValue Concat(JsValue thisObj, JsValue[] arguments) return jsString; } - private JsValue CharCodeAt(JsValue thisObj, JsValue[] arguments) + private JsValue CharCodeAt(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); JsValue pos = arguments.Length > 0 ? arguments[0] : 0; - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var position = (int) TypeConverter.ToInteger(pos); if (position < 0 || position >= s.Length) { @@ -853,12 +853,12 @@ private JsValue CharCodeAt(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.codepointat /// - private JsValue CodePointAt(JsValue thisObj, JsValue[] arguments) + private JsValue CodePointAt(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); JsValue pos = arguments.Length > 0 ? arguments[0] : 0; - var s = TypeConverter.ToString(thisObj); + var s = TypeConverter.ToString(thisObject); var position = (int)TypeConverter.ToInteger(pos); if (position < 0 || position >= s.Length) { @@ -897,10 +897,10 @@ private static CodePointResult CodePointAt(string s, int position) return new CodePointResult(char.ConvertToUtf32(first, second), 2, false); } - private JsValue CharAt(JsValue thisObj, JsValue[] arguments) + private JsValue CharAt(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToJsString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToJsString(thisObject); var position = TypeConverter.ToInteger(arguments.At(0)); var size = s.Length; if (position >= size || position < 0) @@ -910,16 +910,16 @@ private JsValue CharAt(JsValue thisObj, JsValue[] arguments) return JsString.Create(s[(int) position]); } - private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) + private JsValue ValueOf(JsValue thisObject, JsValue[] arguments) { - if (thisObj is StringInstance si) + if (thisObject is StringInstance si) { return si.StringData; } - if (thisObj is JsString) + if (thisObject is JsString) { - return thisObj; + return thisObject; } ExceptionHelper.ThrowTypeError(_realm); @@ -929,26 +929,26 @@ private JsValue ValueOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.padstart /// - private JsValue PadStart(JsValue thisObj, JsValue[] arguments) + private JsValue PadStart(JsValue thisObject, JsValue[] arguments) { - return StringPad(thisObj, arguments, true); + return StringPad(thisObject, arguments, true); } /// /// https://tc39.es/ecma262/#sec-string.prototype.padend /// - private JsValue PadEnd(JsValue thisObj, JsValue[] arguments) + private JsValue PadEnd(JsValue thisObject, JsValue[] arguments) { - return StringPad(thisObj, arguments, false); + return StringPad(thisObject, arguments, false); } /// /// https://tc39.es/ecma262/#sec-stringpad /// - private JsValue StringPad(JsValue thisObj, JsValue[] arguments, bool padStart) + private JsValue StringPad(JsValue thisObject, JsValue[] arguments, bool padStart) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToJsString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToJsString(thisObject); var targetLength = TypeConverter.ToInt32(arguments.At(0)); var padStringValue = arguments.At(1); @@ -976,11 +976,11 @@ private JsValue StringPad(JsValue thisObj, JsValue[] arguments, bool padStart) /// /// https://tc39.es/ecma262/#sec-string.prototype.startswith /// - private JsValue StartsWith(JsValue thisObj, JsValue[] arguments) + private JsValue StartsWith(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var searchString = arguments.At(0); if (ReferenceEquals(searchString, Null)) @@ -1008,11 +1008,11 @@ private JsValue StartsWith(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.endswith /// - private JsValue EndsWith(JsValue thisObj, JsValue[] arguments) + private JsValue EndsWith(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var searchString = arguments.At(0); if (ReferenceEquals(searchString, Null)) @@ -1039,11 +1039,11 @@ private JsValue EndsWith(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.includes /// - private JsValue Includes(JsValue thisObj, JsValue[] arguments) + private JsValue Includes(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); - var s = TypeConverter.ToJsString(thisObj); + var s = TypeConverter.ToJsString(thisObject); var searchString = arguments.At(0); if (searchString.IsRegExp()) @@ -1071,10 +1071,10 @@ private JsValue Includes(JsValue thisObj, JsValue[] arguments) return s.IndexOf(searchStr, (int) pos) > -1; } - private JsValue Normalize(JsValue thisObj, JsValue[] arguments) + private JsValue Normalize(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var str = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var str = TypeConverter.ToString(thisObject); var param = arguments.At(0); @@ -1112,10 +1112,10 @@ private JsValue Normalize(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-string.prototype.repeat /// - private JsValue Repeat(JsValue thisObj, JsValue[] arguments) + private JsValue Repeat(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(Engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(Engine, thisObject); + var s = TypeConverter.ToString(thisObject); var count = arguments.At(0); var n = TypeConverter.ToIntegerOrInfinity(count); @@ -1145,18 +1145,18 @@ private JsValue Repeat(JsValue thisObj, JsValue[] arguments) return sb.ToString(); } - private JsValue IsWellFormed(JsValue thisObj, JsValue[] arguments) + private JsValue IsWellFormed(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); return IsStringWellFormedUnicode(s); } - private JsValue ToWellFormed(JsValue thisObj, JsValue[] arguments) + private JsValue ToWellFormed(JsValue thisObject, JsValue[] arguments) { - TypeConverter.CheckObjectCoercible(_engine, thisObj); - var s = TypeConverter.ToString(thisObj); + TypeConverter.CheckObjectCoercible(_engine, thisObject); + var s = TypeConverter.ToString(thisObject); var strLen = s.Length; var k = 0; diff --git a/Jint/Native/Symbol/SymbolConstructor.cs b/Jint/Native/Symbol/SymbolConstructor.cs index e729b11466..0252db8164 100644 --- a/Jint/Native/Symbol/SymbolConstructor.cs +++ b/Jint/Native/Symbol/SymbolConstructor.cs @@ -73,7 +73,7 @@ protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments /// /// https://tc39.es/ecma262/#sec-symbol.for /// - private JsValue For(JsValue thisObj, JsValue[] arguments) + private JsValue For(JsValue thisObject, JsValue[] arguments) { var stringKey = TypeConverter.ToJsString(arguments.At(0)); @@ -91,7 +91,7 @@ private JsValue For(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-symbol.keyfor /// - private JsValue KeyFor(JsValue thisObj, JsValue[] arguments) + private JsValue KeyFor(JsValue thisObject, JsValue[] arguments) { var symbol = arguments.At(0) as JsSymbol; if (symbol is null) diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs index 87d9163a92..9b019a099c 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayConstructor.cs @@ -46,9 +46,9 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-%typedarray%.from /// - private JsValue From(JsValue thisObj, JsValue[] arguments) + private JsValue From(JsValue thisObject, JsValue[] arguments) { - var c = thisObj; + var c = thisObject; if (!c.IsConstructor) { ExceptionHelper.ThrowTypeError(_realm); @@ -122,16 +122,16 @@ private JsValue From(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.of /// - private JsValue Of(JsValue thisObj, JsValue[] items) + private JsValue Of(JsValue thisObject, JsValue[] items) { var len = items.Length; - if (!thisObj.IsConstructor) + if (!thisObject.IsConstructor) { ExceptionHelper.ThrowTypeError(_realm); } - var newObj = TypedArrayCreate(_realm, (IConstructor) thisObj, new JsValue[] { len }); + var newObj = TypedArrayCreate(_realm, (IConstructor) thisObject, new JsValue[] { len }); var k = 0; while (k < len) @@ -188,7 +188,7 @@ protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments return Undefined; } - public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) + public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) { ExceptionHelper.ThrowTypeError(_realm, "Abstract class TypedArray not directly constructable"); return null; diff --git a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs index 51e37dfd45..039b84a97d 100644 --- a/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs +++ b/Jint/Native/TypedArray/IntrinsicTypedArrayPrototype.cs @@ -87,9 +87,9 @@ protected override void Initialize() /// /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.buffer /// - private JsValue Buffer(JsValue thisObj, JsValue[] arguments) + private JsValue Buffer(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsTypedArray; + var o = thisObject as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -101,9 +101,9 @@ private JsValue Buffer(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.bytelength /// - private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) + private JsValue ByteLength(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsTypedArray; + var o = thisObject as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -120,9 +120,9 @@ private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.byteoffset /// - private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) + private JsValue ByteOffset(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsTypedArray; + var o = thisObject as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -139,9 +139,9 @@ private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype.length /// - private JsValue GetLength(JsValue thisObj, JsValue[] arguments) + private JsValue GetLength(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsTypedArray; + var o = thisObject as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -159,9 +159,9 @@ private JsValue GetLength(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin /// - private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments) + private JsValue CopyWithin(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var target = arguments.At(0); var start = arguments.At(1); @@ -260,18 +260,18 @@ private JsValue CopyWithin(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries /// - private JsValue Entries(JsValue thisObj, JsValue[] arguments) + private JsValue Entries(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.KeyAndValue); } /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.every /// - private JsValue Every(JsValue thisObj, JsValue[] arguments) + private JsValue Every(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; if (len == 0) @@ -302,9 +302,9 @@ private JsValue Every(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill /// - private JsValue Fill(JsValue thisObj, JsValue[] arguments) + private JsValue Fill(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var jsValue = arguments.At(0); var start = arguments.At(1); @@ -359,18 +359,18 @@ private JsValue Fill(JsValue thisObj, JsValue[] arguments) o[i] = value; } - return thisObj; + return thisObject; } /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter /// - private JsValue Filter(JsValue thisObj, JsValue[] arguments) + private JsValue Filter(JsValue thisObject, JsValue[] arguments) { var callbackfn = GetCallable(arguments.At(0)); var thisArg = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; var kept = new List(); @@ -405,32 +405,32 @@ private JsValue Filter(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.find /// - private JsValue Find(JsValue thisObj, JsValue[] arguments) + private JsValue Find(JsValue thisObject, JsValue[] arguments) { - return DoFind(thisObj, arguments).Value; + return DoFind(thisObject, arguments).Value; } /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex /// - private JsValue FindIndex(JsValue thisObj, JsValue[] arguments) + private JsValue FindIndex(JsValue thisObject, JsValue[] arguments) { - return DoFind(thisObj, arguments).Key; + return DoFind(thisObject, arguments).Key; } - private JsValue FindLast(JsValue thisObj, JsValue[] arguments) + private JsValue FindLast(JsValue thisObject, JsValue[] arguments) { - return DoFind(thisObj, arguments, fromEnd: true).Value; + return DoFind(thisObject, arguments, fromEnd: true).Value; } - private JsValue FindLastIndex(JsValue thisObj, JsValue[] arguments) + private JsValue FindLastIndex(JsValue thisObject, JsValue[] arguments) { - return DoFind(thisObj, arguments, fromEnd: true).Key; + return DoFind(thisObject, arguments, fromEnd: true).Key; } - private KeyValuePair DoFind(JsValue thisObj, JsValue[] arguments, bool fromEnd = false) + private KeyValuePair DoFind(JsValue thisObject, JsValue[] arguments, bool fromEnd = false) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = (int) o.Length; var predicate = GetCallable(arguments.At(0)); @@ -473,12 +473,12 @@ private KeyValuePair DoFind(JsValue thisObj, JsValue[] argumen /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach /// - private JsValue ForEach(JsValue thisObj, JsValue[] arguments) + private JsValue ForEach(JsValue thisObject, JsValue[] arguments) { var callbackfn = GetCallable(arguments.At(0)); var thisArg = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; var args = _engine._jsValueArrayPool.RentArray(3); @@ -499,9 +499,9 @@ private JsValue ForEach(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes /// - private JsValue Includes(JsValue thisObj, JsValue[] arguments) + private JsValue Includes(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; if (len == 0) @@ -553,12 +553,12 @@ private JsValue Includes(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof /// - private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue IndexOf(JsValue thisObject, JsValue[] arguments) { var searchElement = arguments.At(0); var fromIndex = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; if (len == 0) { @@ -608,9 +608,9 @@ private JsValue IndexOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.join /// - private JsValue Join(JsValue thisObj, JsValue[] arguments) + private JsValue Join(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var separator = arguments.At(0); var len = o.Length; @@ -649,20 +649,20 @@ static string StringFromJsValue(JsValue value) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys /// - private JsValue Keys(JsValue thisObj, JsValue[] arguments) + private JsValue Keys(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Key); } /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof /// - private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) + private JsValue LastIndexOf(JsValue thisObject, JsValue[] arguments) { var searchElement = arguments.At(0); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; if (len == 0) { @@ -706,9 +706,9 @@ private JsValue LastIndexOf(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.map /// - private ObjectInstance Map(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Map(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; var thisArg = arguments.At(1); @@ -732,12 +732,12 @@ private ObjectInstance Map(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce /// - private JsValue Reduce(JsValue thisObj, JsValue[] arguments) + private JsValue Reduce(JsValue thisObject, JsValue[] arguments) { var callbackfn = GetCallable(arguments.At(0)); var initialValue = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; if (len == 0 && arguments.Length < 2) @@ -777,12 +777,12 @@ private JsValue Reduce(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright /// - private JsValue ReduceRight(JsValue thisObj, JsValue[] arguments) + private JsValue ReduceRight(JsValue thisObject, JsValue[] arguments) { var callbackfn = GetCallable(arguments.At(0)); var initialValue = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = (int) o.Length; if (len == 0 && arguments.Length < 2) @@ -819,9 +819,9 @@ private JsValue ReduceRight(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse /// - private ObjectInstance Reverse(JsValue thisObj, JsValue[] arguments) + private ObjectInstance Reverse(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = (int) o.Length; var middle = (int) System.Math.Floor(len / 2.0); var lower = 0; @@ -844,9 +844,9 @@ private ObjectInstance Reverse(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.set /// - private JsValue Set(JsValue thisObj, JsValue[] arguments) + private JsValue Set(JsValue thisObject, JsValue[] arguments) { - var target = thisObj as JsTypedArray; + var target = thisObject as JsTypedArray; if (target is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -994,11 +994,11 @@ private void SetTypedArrayFromArrayLike(JsTypedArray target, int targetOffset, J /// /// https://tc39.es/proposal-relative-indexing-method/#sec-%typedarray.prototype%-additions /// - private JsValue At(JsValue thisObj, JsValue[] arguments) + private JsValue At(JsValue thisObject, JsValue[] arguments) { var start = arguments.At(0); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); long len = o.Length; var relativeStart = TypeConverter.ToInteger(start); @@ -1024,12 +1024,12 @@ private JsValue At(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice /// - private JsValue Slice(JsValue thisObj, JsValue[] arguments) + private JsValue Slice(JsValue thisObject, JsValue[] arguments) { var start = arguments.At(0); var end = arguments.At(1); - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); long len = o.Length; var relativeStart = TypeConverter.ToIntegerOrInfinity(start); @@ -1109,9 +1109,9 @@ private JsValue Slice(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some /// - private JsValue Some(JsValue thisObj, JsValue[] arguments) + private JsValue Some(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var len = o.Length; var callbackfn = GetCallable(arguments.At(0)); var thisArg = arguments.At(1); @@ -1135,7 +1135,7 @@ private JsValue Some(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort /// - private JsValue Sort(JsValue thisObj, JsValue[] arguments) + private JsValue Sort(JsValue thisObject, JsValue[] arguments) { /* * %TypedArray%.prototype.sort is a distinct function that, except as described below, @@ -1144,7 +1144,7 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) * an object that has a fixed length and whose integer-indexed properties are not sparse. */ - var obj = thisObj.ValidateTypedArray(_realm); + var obj = thisObject.ValidateTypedArray(_realm); var buffer = obj._viewedArrayBuffer; var len = obj.Length; @@ -1168,9 +1168,9 @@ private JsValue Sort(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray /// - private JsValue Subarray(JsValue thisObj, JsValue[] arguments) + private JsValue Subarray(JsValue thisObject, JsValue[] arguments) { - var o = thisObj as JsTypedArray; + var o = thisObject as JsTypedArray; if (o is null) { ExceptionHelper.ThrowTypeError(_realm); @@ -1232,7 +1232,7 @@ private JsValue Subarray(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring /// - private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) + private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments) { /* * %TypedArray%.prototype.toLocaleString is a distinct function that implements the same algorithm as Array.prototype.toLocaleString @@ -1242,7 +1242,7 @@ private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) * any observable changes in the specified behaviour of the algorithm. */ - var array = thisObj.ValidateTypedArray(_realm); + var array = thisObject.ValidateTypedArray(_realm); var len = array.Length; const string separator = ","; if (len == 0) @@ -1288,18 +1288,18 @@ private JsValue ToLocaleString(JsValue thisObj, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values /// - private JsValue Values(JsValue thisObj, JsValue[] arguments) + private JsValue Values(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); return _realm.Intrinsics.ArrayIteratorPrototype.Construct(o, ArrayIteratorType.Value); } /// /// https://tc39.es/ecma262/#sec-get-%typedarray%.prototype-@@tostringtag /// - private static JsValue ToStringTag(JsValue thisObj, JsValue[] arguments) + private static JsValue ToStringTag(JsValue thisObject, JsValue[] arguments) { - if (thisObj is not JsTypedArray o) + if (thisObject is not JsTypedArray o) { return Undefined; } @@ -1307,9 +1307,9 @@ private static JsValue ToStringTag(JsValue thisObj, JsValue[] arguments) return o._arrayElementType.GetTypedArrayName(); } - private JsValue ToReversed(JsValue thisObj, JsValue[] arguments) + private JsValue ToReversed(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var length = o._arrayLength; var a = TypedArrayCreateSameType(o, new [] { JsNumber.Create(length) }); @@ -1323,9 +1323,9 @@ private JsValue ToReversed(JsValue thisObj, JsValue[] arguments) return a; } - private JsValue ToSorted(JsValue thisObj, JsValue[] arguments) + private JsValue ToSorted(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var compareFn = GetCompareFunction(arguments.At(0)); var buffer = o._viewedArrayBuffer; @@ -1342,9 +1342,9 @@ private JsValue ToSorted(JsValue thisObj, JsValue[] arguments) return a; } - private ObjectInstance With(JsValue thisObj, JsValue[] arguments) + private ObjectInstance With(JsValue thisObject, JsValue[] arguments) { - var o = thisObj.ValidateTypedArray(_realm); + var o = thisObject.ValidateTypedArray(_realm); var value = arguments.At(1); var length = o._arrayLength; diff --git a/Jint/Native/TypedArray/TypedArrayConstructor.cs b/Jint/Native/TypedArray/TypedArrayConstructor.cs index 7887c49350..7871980228 100644 --- a/Jint/Native/TypedArray/TypedArrayConstructor.cs +++ b/Jint/Native/TypedArray/TypedArrayConstructor.cs @@ -41,7 +41,7 @@ protected override void Initialize() SetProperties(properties); } - public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) + public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) { if (newTarget.IsUndefined()) { @@ -64,13 +64,13 @@ public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) _ => null! }; - var numberOfArgs = args.Length; + var numberOfArgs = arguments.Length; if (numberOfArgs == 0) { return AllocateTypedArray(newTarget, proto, 0); } - var firstArgument = args[0]; + var firstArgument = arguments[0]; if (firstArgument.IsObject()) { var o = AllocateTypedArray(newTarget, proto); @@ -80,8 +80,8 @@ public override ObjectInstance Construct(JsValue[] args, JsValue newTarget) } else if (firstArgument is JsArrayBuffer arrayBuffer) { - var byteOffset = numberOfArgs > 1 ? args[1] : Undefined; - var length = numberOfArgs > 2 ? args[2] : Undefined; + var byteOffset = numberOfArgs > 1 ? arguments[1] : Undefined; + var length = numberOfArgs > 2 ? arguments[2] : Undefined; InitializeTypedArrayFromArrayBuffer(o, arrayBuffer, byteOffset, length); } else diff --git a/Jint/Native/WeakMap/WeakMapPrototype.cs b/Jint/Native/WeakMap/WeakMapPrototype.cs index a4c1fccebd..a73f83c661 100644 --- a/Jint/Native/WeakMap/WeakMapPrototype.cs +++ b/Jint/Native/WeakMap/WeakMapPrototype.cs @@ -45,39 +45,39 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Get(JsValue thisObj, JsValue[] arguments) + private JsValue Get(JsValue thisObject, JsValue[] arguments) { - var map = AssertWeakMapInstance(thisObj); + var map = AssertWeakMapInstance(thisObject); return map.WeakMapGet(arguments.At(0)); } - private JsValue Delete(JsValue thisObj, JsValue[] arguments) + private JsValue Delete(JsValue thisObject, JsValue[] arguments) { - var map = AssertWeakMapInstance(thisObj); + var map = AssertWeakMapInstance(thisObject); return arguments.Length > 0 && map.WeakMapDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue Set(JsValue thisObj, JsValue[] arguments) + private JsValue Set(JsValue thisObject, JsValue[] arguments) { - var map = AssertWeakMapInstance(thisObj); + var map = AssertWeakMapInstance(thisObject); map.WeakMapSet(arguments.At(0), arguments.At(1)); - return thisObj; + return thisObject; } - private JsValue Has(JsValue thisObj, JsValue[] arguments) + private JsValue Has(JsValue thisObject, JsValue[] arguments) { - var map = AssertWeakMapInstance(thisObj); + var map = AssertWeakMapInstance(thisObject); return map.WeakMapHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private WeakMapInstance AssertWeakMapInstance(JsValue thisObj) + private WeakMapInstance AssertWeakMapInstance(JsValue thisObject) { - var map = thisObj as WeakMapInstance; - if (map is null) + if (thisObject is WeakMapInstance map) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakMap"); + return map; } - return map; + ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakMap"); + return default; } } diff --git a/Jint/Native/WeakRef/WeakRefPrototype.cs b/Jint/Native/WeakRef/WeakRefPrototype.cs index acd9645fb4..7b1d4c3618 100644 --- a/Jint/Native/WeakRef/WeakRefPrototype.cs +++ b/Jint/Native/WeakRef/WeakRefPrototype.cs @@ -41,9 +41,9 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Deref(JsValue thisObj, JsValue[] arguments) + private JsValue Deref(JsValue thisObject, JsValue[] arguments) { - var weakRef = thisObj as WeakRefInstance; + var weakRef = thisObject as WeakRefInstance; if (weakRef is null) { ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakRef"); diff --git a/Jint/Native/WeakSet/WeakSetPrototype.cs b/Jint/Native/WeakSet/WeakSetPrototype.cs index 9b9ec1861e..0bb8612e21 100644 --- a/Jint/Native/WeakSet/WeakSetPrototype.cs +++ b/Jint/Native/WeakSet/WeakSetPrototype.cs @@ -47,33 +47,33 @@ protected override void Initialize() SetSymbols(symbols); } - private JsValue Add(JsValue thisObj, JsValue[] arguments) + private JsValue Add(JsValue thisObject, JsValue[] arguments) { - var set = AssertWeakSetInstance(thisObj); + var set = AssertWeakSetInstance(thisObject); set.WeakSetAdd(arguments.At(0)); - return thisObj; + return thisObject; } - private JsValue Delete(JsValue thisObj, JsValue[] arguments) + private JsValue Delete(JsValue thisObject, JsValue[] arguments) { - var set = AssertWeakSetInstance(thisObj); + var set = AssertWeakSetInstance(thisObject); return set.WeakSetDelete(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private JsValue Has(JsValue thisObj, JsValue[] arguments) + private JsValue Has(JsValue thisObject, JsValue[] arguments) { - var set = AssertWeakSetInstance(thisObj); + var set = AssertWeakSetInstance(thisObject); return set.WeakSetHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private WeakSetInstance AssertWeakSetInstance(JsValue thisObj) + private WeakSetInstance AssertWeakSetInstance(JsValue thisObject) { - var set = thisObj as WeakSetInstance; - if (set is null) + if (thisObject is WeakSetInstance set) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakSet"); + return set; } - return set; + ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakSet"); + return default; } } diff --git a/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs b/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs index 9a9d66fcfa..ed5ade0f2f 100644 --- a/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs +++ b/Jint/Runtime/Environments/FunctionEnvironmentRecord.cs @@ -405,7 +405,7 @@ public ArrayPatternProtocol( _max = max; } - protected override void ProcessItem(JsValue[] args, JsValue currentValue) + protected override void ProcessItem(JsValue[] arguments, JsValue currentValue) { _instance.SetIndexValue((uint) _index, currentValue, updateLength: false); _index++; diff --git a/Jint/Runtime/Interop/ObjectWrapper.cs b/Jint/Runtime/Interop/ObjectWrapper.cs index 9afd608962..f6f5ad67cb 100644 --- a/Jint/Runtime/Interop/ObjectWrapper.cs +++ b/Jint/Runtime/Interop/ObjectWrapper.cs @@ -259,18 +259,18 @@ public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object tar return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target); } - private static JsValue Iterator(JsValue thisObj, JsValue[] arguments) + private static JsValue Iterator(JsValue thisObject, JsValue[] arguments) { - var wrapper = (ObjectWrapper) thisObj; + var wrapper = (ObjectWrapper) thisObject; return wrapper._typeDescriptor.IsDictionary ? new DictionaryIterator(wrapper._engine, wrapper) : new EnumerableIterator(wrapper._engine, (IEnumerable) wrapper.Target); } - private static JsValue GetLength(JsValue thisObj, JsValue[] arguments) + private static JsValue GetLength(JsValue thisObject, JsValue[] arguments) { - var wrapper = (ObjectWrapper) thisObj; + var wrapper = (ObjectWrapper) thisObject; return JsNumber.Create((int) (wrapper._typeDescriptor.LengthProperty?.GetValue(wrapper.Target) ?? 0)); } diff --git a/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs index 010c89e6c6..0a67535406 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintArrayExpression.cs @@ -103,7 +103,7 @@ public ArraySpreadProtocol( _index = startIndex - 1; } - protected override void ProcessItem(JsValue[] args, JsValue currentValue) + protected override void ProcessItem(JsValue[] arguments, JsValue currentValue) { _index++; _addedCount++; diff --git a/Jint/Runtime/Interpreter/Expressions/JintExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintExpression.cs index 437100fe56..51e42f766a 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintExpression.cs @@ -477,7 +477,7 @@ public ArraySpreadProtocol( _instance = instance; } - protected override void ProcessItem(JsValue[] args, JsValue currentValue) + protected override void ProcessItem(JsValue[] arguments, JsValue currentValue) { _instance.Add(currentValue); } diff --git a/Jint/Runtime/Modules/CyclicModuleRecord.cs b/Jint/Runtime/Modules/CyclicModuleRecord.cs index e963b4c778..9bf7593a5d 100644 --- a/Jint/Runtime/Modules/CyclicModuleRecord.cs +++ b/Jint/Runtime/Modules/CyclicModuleRecord.cs @@ -435,7 +435,7 @@ private Completion ExecuteAsyncModule() /// /// https://tc39.es/ecma262/#sec-async-module-execution-fulfilled /// - private JsValue AsyncModuleExecutionFulfilled(JsValue thisObj, JsValue[] arguments) + private JsValue AsyncModuleExecutionFulfilled(JsValue thisObject, JsValue[] arguments) { var module = (CyclicModuleRecord) arguments.At(0); if (module.Status == ModuleStatus.Evaluated) @@ -509,7 +509,7 @@ private JsValue AsyncModuleExecutionFulfilled(JsValue thisObj, JsValue[] argumen /// /// https://tc39.es/ecma262/#sec-async-module-execution-rejected /// - private static JsValue AsyncModuleExecutionRejected(JsValue thisObj, JsValue[] arguments) + private static JsValue AsyncModuleExecutionRejected(JsValue thisObject, JsValue[] arguments) { var module = (SourceTextModuleRecord) arguments.At(0); var error = arguments.At(1); @@ -538,7 +538,7 @@ private static JsValue AsyncModuleExecutionRejected(JsValue thisObj, JsValue[] a for (var i = 0; i < asyncParentModules.Count; i++) { var m = asyncParentModules[i]; - AsyncModuleExecutionRejected(thisObj, new[] { m, error }); + AsyncModuleExecutionRejected(thisObject, new[] { m, error }); } if (module._topLevelCapability is not null) From 805ae4f57c8505937bf9a29ff0d7eff398d76a95 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 21:04:18 +0300 Subject: [PATCH 13/24] Rename WeakSetInstance to JsWeakSet (#1598) --- Jint.Tests/Runtime/WeakSetMapTests.cs | 2 +- Jint/Native/WeakSet/{WeakSetInstance.cs => JsWeakSet.cs} | 4 ++-- Jint/Native/WeakSet/WeakSetConstructor.cs | 2 +- Jint/Native/WeakSet/WeakSetPrototype.cs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename Jint/Native/WeakSet/{WeakSetInstance.cs => JsWeakSet.cs} (88%) diff --git a/Jint.Tests/Runtime/WeakSetMapTests.cs b/Jint.Tests/Runtime/WeakSetMapTests.cs index 0d7fffe5c2..154c44c7e1 100644 --- a/Jint.Tests/Runtime/WeakSetMapTests.cs +++ b/Jint.Tests/Runtime/WeakSetMapTests.cs @@ -39,7 +39,7 @@ public void WeakSetShouldThrowWhenCalledWithoutNew() public void WeakSetAddShouldThrowForPrimitiveKey(JsValue key) { var engine = new Engine(); - var weakSet = new WeakSetInstance(engine); + var weakSet = new JsWeakSet(engine); var e = Assert.Throws(() => weakSet.WeakSetAdd(key)); Assert.StartsWith("WeakSet value must be an object or symbol, got ", e.Message); diff --git a/Jint/Native/WeakSet/WeakSetInstance.cs b/Jint/Native/WeakSet/JsWeakSet.cs similarity index 88% rename from Jint/Native/WeakSet/WeakSetInstance.cs rename to Jint/Native/WeakSet/JsWeakSet.cs index 8882c73a44..32883db12d 100644 --- a/Jint/Native/WeakSet/WeakSetInstance.cs +++ b/Jint/Native/WeakSet/JsWeakSet.cs @@ -5,11 +5,11 @@ namespace Jint.Native.WeakSet; -internal sealed class WeakSetInstance : ObjectInstance +internal sealed class JsWeakSet : ObjectInstance { private readonly ConditionalWeakTable _table; - public WeakSetInstance(Engine engine) : base(engine) + public JsWeakSet(Engine engine) : base(engine) { _table = new ConditionalWeakTable(); } diff --git a/Jint/Native/WeakSet/WeakSetConstructor.cs b/Jint/Native/WeakSet/WeakSetConstructor.cs index 1ead0877f9..987dd8beeb 100644 --- a/Jint/Native/WeakSet/WeakSetConstructor.cs +++ b/Jint/Native/WeakSet/WeakSetConstructor.cs @@ -34,7 +34,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var set = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.WeakSet.PrototypeObject, - static (Engine engine, Realm _, object? _) => new WeakSetInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsWeakSet(engine)); var arg1 = arguments.At(0); if (!arg1.IsNullOrUndefined()) diff --git a/Jint/Native/WeakSet/WeakSetPrototype.cs b/Jint/Native/WeakSet/WeakSetPrototype.cs index 0bb8612e21..43e8ea2c02 100644 --- a/Jint/Native/WeakSet/WeakSetPrototype.cs +++ b/Jint/Native/WeakSet/WeakSetPrototype.cs @@ -66,9 +66,9 @@ private JsValue Has(JsValue thisObject, JsValue[] arguments) return set.WeakSetHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private WeakSetInstance AssertWeakSetInstance(JsValue thisObject) + private JsWeakSet AssertWeakSetInstance(JsValue thisObject) { - if (thisObject is WeakSetInstance set) + if (thisObject is JsWeakSet set) { return set; } From 4bff490028f5e4fb1d5021da3c767caec361d65d Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 21:35:17 +0300 Subject: [PATCH 14/24] Rename WeakMapInstance to JsWeakMap (#1599) --- Jint.Tests/Runtime/WeakSetMapTests.cs | 2 +- Jint/Native/WeakMap/{WeakMapInstance.cs => JsWeakMap.cs} | 4 ++-- Jint/Native/WeakMap/WeakMapConstructor.cs | 2 +- Jint/Native/WeakMap/WeakMapPrototype.cs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) rename Jint/Native/WeakMap/{WeakMapInstance.cs => JsWeakMap.cs} (90%) diff --git a/Jint.Tests/Runtime/WeakSetMapTests.cs b/Jint.Tests/Runtime/WeakSetMapTests.cs index 154c44c7e1..537bb9db64 100644 --- a/Jint.Tests/Runtime/WeakSetMapTests.cs +++ b/Jint.Tests/Runtime/WeakSetMapTests.cs @@ -52,7 +52,7 @@ public void WeakSetAddShouldThrowForPrimitiveKey(JsValue key) public void WeakMapSetShouldThrowForPrimitiveKey(JsValue key) { var engine = new Engine(); - var weakMap = new WeakMapInstance(engine); + var weakMap = new JsWeakMap(engine); var e = Assert.Throws(() => weakMap.WeakMapSet(key, new JsObject(engine))); Assert.StartsWith("WeakMap key must be an object, got ", e.Message); diff --git a/Jint/Native/WeakMap/WeakMapInstance.cs b/Jint/Native/WeakMap/JsWeakMap.cs similarity index 90% rename from Jint/Native/WeakMap/WeakMapInstance.cs rename to Jint/Native/WeakMap/JsWeakMap.cs index 3daf413ce8..daa3770f42 100644 --- a/Jint/Native/WeakMap/WeakMapInstance.cs +++ b/Jint/Native/WeakMap/JsWeakMap.cs @@ -5,11 +5,11 @@ namespace Jint.Native.WeakMap; -internal sealed class WeakMapInstance : ObjectInstance +internal sealed class JsWeakMap : ObjectInstance { private readonly ConditionalWeakTable _table; - public WeakMapInstance(Engine engine) : base(engine) + public JsWeakMap(Engine engine) : base(engine) { _table = new ConditionalWeakTable(); } diff --git a/Jint/Native/WeakMap/WeakMapConstructor.cs b/Jint/Native/WeakMap/WeakMapConstructor.cs index 948e238bd4..0b513bb4a8 100644 --- a/Jint/Native/WeakMap/WeakMapConstructor.cs +++ b/Jint/Native/WeakMap/WeakMapConstructor.cs @@ -35,7 +35,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var map = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.WeakMap.PrototypeObject, - static (Engine engine, Realm _, object? _) => new WeakMapInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsWeakMap(engine)); if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { var adder = map.Get("set"); diff --git a/Jint/Native/WeakMap/WeakMapPrototype.cs b/Jint/Native/WeakMap/WeakMapPrototype.cs index a73f83c661..528328567f 100644 --- a/Jint/Native/WeakMap/WeakMapPrototype.cs +++ b/Jint/Native/WeakMap/WeakMapPrototype.cs @@ -70,9 +70,9 @@ private JsValue Has(JsValue thisObject, JsValue[] arguments) return map.WeakMapHas(arguments.At(0)) ? JsBoolean.True : JsBoolean.False; } - private WeakMapInstance AssertWeakMapInstance(JsValue thisObject) + private JsWeakMap AssertWeakMapInstance(JsValue thisObject) { - if (thisObject is WeakMapInstance map) + if (thisObject is JsWeakMap map) { return map; } From c52ff7f8de06bd708929febcdd7de849807bfc72 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 21:42:41 +0300 Subject: [PATCH 15/24] Rename SetInstance to JsSet (#1600) --- Jint/Native/Set/{SetInstance.cs => JsSet.cs} | 4 ++-- Jint/Native/Set/SetConstructor.cs | 2 +- Jint/Native/Set/SetIteratorPrototype.cs | 8 ++++---- Jint/Native/Set/SetPrototype.cs | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) rename Jint/Native/Set/{SetInstance.cs => JsSet.cs} (94%) diff --git a/Jint/Native/Set/SetInstance.cs b/Jint/Native/Set/JsSet.cs similarity index 94% rename from Jint/Native/Set/SetInstance.cs rename to Jint/Native/Set/JsSet.cs index 828aed30da..d13d5ef417 100644 --- a/Jint/Native/Set/SetInstance.cs +++ b/Jint/Native/Set/JsSet.cs @@ -5,11 +5,11 @@ namespace Jint.Native.Set; -internal sealed class SetInstance : ObjectInstance +internal sealed class JsSet : ObjectInstance { internal readonly OrderedSet _set; - public SetInstance(Engine engine) : base(engine) + public JsSet(Engine engine) : base(engine) { _set = new OrderedSet(SameValueZeroComparer.Instance); } diff --git a/Jint/Native/Set/SetConstructor.cs b/Jint/Native/Set/SetConstructor.cs index 25b5f55968..2335432519 100644 --- a/Jint/Native/Set/SetConstructor.cs +++ b/Jint/Native/Set/SetConstructor.cs @@ -55,7 +55,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var set = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Set.PrototypeObject, - static (Engine engine, Realm _, object? _) => new SetInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsSet(engine)); if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { diff --git a/Jint/Native/Set/SetIteratorPrototype.cs b/Jint/Native/Set/SetIteratorPrototype.cs index d0873eca63..7f3f0501fe 100644 --- a/Jint/Native/Set/SetIteratorPrototype.cs +++ b/Jint/Native/Set/SetIteratorPrototype.cs @@ -35,13 +35,13 @@ protected override void Initialize() SetSymbols(symbols); } - internal IteratorInstance ConstructEntryIterator(SetInstance set) + internal IteratorInstance ConstructEntryIterator(JsSet set) { var instance = new SetEntryIterator(Engine, set); return instance; } - internal IteratorInstance ConstructValueIterator(SetInstance set) + internal IteratorInstance ConstructValueIterator(JsSet set) { var instance = new SetValueIterator(Engine, set._set._list); return instance; @@ -49,10 +49,10 @@ internal IteratorInstance ConstructValueIterator(SetInstance set) private sealed class SetEntryIterator : IteratorInstance { - private readonly SetInstance _set; + private readonly JsSet _set; private int _position; - public SetEntryIterator(Engine engine, SetInstance set) : base(engine) + public SetEntryIterator(Engine engine, JsSet set) : base(engine) { _prototype = engine.Realm.Intrinsics.SetIteratorPrototype; _set = set; diff --git a/Jint/Native/Set/SetPrototype.cs b/Jint/Native/Set/SetPrototype.cs index fd670e00ab..5f97ca8c0b 100644 --- a/Jint/Native/Set/SetPrototype.cs +++ b/Jint/Native/Set/SetPrototype.cs @@ -116,9 +116,9 @@ private ObjectInstance Values(JsValue thisObject, JsValue[] arguments) return set.Values(); } - private SetInstance AssertSetInstance(JsValue thisObject) + private JsSet AssertSetInstance(JsValue thisObject) { - if (thisObject is SetInstance set) + if (thisObject is JsSet set) { return set; } From 5c19933f49d918ff56d9dc971bead7deec525ffd Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 21:58:26 +0300 Subject: [PATCH 16/24] Rename MapInstance to JsMap (#1601) --- Jint/Native/Map/{MapInstance.cs => JsMap.cs} | 11 ++--------- Jint/Native/Map/MapConstructor.cs | 4 ++-- Jint/Native/Map/MapIteratorPrototype.cs | 8 ++++---- Jint/Native/Map/MapPrototype.cs | 4 ++-- 4 files changed, 10 insertions(+), 17 deletions(-) rename Jint/Native/Map/{MapInstance.cs => JsMap.cs} (89%) diff --git a/Jint/Native/Map/MapInstance.cs b/Jint/Native/Map/JsMap.cs similarity index 89% rename from Jint/Native/Map/MapInstance.cs rename to Jint/Native/Map/JsMap.cs index 9dee03d331..546244c98a 100644 --- a/Jint/Native/Map/MapInstance.cs +++ b/Jint/Native/Map/JsMap.cs @@ -1,17 +1,16 @@ using System.Diagnostics.CodeAnalysis; -using System.Runtime.CompilerServices; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; namespace Jint.Native.Map; -internal sealed class MapInstance : ObjectInstance +internal sealed class JsMap : ObjectInstance { private readonly Realm _realm; internal readonly OrderedDictionary _map; - public MapInstance(Engine engine, Realm realm) : base(engine) + public JsMap(Engine engine, Realm realm) : base(engine) { _realm = realm; _map = new OrderedDictionary(SameValueZeroComparer.Instance); @@ -101,10 +100,4 @@ internal ObjectInstance Values() { return _realm.Intrinsics.MapIteratorPrototype.ConstructValueIterator(this); } - - [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal uint GetSize() - { - return (uint) _map.Count; - } } diff --git a/Jint/Native/Map/MapConstructor.cs b/Jint/Native/Map/MapConstructor.cs index bc26e46aef..26d39f334b 100644 --- a/Jint/Native/Map/MapConstructor.cs +++ b/Jint/Native/Map/MapConstructor.cs @@ -62,7 +62,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var map = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Map.PrototypeObject, - static (Engine engine, Realm realm, object? _) => new MapInstance(engine, realm)); + static (Engine engine, Realm realm, object? _) => new JsMap(engine, realm)); if (arguments.Length > 0 && !arguments[0].IsNullOrUndefined()) { @@ -84,7 +84,7 @@ private JsValue GroupBy(JsValue thisObject, JsValue[] arguments) var items = arguments.At(0); var callbackfn = arguments.At(1); var grouping = GroupByHelper.GroupBy(_engine, _realm, items, callbackfn, mapMode: true); - var map = (MapInstance) Construct(_realm.Intrinsics.Map); + var map = (JsMap) Construct(_realm.Intrinsics.Map); foreach (var pair in grouping) { map.MapSet(pair.Key, pair.Value); diff --git a/Jint/Native/Map/MapIteratorPrototype.cs b/Jint/Native/Map/MapIteratorPrototype.cs index c100627dc8..ab34b712ee 100644 --- a/Jint/Native/Map/MapIteratorPrototype.cs +++ b/Jint/Native/Map/MapIteratorPrototype.cs @@ -35,7 +35,7 @@ protected override void Initialize() SetSymbols(symbols); } - internal IteratorInstance ConstructEntryIterator(MapInstance map) + internal IteratorInstance ConstructEntryIterator(JsMap map) { var instance = new MapIterator(Engine, map) { @@ -45,7 +45,7 @@ internal IteratorInstance ConstructEntryIterator(MapInstance map) return instance; } - internal IteratorInstance ConstructKeyIterator(MapInstance map) + internal IteratorInstance ConstructKeyIterator(JsMap map) { var instance = new IteratorInstance.EnumerableIterator(Engine, map._map.Keys) { @@ -55,7 +55,7 @@ internal IteratorInstance ConstructKeyIterator(MapInstance map) return instance; } - internal IteratorInstance ConstructValueIterator(MapInstance map) + internal IteratorInstance ConstructValueIterator(JsMap map) { var instance = new IteratorInstance.EnumerableIterator(Engine, map._map.Values) { @@ -71,7 +71,7 @@ private sealed class MapIterator : IteratorInstance private int _position; - public MapIterator(Engine engine, MapInstance map) : base(engine) + public MapIterator(Engine engine, JsMap map) : base(engine) { _map = map._map; _position = 0; diff --git a/Jint/Native/Map/MapPrototype.cs b/Jint/Native/Map/MapPrototype.cs index f0726243cd..ff77ac3f70 100644 --- a/Jint/Native/Map/MapPrototype.cs +++ b/Jint/Native/Map/MapPrototype.cs @@ -125,9 +125,9 @@ private ObjectInstance Values(JsValue thisObject, JsValue[] arguments) return map.Values(); } - private MapInstance AssertMapInstance(JsValue thisObject) + private JsMap AssertMapInstance(JsValue thisObject) { - if (thisObject is MapInstance map) + if (thisObject is JsMap map) { return map; } From 0b1ed1b39487c014a0a9ea10955d4e32e6d7eaec Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Sun, 30 Jul 2023 22:29:39 +0300 Subject: [PATCH 17/24] Rename WeakRefInstance to JsWeakRef (#1602) --- Jint/Native/WeakRef/{WeakRefInstance.cs => JsWeakRef.cs} | 4 ++-- Jint/Native/WeakRef/WeakRefConstructor.cs | 2 +- Jint/Native/WeakRef/WeakRefPrototype.cs | 8 ++++---- 3 files changed, 7 insertions(+), 7 deletions(-) rename Jint/Native/WeakRef/{WeakRefInstance.cs => JsWeakRef.cs} (80%) diff --git a/Jint/Native/WeakRef/WeakRefInstance.cs b/Jint/Native/WeakRef/JsWeakRef.cs similarity index 80% rename from Jint/Native/WeakRef/WeakRefInstance.cs rename to Jint/Native/WeakRef/JsWeakRef.cs index 77ef081e93..6eaec58430 100644 --- a/Jint/Native/WeakRef/WeakRefInstance.cs +++ b/Jint/Native/WeakRef/JsWeakRef.cs @@ -5,11 +5,11 @@ namespace Jint.Native.WeakRef; /// /// https://tc39.es/ecma262/#sec-properties-of-weak-ref-instances /// -internal sealed class WeakRefInstance : ObjectInstance +internal sealed class JsWeakRef : ObjectInstance { private readonly WeakReference _weakRefTarget; - public WeakRefInstance(Engine engine, JsValue target) : base(engine) + public JsWeakRef(Engine engine, JsValue target) : base(engine) { _weakRefTarget = new WeakReference(target); } diff --git a/Jint/Native/WeakRef/WeakRefConstructor.cs b/Jint/Native/WeakRef/WeakRefConstructor.cs index bcfa74b9ac..913f45a141 100644 --- a/Jint/Native/WeakRef/WeakRefConstructor.cs +++ b/Jint/Native/WeakRef/WeakRefConstructor.cs @@ -44,7 +44,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var weakRef = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.WeakRef.PrototypeObject, - static (engine, _, target) => new WeakRefInstance(engine, target!), + static (engine, _, target) => new JsWeakRef(engine, target!), target); _engine.AddToKeptObjects(target); diff --git a/Jint/Native/WeakRef/WeakRefPrototype.cs b/Jint/Native/WeakRef/WeakRefPrototype.cs index 7b1d4c3618..b0be7daefb 100644 --- a/Jint/Native/WeakRef/WeakRefPrototype.cs +++ b/Jint/Native/WeakRef/WeakRefPrototype.cs @@ -43,12 +43,12 @@ protected override void Initialize() private JsValue Deref(JsValue thisObject, JsValue[] arguments) { - var weakRef = thisObject as WeakRefInstance; - if (weakRef is null) + if (thisObject is JsWeakRef weakRef) { - ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakRef"); + return weakRef.WeakRefDeref(); } - return weakRef.WeakRefDeref(); + ExceptionHelper.ThrowTypeError(_realm, "object must be a WeakRef"); + return default; } } From 568905202615af8c1ce47933c6b521baddda2fc8 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Mon, 31 Jul 2023 09:11:02 +0300 Subject: [PATCH 18/24] Rename ProxyInstance to JsProxy (#1604) --- Jint/Native/Function/FunctionInstance.cs | 2 +- Jint/Native/Json/JsonSerializer.cs | 2 +- Jint/Native/Object/ObjectPrototype.cs | 2 +- Jint/Native/Proxy/{ProxyInstance.cs => JsProxy.cs} | 4 ++-- Jint/Native/Proxy/ProxyConstructor.cs | 6 +++--- 5 files changed, 8 insertions(+), 8 deletions(-) rename Jint/Native/Proxy/{ProxyInstance.cs => JsProxy.cs} (99%) diff --git a/Jint/Native/Function/FunctionInstance.cs b/Jint/Native/Function/FunctionInstance.cs index 0670f6f135..44ec6525ac 100644 --- a/Jint/Native/Function/FunctionInstance.cs +++ b/Jint/Native/Function/FunctionInstance.cs @@ -257,7 +257,7 @@ internal Realm GetFunctionRealm(JsValue obj) return GetFunctionRealm(bindFunctionInstance.BoundTargetFunction); } - if (obj is ProxyInstance proxyInstance) + if (obj is JsProxy proxyInstance) { if (proxyInstance._handler is null) { diff --git a/Jint/Native/Json/JsonSerializer.cs b/Jint/Native/Json/JsonSerializer.cs index 3f2deb79a9..fe17770993 100644 --- a/Jint/Native/Json/JsonSerializer.cs +++ b/Jint/Native/Json/JsonSerializer.cs @@ -285,7 +285,7 @@ private static bool CanSerializesAsArray(ObjectInstance value) return true; } - if (value is ProxyInstance proxyInstance && CanSerializesAsArray(proxyInstance._target)) + if (value is JsProxy proxyInstance && CanSerializesAsArray(proxyInstance._target)) { return true; } diff --git a/Jint/Native/Object/ObjectPrototype.cs b/Jint/Native/Object/ObjectPrototype.cs index 6dfa827509..9dbaa826df 100644 --- a/Jint/Native/Object/ObjectPrototype.cs +++ b/Jint/Native/Object/ObjectPrototype.cs @@ -269,7 +269,7 @@ internal JsValue ToObjectString(JsValue thisObject, JsValue[] arguments) } else { - tag = (o is ProxyInstance ? ObjectClass.Object : o.Class).ToString(); + tag = (o is JsProxy ? ObjectClass.Object : o.Class).ToString(); } } diff --git a/Jint/Native/Proxy/ProxyInstance.cs b/Jint/Native/Proxy/JsProxy.cs similarity index 99% rename from Jint/Native/Proxy/ProxyInstance.cs rename to Jint/Native/Proxy/JsProxy.cs index db0f721663..463cf05529 100644 --- a/Jint/Native/Proxy/ProxyInstance.cs +++ b/Jint/Native/Proxy/JsProxy.cs @@ -5,7 +5,7 @@ namespace Jint.Native.Proxy { - internal sealed class ProxyInstance : ObjectInstance, IConstructor, ICallable + internal sealed class JsProxy : ObjectInstance, IConstructor, ICallable { internal ObjectInstance _target; internal ObjectInstance? _handler; @@ -27,7 +27,7 @@ internal sealed class ProxyInstance : ObjectInstance, IConstructor, ICallable private static readonly JsString KeyFunctionRevoke = new JsString("revoke"); private static readonly JsString KeyIsArray = new JsString("isArray"); - public ProxyInstance( + public JsProxy( Engine engine, ObjectInstance target, ObjectInstance handler) diff --git a/Jint/Native/Proxy/ProxyConstructor.cs b/Jint/Native/Proxy/ProxyConstructor.cs index 4d0950337d..d06fdcd237 100644 --- a/Jint/Native/Proxy/ProxyConstructor.cs +++ b/Jint/Native/Proxy/ProxyConstructor.cs @@ -50,7 +50,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) /// /// https://tc39.es/ecma262/#sec-proxy-target-handler /// - public ProxyInstance Construct(JsValue target, JsValue handler) + public JsProxy Construct(JsValue target, JsValue handler) { return ProxyCreate(target, handler); } @@ -78,7 +78,7 @@ JsValue Revoke(JsValue thisObject, JsValue[] arguments) /// /// https://tc39.es/ecma262/#sec-proxycreate /// - private ProxyInstance ProxyCreate(JsValue target, JsValue handler) + private JsProxy ProxyCreate(JsValue target, JsValue handler) { if (target is not ObjectInstance targetObject) { @@ -92,7 +92,7 @@ private ProxyInstance ProxyCreate(JsValue target, JsValue handler) return null; } - var p = new ProxyInstance(Engine, targetObject, targetHandler); + var p = new JsProxy(Engine, targetObject, targetHandler); return p; } } From cc63b205dc16888521c68c13396ae6ac4e96d6c4 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Mon, 31 Jul 2023 09:22:32 +0300 Subject: [PATCH 19/24] Rename PromiseInstance to JsPromise (#1605) --- Jint.Tests/Runtime/PromiseTests.cs | 2 +- Jint/Engine.Modules.cs | 2 +- Jint/Engine.cs | 2 +- Jint/JsValueExtensions.cs | 4 ++-- Jint/Native/Promise/{PromiseInstance.cs => JsPromise.cs} | 4 ++-- Jint/Native/Promise/PromiseConstructor.cs | 2 +- Jint/Native/Promise/PromiseOperations.cs | 4 ++-- Jint/Native/Promise/PromisePrototype.cs | 2 +- Jint/Native/ShadowRealm/ShadowRealm.cs | 2 +- Jint/Runtime/Host.cs | 4 ++-- Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs | 4 ++-- Jint/Runtime/Modules/CyclicModuleRecord.cs | 2 +- 12 files changed, 17 insertions(+), 17 deletions(-) rename Jint/Native/Promise/{PromiseInstance.cs => JsPromise.cs} (97%) diff --git a/Jint.Tests/Runtime/PromiseTests.cs b/Jint.Tests/Runtime/PromiseTests.cs index 16540a495a..eba125c8fb 100644 --- a/Jint.Tests/Runtime/PromiseTests.cs +++ b/Jint.Tests/Runtime/PromiseTests.cs @@ -128,7 +128,7 @@ public void PromiseCtor_ReturnsPromiseJsValue() var engine = new Engine(); var promise = engine.Evaluate("new Promise((resolve, reject)=>{});"); - Assert.IsType(promise); + Assert.IsType(promise); } [Fact(Timeout = 5000)] diff --git a/Jint/Engine.Modules.cs b/Jint/Engine.Modules.cs index c4677551c8..19690bf324 100644 --- a/Jint/Engine.Modules.cs +++ b/Jint/Engine.Modules.cs @@ -148,7 +148,7 @@ private JsValue EvaluateModule(string specifier, ModuleRecord module) } // This should instead be returned and resolved in ImportModule(specifier) only so Host.ImportModuleDynamically can use this promise - if (evaluationResult is not PromiseInstance promise) + if (evaluationResult is not JsPromise promise) { ExceptionHelper.ThrowInvalidOperationException($"Error while evaluating module: Module evaluation did not return a promise: {evaluationResult.Type}"); } diff --git a/Jint/Engine.cs b/Jint/Engine.cs index 0d58d105c6..7fa5e8317d 100644 --- a/Jint/Engine.cs +++ b/Jint/Engine.cs @@ -436,7 +436,7 @@ private Engine ScriptEvaluation(ScriptRecord scriptRecord) /// a Promise instance and functions to either resolve or reject it public ManualPromise RegisterPromise() { - var promise = new PromiseInstance(this) + var promise = new JsPromise(this) { _prototype = Realm.Intrinsics.Promise.PrototypeObject }; diff --git a/Jint/JsValueExtensions.cs b/Jint/JsValueExtensions.cs index b26975b940..ab861f194a 100644 --- a/Jint/JsValueExtensions.cs +++ b/Jint/JsValueExtensions.cs @@ -47,7 +47,7 @@ public static bool IsDate(this JsValue value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPromise(this JsValue value) { - return value is PromiseInstance; + return value is JsPromise; } [Pure] @@ -543,7 +543,7 @@ private static JsValue ThrowNotObject(JsValue value) /// inner value if Promise the value itself otherwise public static JsValue UnwrapIfPromise(this JsValue value) { - if (value is PromiseInstance promise) + if (value is JsPromise promise) { switch (promise.State) { diff --git a/Jint/Native/Promise/PromiseInstance.cs b/Jint/Native/Promise/JsPromise.cs similarity index 97% rename from Jint/Native/Promise/PromiseInstance.cs rename to Jint/Native/Promise/JsPromise.cs index 6d0c2057e4..06f5a83bb5 100644 --- a/Jint/Native/Promise/PromiseInstance.cs +++ b/Jint/Native/Promise/JsPromise.cs @@ -37,7 +37,7 @@ Action Reject ); -internal sealed class PromiseInstance : ObjectInstance +internal sealed class JsPromise : ObjectInstance { internal PromiseState State { get; private set; } @@ -47,7 +47,7 @@ internal sealed class PromiseInstance : ObjectInstance internal List PromiseRejectReactions = new(); internal List PromiseFulfillReactions = new(); - internal PromiseInstance(Engine engine) : base(engine) + internal JsPromise(Engine engine) : base(engine) { } diff --git a/Jint/Native/Promise/PromiseConstructor.cs b/Jint/Native/Promise/PromiseConstructor.cs index bd1c1259cb..63d7d3b568 100644 --- a/Jint/Native/Promise/PromiseConstructor.cs +++ b/Jint/Native/Promise/PromiseConstructor.cs @@ -79,7 +79,7 @@ public override ObjectInstance Construct(JsValue[] arguments, JsValue newTarget) var promise = OrdinaryCreateFromConstructor( newTarget, static intrinsics => intrinsics.Promise.PrototypeObject, - static (Engine engine, Realm _, object? _) => new PromiseInstance(engine)); + static (Engine engine, Realm _, object? _) => new JsPromise(engine)); var (resolve, reject) = promise.CreateResolvingFunctions(); try diff --git a/Jint/Native/Promise/PromiseOperations.cs b/Jint/Native/Promise/PromiseOperations.cs index 62eab70a09..ea7100642b 100644 --- a/Jint/Native/Promise/PromiseOperations.cs +++ b/Jint/Native/Promise/PromiseOperations.cs @@ -78,7 +78,7 @@ private static Action NewPromiseReactionJob(PromiseReaction reaction, JsValue va // d. Return Completion(thenCallResult). // .....Realm stuff.... // 6. Return the Record { [[Job]]: job, [[Realm]]: thenRealm }. - internal static Action NewPromiseResolveThenableJob(PromiseInstance promise, ObjectInstance thenable, ICallable thenMethod) + internal static Action NewPromiseResolveThenableJob(JsPromise promise, ObjectInstance thenable, ICallable thenMethod) { return () => { @@ -114,7 +114,7 @@ internal static JsValue TriggerPromiseReactions(Engine engine, List /// https://tc39.es/ecma262/#sec-finishdynamicimport /// - internal virtual void FinishDynamicImport(IScriptOrModule? referencingModule, string specifier, PromiseCapability promiseCapability, PromiseInstance innerPromise) + internal virtual void FinishDynamicImport(IScriptOrModule? referencingModule, string specifier, PromiseCapability promiseCapability, JsPromise innerPromise) { var onFulfilled = new ClrFunctionInstance(Engine, "", (thisObj, args) => { diff --git a/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs index 96d470239d..baaaa6b6e7 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintAwaitExpression.cs @@ -26,9 +26,9 @@ protected override object EvaluateInternal(EvaluationContext context) { var value = _awaitExpression.GetValue(context); - if (value is not PromiseInstance) + if (value is not JsPromise) { - var promiseInstance = new PromiseInstance(engine); + var promiseInstance = new JsPromise(engine); promiseInstance.Resolve(value); value = promiseInstance; } diff --git a/Jint/Runtime/Modules/CyclicModuleRecord.cs b/Jint/Runtime/Modules/CyclicModuleRecord.cs index 9bf7593a5d..05bea96634 100644 --- a/Jint/Runtime/Modules/CyclicModuleRecord.cs +++ b/Jint/Runtime/Modules/CyclicModuleRecord.cs @@ -426,7 +426,7 @@ private Completion ExecuteAsyncModule() var onFullfilled = new ClrFunctionInstance(_engine, "fulfilled", AsyncModuleExecutionFulfilled, 1, PropertyFlag.Configurable); var onRejected = new ClrFunctionInstance(_engine, "rejected", AsyncModuleExecutionRejected, 1, PropertyFlag.Configurable); - PromiseOperations.PerformPromiseThen(_engine, (PromiseInstance) capability.PromiseInstance, onFullfilled, onRejected, null); + PromiseOperations.PerformPromiseThen(_engine, (JsPromise) capability.PromiseInstance, onFullfilled, onRejected, null); return ExecuteModule(capability); } From 6eddc61db4ff872d993c034716e142795b922e38 Mon Sep 17 00:00:00 2001 From: adams85 <31276480+adams85@users.noreply.github.com> Date: Mon, 31 Jul 2023 14:22:54 +0200 Subject: [PATCH 20/24] Implement workarounds for regex parsing known issues (#1603) --- .../Test262Harness.settings.json | 4 - Jint.Tests/Runtime/RegExpTests.cs | 39 +++++++- Jint/Native/RegExp/RegExpPrototype.cs | 94 ++++++++++--------- Jint/Shims.cs | 41 ++++++++ 4 files changed, 129 insertions(+), 49 deletions(-) create mode 100644 Jint/Shims.cs diff --git a/Jint.Tests.Test262/Test262Harness.settings.json b/Jint.Tests.Test262/Test262Harness.settings.json index 0140de4ee3..54a56f0059 100644 --- a/Jint.Tests.Test262/Test262Harness.settings.json +++ b/Jint.Tests.Test262/Test262Harness.settings.json @@ -44,14 +44,10 @@ "language/literals/regexp/named-groups/forward-reference.js", // RegExp handling problems - "built-ins/RegExp/match-indices/indices-array-unicode-property-names.js", "built-ins/RegExp/named-groups/non-unicode-match.js", "built-ins/RegExp/named-groups/non-unicode-property-names-valid.js", - "built-ins/RegExp/named-groups/non-unicode-property-names.js", "built-ins/RegExp/named-groups/unicode-match.js", "built-ins/RegExp/named-groups/unicode-property-names-valid.js", - "built-ins/RegExp/named-groups/unicode-property-names.js", - "built-ins/RegExp/prototype/Symbol.replace/named-groups.js", "built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T6.js", "built-ins/String/prototype/split/separator-regexp.js", "language/literals/regexp/u-case-mapping.js", diff --git a/Jint.Tests/Runtime/RegExpTests.cs b/Jint.Tests/Runtime/RegExpTests.cs index b9f08ea3d7..af27f11aa8 100644 --- a/Jint.Tests/Runtime/RegExpTests.cs +++ b/Jint.Tests/Runtime/RegExpTests.cs @@ -35,7 +35,7 @@ public void CanNotBreakEngineWithLongRunningRegExp() public void PreventsInfiniteLoop() { var engine = new Engine(); - var result = (ArrayInstance)engine.Evaluate("'x'.match(/|/g);"); + var result = (ArrayInstance) engine.Evaluate("'x'.match(/|/g);"); Assert.Equal((uint) 2, result.Length); Assert.Equal("", result[0]); Assert.Equal("", result[1]); @@ -103,4 +103,41 @@ public void ShouldProduceCorrectSourceForSlashEscapes() var source = engine.Evaluate(@"/\/\//.source"); Assert.Equal("\\/\\/", source); } + + [Theory] + [InlineData("", "/()/ug", new[] { "" }, new[] { 0 })] + [InlineData("💩", "/()/ug", new[] { "", "" }, new[] { 0, 2 })] + [InlineData("ᴜⁿᵢ𝒸ₒᵈₑ is a 💩", "/i?/ug", + new[] { "", "", "", "", "", "", "", "", "i", "", "", "", "", "", "" }, + new[] { 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16 })] + public void ShouldNotMatchEmptyStringsWithinSurrogatePairsInUnicodeMode(string input, string pattern, string[] expectedCaptures, int[] expectedIndices) + { + var engine = new Engine(); + var matches = engine.Evaluate($"[...'{input}'.matchAll({pattern})]").AsArray(); + Assert.Equal((ulong) expectedCaptures.Length, matches.Length); + Assert.Equal(expectedCaptures, matches.Select((m, i) => m.Get(0).AsString())); + Assert.Equal(expectedIndices, matches.Select(m => m.Get("index").AsInteger())); + } + + [Fact] + public void ShouldAllowProblematicGroupNames() + { + var engine = new Engine(); + + var match = engine.Evaluate("'abc'.match(/(?<$group>b)/)").AsArray(); + var groups = match.Get("groups").AsObject(); + Assert.Equal(new[] { "$group" }, groups.GetOwnPropertyKeys().Select(k => k.AsString())); + Assert.Equal("b", groups["$group"]); + + var result = engine.Evaluate("'abc'.replace(/(?<$group>b)/g, '-$<$group>-')").AsString(); + Assert.Equal("a-b-c", result); + } + + [Fact] + public void Issue506() + { + var engine = new Engine(); + var result = engine.Evaluate("/[^]?(:[rp][el]a[\\w-]+)[^]/.test(':reagent-')").AsBoolean(); + Assert.True(result); + } } diff --git a/Jint/Native/RegExp/RegExpPrototype.cs b/Jint/Native/RegExp/RegExpPrototype.cs index 265b6fb9f1..65fbe03f07 100644 --- a/Jint/Native/RegExp/RegExpPrototype.cs +++ b/Jint/Native/RegExp/RegExpPrototype.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using System.Text; using System.Text.RegularExpressions; using Jint.Collections; using Jint.Native.Number; @@ -824,7 +825,7 @@ internal static JsValue RegExpExec(ObjectInstance r, string s) var exec = r.Get(PropertyExec); if (exec is ICallable callable) { - var result = callable.Call(r, new JsValue[] { s }); + var result = callable.Call(r, new JsValue[] { s }); if (!result.IsNull() && !result.IsObject()) { ExceptionHelper.ThrowTypeError(r.Engine.Realm); @@ -902,31 +903,47 @@ private static JsValue RegExpBuiltinExec(JsRegExp R, string s) // the stateful version Match match; - while (true) + + if (lastIndex > length) { - if (lastIndex > length) - { - R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); - return Null; - } + R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); + return Null; + } - match = R.Value.Match(s, (int) lastIndex); - var success = match.Success && (!sticky || match.Index == (int) lastIndex); - if (!success) + var startAt = (int) lastIndex; + while (true) + { + match = R.Value.Match(s, startAt); + + // The conversion of Unicode regex patterns to .NET Regex has some flaws: + // when the pattern may match empty strings, the adapted Regex will return empty string matches + // in the middle of surrogate pairs. As a best effort solution, we remove these fake positive matches. + // (See also: https://github.com/sebastienros/esprima-dotnet/pull/364#issuecomment-1606045259) + + if (match.Success + && fullUnicode + && match.Length == 0 + && 0 < match.Index && match.Index < s.Length + && char.IsHighSurrogate(s[match.Index - 1]) && char.IsLowSurrogate(s[match.Index])) { - R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); - return Null; + startAt++; + continue; } break; } - var e = match.Index + match.Length; - if (fullUnicode) + var success = match.Success && (!sticky || match.Index == (int) lastIndex); + if (!success) { - e = GetStringIndex(s, e); + R.Set(JsRegExp.PropertyLastIndex, JsNumber.PositiveZero, true); + return Null; } + var e = match.Index + match.Length; + + // NOTE: Even in Unicode mode, we don't need to translate indices as .NET regexes always return code unit indices. + if (global || sticky) { R.Set(JsRegExp.PropertyLastIndex, e, true); @@ -935,35 +952,6 @@ private static JsValue RegExpBuiltinExec(JsRegExp R, string s) return CreateReturnValueArray(R.Engine, matcher, match, s, fullUnicode, hasIndices); } - /// - /// https://tc39.es/ecma262/#sec-getstringindex - /// - private static int GetStringIndex(string s, int codePointIndex) - { - if (s.Length == 0) - { - return 0; - } - - var len = s.Length; - var codeUnitCount = 0; - var codePointCount = 0; - - while (codeUnitCount < len) - { - if (codePointCount == codePointIndex) - { - return codeUnitCount; - } - - var isSurrogatePair = char.IsSurrogatePair(s, codeUnitCount); - codeUnitCount += isSurrogatePair ? 2 : 1; - codePointCount += 1; - } - - return len; - } - private static JsArray CreateReturnValueArray( Engine engine, Regex regex, @@ -1080,6 +1068,24 @@ private static JsValue GetMatchIndexPair(Engine engine, string s, JsNumber[] mat return null; } + + // The characters allowed in group names differs between the JS and .NET regex engines. + // For example the group name "$group" is valid in JS but invalid in .NET. + // As a workaround for this issue, the parser make an attempt to encode the problematic group names to + // names which are valid in .NET and probably won't collide with other group names present in the pattern + // (https://github.com/sebastienros/esprima-dotnet/blob/v3.0.0-rc-03/src/Esprima/Scanner.RegExpParser.cs#L942). + // We need to decode such group names. + const string encodedGroupNamePrefix = "__utf8_"; + if (groupNameFromNumber.StartsWith(encodedGroupNamePrefix, StringComparison.Ordinal)) + { + try + { + var bytes = groupNameFromNumber.AsSpan(encodedGroupNamePrefix.Length).BytesFromHexString(); + groupNameFromNumber = Encoding.UTF8.GetString(bytes); + } + catch { /* intentional no-op */ } + } + return groupNameFromNumber; } diff --git a/Jint/Shims.cs b/Jint/Shims.cs new file mode 100644 index 0000000000..9327192f20 --- /dev/null +++ b/Jint/Shims.cs @@ -0,0 +1,41 @@ +namespace Jint; + +internal static class Shims +{ + public static byte[] BytesFromHexString(this ReadOnlySpan value) + { +#if NET6_0_OR_GREATER + return Convert.FromHexString(value); +#else + if ((value.Length & 1) != 0) + { + throw new FormatException(); + } + + var byteCount = value.Length >> 1; + var result = new byte[byteCount]; + var index = 0; + for (var i = 0; i < byteCount; i++) + { + int hi, lo; + if ((hi = GetDigitValue(value[index++])) < 0 + || (lo = GetDigitValue(value[index++])) < 0) + { + throw new FormatException(); + } + + result[i] = (byte) (hi << 4 | lo); + } + + return result; + + static int GetDigitValue(char ch) => ch switch + { + >= '0' and <= '9' => ch - 0x30, + >= 'a' and <= 'f' => ch - 0x57, + >= 'A' and <= 'F' => ch - 0x37, + _ => -1 + }; +#endif + } +} From 2ebfedf76e88e89a9a0f7e3f1f7e5701e49df2ba Mon Sep 17 00:00:00 2001 From: Lehonti Ramos <17771375+Lehonti@users.noreply.github.com> Date: Thu, 3 Aug 2023 08:59:07 +0200 Subject: [PATCH 21/24] Added readonly modifier to fields that aren't being changed (#1610) Co-authored-by: Lehonti Ramos --- Jint.Benchmark/DromaeoBenchmark.cs | 2 +- Jint.Benchmark/EngineConstructionBenchmark.cs | 2 +- .../ExtensionMethods/ObservableExtensions.cs | 8 ++++---- Jint.Tests/Runtime/GenericMethodTests.cs | 2 +- Jint.Tests/Runtime/InteropTests.MemberAccess.cs | 2 +- Jint.Tests/Runtime/JsValueConversionTests.cs | 2 +- Jint/Agent.cs | 2 +- Jint/Native/Number/Dtoa/Bignum.cs | 13 ++++++++----- Jint/Runtime/Interpreter/JintStatementList.cs | 2 +- Jint/Runtime/Modules/CyclicModuleRecord.cs | 2 +- 10 files changed, 20 insertions(+), 17 deletions(-) diff --git a/Jint.Benchmark/DromaeoBenchmark.cs b/Jint.Benchmark/DromaeoBenchmark.cs index 8e81a7a845..ad77dd7cab 100644 --- a/Jint.Benchmark/DromaeoBenchmark.cs +++ b/Jint.Benchmark/DromaeoBenchmark.cs @@ -16,7 +16,7 @@ public class DromaeoBenchmark {"dromaeo-string-base64", null} }; - private Dictionary _prepared = new(); + private readonly Dictionary _prepared = new(); private Engine engine; diff --git a/Jint.Benchmark/EngineConstructionBenchmark.cs b/Jint.Benchmark/EngineConstructionBenchmark.cs index c6751cd12b..56522b1307 100644 --- a/Jint.Benchmark/EngineConstructionBenchmark.cs +++ b/Jint.Benchmark/EngineConstructionBenchmark.cs @@ -21,4 +21,4 @@ public double BuildEngine() var engine = new Engine(); return engine.Evaluate(_program).AsNumber(); } -} \ No newline at end of file +} diff --git a/Jint.Tests/Runtime/ExtensionMethods/ObservableExtensions.cs b/Jint.Tests/Runtime/ExtensionMethods/ObservableExtensions.cs index b45a0f794a..d770ee9edb 100644 --- a/Jint.Tests/Runtime/ExtensionMethods/ObservableExtensions.cs +++ b/Jint.Tests/Runtime/ExtensionMethods/ObservableExtensions.cs @@ -6,7 +6,7 @@ internal class Subscribe : IObserver private readonly Action onError; private readonly Action onCompleted; - int isStopped = 0; + readonly int isStopped = 0; public Subscribe(Action onNext, Action onError, Action onCompleted) { @@ -65,7 +65,7 @@ public static IObservable Where(this IObservable source, Func : IObservable { - private List> observers = new List>(); + private readonly List> observers = new List>(); public T Last { get; private set; } @@ -78,8 +78,8 @@ public IDisposable Subscribe(IObserver observer) private class Unsubscriber : IDisposable { - private List> _observers; - private IObserver _observer; + private readonly List> _observers; + private readonly IObserver _observer; public Unsubscriber(List> observers, IObserver observer) { diff --git a/Jint.Tests/Runtime/GenericMethodTests.cs b/Jint.Tests/Runtime/GenericMethodTests.cs index ca2cadc071..2ce30cb441 100644 --- a/Jint.Tests/Runtime/GenericMethodTests.cs +++ b/Jint.Tests/Runtime/GenericMethodTests.cs @@ -140,7 +140,7 @@ public void Foo(U u) public class TestGenericBaseClass { - private System.Collections.Generic.List _list = new System.Collections.Generic.List(); + private readonly System.Collections.Generic.List _list = new System.Collections.Generic.List(); public int Count { diff --git a/Jint.Tests/Runtime/InteropTests.MemberAccess.cs b/Jint.Tests/Runtime/InteropTests.MemberAccess.cs index 076b254d99..404ca08f1e 100644 --- a/Jint.Tests/Runtime/InteropTests.MemberAccess.cs +++ b/Jint.Tests/Runtime/InteropTests.MemberAccess.cs @@ -200,7 +200,7 @@ private static class EchoService private class CustomDictionary : IDictionary { - Dictionary _dictionary = new Dictionary(); + readonly Dictionary _dictionary = new Dictionary(); public TValue this[string key] { diff --git a/Jint.Tests/Runtime/JsValueConversionTests.cs b/Jint.Tests/Runtime/JsValueConversionTests.cs index 5e61c1df8e..386684c0b2 100644 --- a/Jint.Tests/Runtime/JsValueConversionTests.cs +++ b/Jint.Tests/Runtime/JsValueConversionTests.cs @@ -5,7 +5,7 @@ namespace Jint.Tests.Runtime { public class JsValueConversionTests { - private Engine _engine; + private readonly Engine _engine; public JsValueConversionTests() { diff --git a/Jint/Agent.cs b/Jint/Agent.cs index 85d4640303..44c8f5c55c 100644 --- a/Jint/Agent.cs +++ b/Jint/Agent.cs @@ -7,7 +7,7 @@ namespace Jint; /// internal sealed class Agent { - private List _keptAlive = new(); + private readonly List _keptAlive = new(); public void AddToKeptObjects(JsValue target) { diff --git a/Jint/Native/Number/Dtoa/Bignum.cs b/Jint/Native/Number/Dtoa/Bignum.cs index cddbd525e4..ac874ccbe3 100644 --- a/Jint/Native/Number/Dtoa/Bignum.cs +++ b/Jint/Native/Number/Dtoa/Bignum.cs @@ -24,7 +24,7 @@ internal sealed class Bignum // grow. There are no checks if the stack-allocated space is sufficient. private const int kBigitCapacity = kMaxSignificantBits / kBigitSize; - private uint[] bigits_ = new uint[kBigitCapacity]; + private readonly uint[] bigits_ = new uint[kBigitCapacity]; // The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize). private int exponent_; @@ -429,7 +429,8 @@ internal void MultiplyByUInt32(uint factor) internal void MultiplyByUInt64(ulong factor) { if (factor == 1) return; - if (factor == 0) { + if (factor == 0) + { Zero(); return; } @@ -437,7 +438,8 @@ internal void MultiplyByUInt64(ulong factor) ulong carry = 0; ulong low = factor & 0xFFFFFFFF; ulong high = factor >> 32; - for (int i = 0; i < used_digits_; ++i) { + for (int i = 0; i < used_digits_; ++i) + { ulong product_low = low * bigits_[i]; ulong product_high = high * bigits_[i]; ulong tmp = (carry & kBigitMask) + product_low; @@ -445,7 +447,8 @@ internal void MultiplyByUInt64(ulong factor) carry = (carry >> kBigitSize) + (tmp >> kBigitSize) + (product_high << (32 - kBigitSize)); } - while (carry != 0) { + while (carry != 0) + { EnsureCapacity(used_digits_ + 1); bigits_[used_digits_] = (uint) (carry & kBigitMask); used_digits_++; @@ -655,4 +658,4 @@ void Square() Clamp(); } } -} \ No newline at end of file +} diff --git a/Jint/Runtime/Interpreter/JintStatementList.cs b/Jint/Runtime/Interpreter/JintStatementList.cs index a909ef9395..74f84a3e90 100644 --- a/Jint/Runtime/Interpreter/JintStatementList.cs +++ b/Jint/Runtime/Interpreter/JintStatementList.cs @@ -19,7 +19,7 @@ private sealed class Pair private Pair[]? _jintStatements; private bool _initialized; - private uint _index; + private readonly uint _index; private readonly bool _generator; public JintStatementList(IFunction function) diff --git a/Jint/Runtime/Modules/CyclicModuleRecord.cs b/Jint/Runtime/Modules/CyclicModuleRecord.cs index 05bea96634..eedaf497be 100644 --- a/Jint/Runtime/Modules/CyclicModuleRecord.cs +++ b/Jint/Runtime/Modules/CyclicModuleRecord.cs @@ -29,7 +29,7 @@ public abstract class CyclicModuleRecord : ModuleRecord protected bool _hasTLA; private bool _asyncEvaluation; private PromiseCapability _topLevelCapability; - private List _asyncParentModules; + private readonly List _asyncParentModules; private int _asyncEvalOrder; private int _pendingAsyncDependencies; From 0ebf7cd5a8b6de05a341fb19dcad67414a56a2b1 Mon Sep 17 00:00:00 2001 From: viruscamp Date: Sun, 6 Aug 2023 15:34:31 +0800 Subject: [PATCH 22/24] Support explicit interface and hidden member of super class (#1613) --- .../Runtime/InteropExplicitTypeTests.cs | 186 ++++++++++++++++++ Jint.Tests/Runtime/InteropTests.cs | 4 +- Jint/Native/JsValue.cs | 10 +- Jint/Options.cs | 20 +- .../Specialized/ReflectionDescriptor.cs | 3 +- .../Runtime/Interop/DefaultObjectConverter.cs | 6 +- .../Interop/MethodInfoFunctionInstance.cs | 10 +- Jint/Runtime/Interop/ObjectWrapper.cs | 48 +++-- .../Interop/Reflection/ReflectionAccessor.cs | 2 + 9 files changed, 267 insertions(+), 22 deletions(-) create mode 100644 Jint.Tests/Runtime/InteropExplicitTypeTests.cs diff --git a/Jint.Tests/Runtime/InteropExplicitTypeTests.cs b/Jint.Tests/Runtime/InteropExplicitTypeTests.cs new file mode 100644 index 0000000000..9aeaea3494 --- /dev/null +++ b/Jint.Tests/Runtime/InteropExplicitTypeTests.cs @@ -0,0 +1,186 @@ +using System.Reflection; + +namespace Jint.Tests.Runtime +{ + public class InteropExplicitTypeTests + { + public interface I1 + { + string Name { get; } + } + + public class Super + { + public string Name { get; } = "Super"; + } + + public class CI1 : Super, I1 + { + public new string Name { get; } = "CI1"; + + string I1.Name { get; } = "CI1 as I1"; + } + + public class Indexer + { + private readonly T t; + public Indexer(T t) + { + this.t = t; + } + public T this[int index] + { + get { return t; } + } + } + + public class InterfaceHolder + { + public InterfaceHolder() + { + var ci1 = new CI1(); + this.ci1 = ci1; + this.i1 = ci1; + this.super = ci1; + + this.IndexerCI1 = new Indexer(ci1); + this.IndexerI1 = new Indexer(ci1); + this.IndexerSuper = new Indexer(ci1); + } + + public readonly CI1 ci1; + public readonly I1 i1; + public readonly Super super; + + public CI1 CI1 { get => ci1; } + public I1 I1 { get => i1; } + public Super Super { get => super; } + + public CI1 GetCI1() => ci1; + public I1 GetI1() => i1; + public Super GetSuper() => super; + + public Indexer IndexerCI1 { get; } + public Indexer IndexerI1 { get; } + public Indexer IndexerSuper { get; } + + } + + private readonly Engine _engine; + private readonly InterfaceHolder holder; + + public InteropExplicitTypeTests() + { + holder = new InterfaceHolder(); + _engine = new Engine(cfg => cfg.AllowClr( + typeof(Console).GetTypeInfo().Assembly, + typeof(File).GetTypeInfo().Assembly)) + .SetValue("log", new Action(Console.WriteLine)) + .SetValue("assert", new Action(Assert.True)) + .SetValue("equal", new Action(Assert.Equal)) + .SetValue("holder", holder) + ; + } + [Fact] + public void EqualTest() + { + Assert.Equal(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.i1")); + Assert.NotEqual(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.ci1")); + + Assert.Equal(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.super")); + Assert.NotEqual(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.ci1")); + } + + [Fact] + public void ExplicitInterfaceFromField() + { + Assert.Equal(holder.i1.Name, _engine.Evaluate("holder.i1.Name")); + Assert.NotEqual(holder.i1.Name, _engine.Evaluate("holder.ci1.Name")); + } + + [Fact] + public void ExplicitInterfaceFromProperty() + { + Assert.Equal(holder.I1.Name, _engine.Evaluate("holder.I1.Name")); + Assert.NotEqual(holder.I1.Name, _engine.Evaluate("holder.CI1.Name")); + } + + [Fact] + public void ExplicitInterfaceFromMethod() + { + Assert.Equal(holder.GetI1().Name, _engine.Evaluate("holder.GetI1().Name")); + Assert.NotEqual(holder.GetI1().Name, _engine.Evaluate("holder.GetCI1().Name")); + } + + [Fact] + public void ExplicitInterfaceFromIndexer() + { + Assert.Equal(holder.IndexerI1[0].Name, _engine.Evaluate("holder.IndexerI1[0].Name")); + } + + + [Fact] + public void SuperClassFromField() + { + Assert.Equal(holder.super.Name, _engine.Evaluate("holder.super.Name")); + Assert.NotEqual(holder.super.Name, _engine.Evaluate("holder.ci1.Name")); + } + + [Fact] + public void SuperClassFromProperty() + { + Assert.Equal(holder.Super.Name, _engine.Evaluate("holder.Super.Name")); + Assert.NotEqual(holder.Super.Name, _engine.Evaluate("holder.CI1.Name")); + } + + [Fact] + public void SuperClassFromMethod() + { + Assert.Equal(holder.GetSuper().Name, _engine.Evaluate("holder.GetSuper().Name")); + Assert.NotEqual(holder.GetSuper().Name, _engine.Evaluate("holder.GetCI1().Name")); + } + + [Fact] + public void SuperClassFromIndexer() + { + Assert.Equal(holder.IndexerSuper[0].Name, _engine.Evaluate("holder.IndexerSuper[0].Name")); + } + + public struct NullabeStruct: I1 + { + public NullabeStruct() + { + } + public string name = "NullabeStruct"; + + public string Name { get => name; } + + string I1.Name { get => "NullabeStruct as I1"; } + } + + public class NullableHolder + { + public I1? I1 { get; set; } + public NullabeStruct? NullabeStruct { get; set; } + } + + [Fact] + public void TestNullable() + { + var nullableHolder = new NullableHolder(); + _engine.SetValue("nullableHolder", nullableHolder); + _engine.SetValue("nullabeStruct", new NullabeStruct()); + + Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct"), Native.JsValue.Null); + _engine.Evaluate("nullableHolder.NullabeStruct = nullabeStruct"); + Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct.Name"), nullableHolder.NullabeStruct?.Name); + } + + [Fact] + public void TestUnwrapClr() + { + Assert.NotEqual(holder.CI1.Name, _engine.Evaluate("holder.I1.Name")); + Assert.Equal(holder.CI1.Name, _engine.Evaluate("unwrapClr(holder.I1).Name")); + } + } +} diff --git a/Jint.Tests/Runtime/InteropTests.cs b/Jint.Tests/Runtime/InteropTests.cs index 771eab8833..07f345a3c5 100644 --- a/Jint.Tests/Runtime/InteropTests.cs +++ b/Jint.Tests/Runtime/InteropTests.cs @@ -849,7 +849,7 @@ public void CanAddArrayPrototypeForArrayLikeClrObjects() { var e = new Engine(cfg => cfg .AllowClr(typeof(Person).Assembly) - .SetWrapObjectHandler((engine, target) => + .SetWrapObjectHandler((engine, target, type) => { var instance = new ObjectWrapper(engine, target); if (instance.IsArrayLike) @@ -884,7 +884,7 @@ public void CanSetIsConcatSpreadableForArrays() { var engine = new Engine(opt => { - opt.SetWrapObjectHandler((eng, obj) => + opt.SetWrapObjectHandler((eng, obj, type) => { var wrapper = new ObjectWrapper(eng, obj); if (wrapper.IsArrayLike) diff --git a/Jint/Native/JsValue.cs b/Jint/Native/JsValue.cs index 0a2067b100..6499e0d58d 100644 --- a/Jint/Native/JsValue.cs +++ b/Jint/Native/JsValue.cs @@ -110,6 +110,14 @@ public Types Type /// Creates a valid instance from any instance /// public static JsValue FromObject(Engine engine, object? value) + { + return FromObjectWithType(engine, value, null); + } + + /// + /// Creates a valid instance from any instance, with a type + /// + public static JsValue FromObjectWithType(Engine engine, object? value, Type? type) { if (value is null) { @@ -132,7 +140,7 @@ public static JsValue FromObject(Engine engine, object? value) } } - if (DefaultObjectConverter.TryConvert(engine, value, out var defaultConversion)) + if (DefaultObjectConverter.TryConvert(engine, value, type, out var defaultConversion)) { return defaultConversion; } diff --git a/Jint/Options.cs b/Jint/Options.cs index 157cf4247e..63f57f2769 100644 --- a/Jint/Options.cs +++ b/Jint/Options.cs @@ -15,7 +15,7 @@ namespace Jint { public delegate JsValue? MemberAccessorDelegate(Engine engine, object target, string member); - public delegate ObjectInstance? WrapObjectDelegate(Engine engine, object target); + public delegate ObjectInstance? WrapObjectDelegate(Engine engine, object target, Type? type); public delegate bool ExceptionHandlerDelegate(Exception exception); @@ -120,6 +120,22 @@ internal void Apply(Engine engine) (thisObj, arguments) => new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden)); + engine.Realm.GlobalObject.SetProperty("unwrapClr", new PropertyDescriptor(new ClrFunctionInstance( + engine, + "unwrapClr", + (thisObj, arguments) => + { + var arg = arguments.At(0); + if (arg is ObjectWrapper obj) + { + return new ObjectWrapper(engine, obj.Target); + } + else + { + return arg; + } + }), + PropertyFlag.AllForbidden)); } if (Interop.ExtensionMethodTypes.Count > 0) @@ -282,7 +298,7 @@ public class InteropOptions /// ObjectInstance using class ObjectWrapper. This function can be used to /// change the behavior. /// - public WrapObjectDelegate WrapObjectHandler { get; set; } = static (engine, target) => new ObjectWrapper(engine, target); + public WrapObjectDelegate WrapObjectHandler { get; set; } = static (engine, target, type) => new ObjectWrapper(engine, target, type); /// /// diff --git a/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs b/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs index d35d4eef7b..4885b4f52f 100644 --- a/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs +++ b/Jint/Runtime/Descriptors/Specialized/ReflectionDescriptor.cs @@ -29,7 +29,8 @@ protected internal override JsValue? CustomValue get { var value = _reflectionAccessor.GetValue(_engine, _target); - return JsValue.FromObject(_engine, value); + var type = _reflectionAccessor.MemberType; + return JsValue.FromObjectWithType(_engine, value, type); } set { diff --git a/Jint/Runtime/Interop/DefaultObjectConverter.cs b/Jint/Runtime/Interop/DefaultObjectConverter.cs index 81ba34cc5e..8c3a647389 100644 --- a/Jint/Runtime/Interop/DefaultObjectConverter.cs +++ b/Jint/Runtime/Interop/DefaultObjectConverter.cs @@ -34,10 +34,10 @@ internal static class DefaultObjectConverter } }; - public static bool TryConvert(Engine engine, object value, [NotNullWhen(true)] out JsValue? result) + public static bool TryConvert(Engine engine, object value, Type? type, [NotNullWhen(true)] out JsValue? result) { result = null; - var valueType = value.GetType(); + Type valueType = ObjectWrapper.ClrType(value, type); var typeMappers = _typeMappers; @@ -109,7 +109,7 @@ public static bool TryConvert(Engine engine, object value, [NotNullWhen(true)] o } else { - var wrapped = engine.Options.Interop.WrapObjectHandler.Invoke(engine, value); + var wrapped = engine.Options.Interop.WrapObjectHandler.Invoke(engine, value, type); result = wrapped; if (engine.Options.Interop.TrackObjectWrapperIdentity && wrapped is not null) diff --git a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs index 3ad902ac52..81deb326ee 100644 --- a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs +++ b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs @@ -220,6 +220,12 @@ JsValue[] ArgumentProvider(MethodDescriptor method) continue; } + Type? returnType = null; + if (method.Method is MethodInfo methodInfo) + { + returnType = methodInfo.ReturnType; + } + // todo: cache method info try { @@ -227,10 +233,10 @@ JsValue[] ArgumentProvider(MethodDescriptor method) { var genericMethodInfo = resolvedMethod; var result = genericMethodInfo.Invoke(thisObj, parameters); - return FromObject(Engine, result); + return FromObjectWithType(Engine, result, returnType); } - return FromObject(Engine, method.Method.Invoke(thisObj, parameters)); + return FromObjectWithType(Engine, method.Method.Invoke(thisObj, parameters), returnType); } catch (TargetInvocationException exception) { diff --git a/Jint/Runtime/Interop/ObjectWrapper.cs b/Jint/Runtime/Interop/ObjectWrapper.cs index f6f5ad67cb..74eb62a65e 100644 --- a/Jint/Runtime/Interop/ObjectWrapper.cs +++ b/Jint/Runtime/Interop/ObjectWrapper.cs @@ -1,3 +1,4 @@ +using System; using System.Collections; using System.Globalization; using System.Reflection; @@ -10,18 +11,20 @@ namespace Jint.Runtime.Interop { - /// - /// Wraps a CLR instance - /// - public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable + /// + /// Wraps a CLR instance + /// + public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable { private readonly TypeDescriptor _typeDescriptor; + private readonly Type _clrType; - public ObjectWrapper(Engine engine, object obj) + public ObjectWrapper(Engine engine, object obj, Type? type = null) : base(engine) { Target = obj; - _typeDescriptor = TypeDescriptor.Get(obj.GetType()); + _clrType = ClrType(obj, type); + _typeDescriptor = TypeDescriptor.Get(_clrType); if (_typeDescriptor.LengthProperty is not null) { // create a forwarder to produce length from Count or Length if one of them is present @@ -48,7 +51,7 @@ public override bool Set(JsValue property, JsValue value, JsValue receiver) if (_properties is null || !_properties.ContainsKey(member)) { // can try utilize fast path - var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member, forWrite: true); + var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member, forWrite: true); if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor)) { @@ -160,7 +163,7 @@ private IEnumerable EnumerateOwnPropertyKeys(Types types) else if (includeStrings) { // we take public properties and fields - var type = Target.GetType(); + var type = _clrType; foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public)) { var indexParameters = p.GetIndexParameters(); @@ -232,7 +235,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property) return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable); } - var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member); + var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member); var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary); if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined)) { @@ -259,6 +262,26 @@ public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object tar return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target); } + public static Type ClrType(object obj, Type? type) + { + if (type is null || type == typeof(object)) + { + return obj.GetType(); + } + else + { + var underlyingType = Nullable.GetUnderlyingType(type); + if (underlyingType is not null) + { + return underlyingType; + } + else + { + return type; + } + } + } + private static JsValue Iterator(JsValue thisObject, JsValue[] arguments) { var wrapper = (ObjectWrapper) thisObject; @@ -296,12 +319,15 @@ public bool Equals(ObjectWrapper? other) return true; } - return Equals(Target, other.Target); + return Equals(Target, other.Target) && Equals(_clrType, other._clrType); } public override int GetHashCode() { - return Target?.GetHashCode() ?? 0; + var hashCode = -1468639730; + hashCode = hashCode * -1521134295 + Target.GetHashCode(); + hashCode = hashCode * -1521134295 + _clrType.GetHashCode(); + return hashCode; } private sealed class DictionaryIterator : IteratorInstance diff --git a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs index d626bc90f2..ea28ec602e 100644 --- a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs @@ -16,6 +16,8 @@ internal abstract class ReflectionAccessor private readonly object? _memberName; private readonly PropertyInfo? _indexer; + public Type MemberType => _memberType; + protected ReflectionAccessor( Type memberType, object? memberName, From e9ace1a5a130b49ee020e316e87a4d6b0d1076db Mon Sep 17 00:00:00 2001 From: adams85 <31276480+adams85@users.noreply.github.com> Date: Mon, 7 Aug 2023 23:21:28 +0200 Subject: [PATCH 23/24] Fix capturing group numbering bug and a few more regex-related issues (#1614) --- .../Test262Harness.settings.json | 6 -- Jint/Jint.csproj | 2 +- Jint/Native/RegExp/JsRegExp.cs | 3 + Jint/Native/RegExp/RegExpConstructor.cs | 12 +-- Jint/Native/RegExp/RegExpPrototype.cs | 80 ++++++++----------- .../Expressions/JintLiteralExpression.cs | 7 +- 6 files changed, 47 insertions(+), 63 deletions(-) diff --git a/Jint.Tests.Test262/Test262Harness.settings.json b/Jint.Tests.Test262/Test262Harness.settings.json index 54a56f0059..88fa50bd24 100644 --- a/Jint.Tests.Test262/Test262Harness.settings.json +++ b/Jint.Tests.Test262/Test262Harness.settings.json @@ -44,14 +44,8 @@ "language/literals/regexp/named-groups/forward-reference.js", // RegExp handling problems - "built-ins/RegExp/named-groups/non-unicode-match.js", - "built-ins/RegExp/named-groups/non-unicode-property-names-valid.js", - "built-ins/RegExp/named-groups/unicode-match.js", - "built-ins/RegExp/named-groups/unicode-property-names-valid.js", "built-ins/RegExp/prototype/exec/S15.10.6.2_A1_T6.js", - "built-ins/String/prototype/split/separator-regexp.js", "language/literals/regexp/u-case-mapping.js", - "language/literals/regexp/u-surrogate-pairs-atom-escape-decimal.js", // requires investigation how to process complex function name evaluation for property "built-ins/Function/prototype/toString/method-computed-property-name.js", diff --git a/Jint/Jint.csproj b/Jint/Jint.csproj index 5dfab6951e..cc591bc37b 100644 --- a/Jint/Jint.csproj +++ b/Jint/Jint.csproj @@ -16,7 +16,7 @@ - + diff --git a/Jint/Native/RegExp/JsRegExp.cs b/Jint/Native/RegExp/JsRegExp.cs index bacd74c5cb..629fabae0f 100644 --- a/Jint/Native/RegExp/JsRegExp.cs +++ b/Jint/Native/RegExp/JsRegExp.cs @@ -1,4 +1,5 @@ using System.Text.RegularExpressions; +using Esprima; using Jint.Native.Object; using Jint.Runtime; using Jint.Runtime.Descriptors; @@ -62,6 +63,8 @@ public string Flags } } + public RegExpParseResult ParseResult { get; set; } + public bool DotAll { get; private set; } public bool Global { get; private set; } public bool Indices { get; private set; } diff --git a/Jint/Native/RegExp/RegExpConstructor.cs b/Jint/Native/RegExp/RegExpConstructor.cs index 3a339fc672..9e0a174377 100644 --- a/Jint/Native/RegExp/RegExpConstructor.cs +++ b/Jint/Native/RegExp/RegExpConstructor.cs @@ -104,14 +104,15 @@ private ObjectInstance RegExpInitialize(JsRegExp r, JsValue pattern, JsValue fla try { - var regExp = Scanner.AdaptRegExp(p, f, compiled: false, _engine.Options.Constraints.RegexTimeout); + var regExpParseResult = Scanner.AdaptRegExp(p, f, compiled: false, _engine.Options.Constraints.RegexTimeout); - if (regExp is null) + if (!regExpParseResult.Success) { - ExceptionHelper.ThrowSyntaxError(_realm, $"Unsupported regular expression: '/{p}/{flags}'"); + ExceptionHelper.ThrowSyntaxError(_realm, $"Unsupported regular expression. {regExpParseResult.ConversionError!.Description}"); } - r.Value = regExp; + r.Value = regExpParseResult.Regex!; + r.ParseResult = regExpParseResult; } catch (Exception ex) { @@ -135,12 +136,13 @@ private JsRegExp RegExpAlloc(JsValue newTarget) return r; } - public JsRegExp Construct(Regex regExp, string source, string flags) + public JsRegExp Construct(Regex regExp, string source, string flags, RegExpParseResult regExpParseResult = default) { var r = RegExpAlloc(this); r.Value = regExp; r.Source = source; r.Flags = flags; + r.ParseResult = regExpParseResult; RegExpInitialize(r); diff --git a/Jint/Native/RegExp/RegExpPrototype.cs b/Jint/Native/RegExp/RegExpPrototype.cs index 65fbe03f07..7912a64859 100644 --- a/Jint/Native/RegExp/RegExpPrototype.cs +++ b/Jint/Native/RegExp/RegExpPrototype.cs @@ -1,5 +1,4 @@ using System.Diagnostics.CodeAnalysis; -using System.Text; using System.Text.RegularExpressions; using Jint.Collections; using Jint.Native.Number; @@ -168,16 +167,17 @@ private JsValue Replace(JsValue thisObject, JsValue[] arguments) { string Evaluator(Match match) { - var replacerArgs = new List(match.Groups.Count + 2); + var actualGroupCount = GetActualRegexGroupCount(rei, match); + var replacerArgs = new List(actualGroupCount + 2); replacerArgs.Add(match.Value); ObjectInstance? groups = null; - for (var i = 1; i < match.Groups.Count; i++) + for (var i = 1; i < actualGroupCount; i++) { var capture = match.Groups[i]; replacerArgs.Add(capture.Success ? capture.Value : Undefined); - var groupName = GetRegexGroupName(rei.Value, i); + var groupName = GetRegexGroupName(rei, i); if (!string.IsNullOrWhiteSpace(groupName)) { groups ??= OrdinaryObjectCreate(_engine, null); @@ -475,21 +475,13 @@ private JsValue Split(JsValue thisObject, JsValue[] arguments) } var a = _realm.Intrinsics.Array.Construct(Arguments.Empty); - var match = R.Value.Match(s, 0); - - if (!match.Success) // No match at all return the string in an array - { - a.SetIndexValue(0, s, updateLength: true); - return a; - } int lastIndex = 0; uint index = 0; - while (match.Success && index < lim) + for (var match = R.Value.Match(s, 0); match.Success; match = match.NextMatch()) { if (match.Length == 0 && (match.Index == 0 || match.Index == s.Length || match.Index == lastIndex)) { - match = match.NextMatch(); continue; } @@ -502,7 +494,8 @@ private JsValue Split(JsValue thisObject, JsValue[] arguments) } lastIndex = match.Index + match.Length; - for (int i = 1; i < match.Groups.Count; i++) + var actualGroupCount = GetActualRegexGroupCount(R, match); + for (int i = 1; i < actualGroupCount; i++) { var group = match.Groups[i]; var item = Undefined; @@ -518,14 +511,11 @@ private JsValue Split(JsValue thisObject, JsValue[] arguments) return a; } } - - match = match.NextMatch(); - if (!match.Success) // Add the last part of the split - { - a.SetIndexValue(index++, s.Substring(lastIndex), updateLength: true); - } } + // Add the last part of the split + a.SetIndexValue(index, s.Substring(lastIndex), updateLength: true); + return a; } @@ -720,7 +710,7 @@ private JsValue Match(JsValue thisObject, JsValue[] arguments) match = match.NextMatch(); if (!match.Success || match.Index != ++li) break; - a.SetIndexValue(li, match.Value, updateLength: false); + a.SetIndexValue(li, match.Value, updateLength: false); } a.SetLength(li); return a; @@ -898,7 +888,7 @@ private static JsValue RegExpBuiltinExec(JsRegExp R, string s) return Null; } - return CreateReturnValueArray(R.Engine, matcher, m, s, fullUnicode: false, hasIndices: false); + return CreateReturnValueArray(R, m, s, fullUnicode: false, hasIndices: false); } // the stateful version @@ -949,25 +939,26 @@ private static JsValue RegExpBuiltinExec(JsRegExp R, string s) R.Set(JsRegExp.PropertyLastIndex, e, true); } - return CreateReturnValueArray(R.Engine, matcher, match, s, fullUnicode, hasIndices); + return CreateReturnValueArray(R, match, s, fullUnicode, hasIndices); } private static JsArray CreateReturnValueArray( - Engine engine, - Regex regex, + JsRegExp rei, Match match, string s, bool fullUnicode, bool hasIndices) { - var array = engine.Realm.Intrinsics.Array.ArrayCreate((ulong) match.Groups.Count); + var engine = rei.Engine; + var actualGroupCount = GetActualRegexGroupCount(rei, match); + var array = engine.Realm.Intrinsics.Array.ArrayCreate((ulong) actualGroupCount); array.CreateDataProperty(PropertyIndex, match.Index); array.CreateDataProperty(PropertyInput, s); ObjectInstance? groups = null; List? groupNames = null; - var indices = hasIndices ? new List(match.Groups.Count) : null; - for (uint i = 0; i < match.Groups.Count; i++) + var indices = hasIndices ? new List(actualGroupCount) : null; + for (uint i = 0; i < actualGroupCount; i++) { var capture = match.Groups[(int) i]; var capturedValue = Undefined; @@ -988,7 +979,7 @@ private static JsArray CreateReturnValueArray( } } - var groupName = GetRegexGroupName(regex, (int) i); + var groupName = GetRegexGroupName(rei, (int) i); if (!string.IsNullOrWhiteSpace(groupName)) { groups ??= OrdinaryObjectCreate(engine, null); @@ -1055,35 +1046,28 @@ private static JsValue GetMatchIndexPair(Engine engine, string s, JsNumber[] mat return engine.Realm.Intrinsics.Array.CreateArrayFromList(match); } - private static string? GetRegexGroupName(Regex regex, int index) + private static int GetActualRegexGroupCount(JsRegExp rei, Match match) + { + return rei.ParseResult.Success ? rei.ParseResult.ActualRegexGroupCount : match.Groups.Count; + } + + private static string? GetRegexGroupName(JsRegExp rei, int index) { if (index == 0) { return null; } + var regex = rei.Value; + if (rei.ParseResult.Success) + { + return rei.ParseResult.GetRegexGroupName(index); + } + var groupNameFromNumber = regex.GroupNameFromNumber(index); if (groupNameFromNumber.Length == 1 && groupNameFromNumber[0] == 48 + index) { // regex defaults to index as group name when it's not a named group return null; - - } - - // The characters allowed in group names differs between the JS and .NET regex engines. - // For example the group name "$group" is valid in JS but invalid in .NET. - // As a workaround for this issue, the parser make an attempt to encode the problematic group names to - // names which are valid in .NET and probably won't collide with other group names present in the pattern - // (https://github.com/sebastienros/esprima-dotnet/blob/v3.0.0-rc-03/src/Esprima/Scanner.RegExpParser.cs#L942). - // We need to decode such group names. - const string encodedGroupNamePrefix = "__utf8_"; - if (groupNameFromNumber.StartsWith(encodedGroupNamePrefix, StringComparison.Ordinal)) - { - try - { - var bytes = groupNameFromNumber.AsSpan(encodedGroupNamePrefix.Length).BytesFromHexString(); - groupNameFromNumber = Encoding.UTF8.GetString(bytes); - } - catch { /* intentional no-op */ } } return groupNameFromNumber; diff --git a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs index de5de54832..04211a6294 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintLiteralExpression.cs @@ -76,12 +76,13 @@ private JsValue ResolveValue(EvaluationContext context) if (expression.TokenType == TokenType.RegularExpression) { var regExpLiteral = (RegExpLiteral) _expression; - if (regExpLiteral.Value is System.Text.RegularExpressions.Regex regex) + var regExpParseResult = regExpLiteral.ParseResult; + if (regExpParseResult.Success) { - return context.Engine.Realm.Intrinsics.RegExp.Construct(regex, regExpLiteral.Regex.Pattern, regExpLiteral.Regex.Flags); + return context.Engine.Realm.Intrinsics.RegExp.Construct(regExpParseResult.Regex!, regExpLiteral.Regex.Pattern, regExpLiteral.Regex.Flags, regExpParseResult); } - ExceptionHelper.ThrowSyntaxError(context.Engine.Realm, $"Unsupported regular expression: '{regExpLiteral.Regex.Pattern}/{regExpLiteral.Regex.Flags}'"); + ExceptionHelper.ThrowSyntaxError(context.Engine.Realm, $"Unsupported regular expression. {regExpParseResult.ConversionError!.Description}"); } return JsValue.FromObject(context.Engine, expression.Value); From f4982ee8ff37c5004776e60867299d8aefc949e5 Mon Sep 17 00:00:00 2001 From: viruscamp Date: Wed, 9 Aug 2023 22:45:35 +0800 Subject: [PATCH 24/24] More improvements for CLR Interop (#1616) --- Jint.Repl/Program.cs | 20 +- .../Runtime/InteropExplicitTypeTests.cs | 379 +++++++++++------- Jint.Tests/Runtime/InteropTests.cs | 12 + Jint/Options.cs | 23 +- Jint/Runtime/Interop/ClrFunctionInstance.cs | 6 +- Jint/Runtime/Interop/ClrHelper.cs | 85 ++++ .../Runtime/Interop/DefaultObjectConverter.cs | 2 +- .../Interop/MethodInfoFunctionInstance.cs | 26 +- Jint/Runtime/Interop/NamespaceReference.cs | 4 +- Jint/Runtime/Interop/ObjectWrapper.cs | 22 +- .../Interop/Reflection/MethodAccessor.cs | 9 +- .../Interop/Reflection/NestedTypeAccessor.cs | 22 + .../Interop/Reflection/ReflectionAccessor.cs | 2 +- Jint/Runtime/Interop/TypeReference.cs | 5 + Jint/Runtime/Interop/TypeResolver.cs | 15 +- 15 files changed, 431 insertions(+), 201 deletions(-) create mode 100644 Jint/Runtime/Interop/ClrHelper.cs create mode 100644 Jint/Runtime/Interop/Reflection/NestedTypeAccessor.cs diff --git a/Jint.Repl/Program.cs b/Jint.Repl/Program.cs index d906454cec..d52bdfbd41 100644 --- a/Jint.Repl/Program.cs +++ b/Jint.Repl/Program.cs @@ -66,22 +66,20 @@ private static void Main(string[] args) try { var result = engine.Evaluate(input, parserOptions); + JsValue str = result; if (!result.IsPrimitive() && result is not IPrimitiveInstance) { - var str = serializer.Serialize(result, JsValue.Undefined, " "); - Console.WriteLine(str); - } - else - { - if (result.IsString()) - { - Console.WriteLine(serializer.Serialize(result, JsValue.Undefined, JsValue.Undefined)); - } - else + str = serializer.Serialize(result, JsValue.Undefined, " "); + if (str == JsValue.Undefined) { - Console.WriteLine(result); + str = result; } } + else if (result.IsString()) + { + str = serializer.Serialize(result, JsValue.Undefined, JsValue.Undefined); + } + Console.WriteLine(str); } catch (JavaScriptException je) { diff --git a/Jint.Tests/Runtime/InteropExplicitTypeTests.cs b/Jint.Tests/Runtime/InteropExplicitTypeTests.cs index 9aeaea3494..859294dec1 100644 --- a/Jint.Tests/Runtime/InteropExplicitTypeTests.cs +++ b/Jint.Tests/Runtime/InteropExplicitTypeTests.cs @@ -1,186 +1,291 @@ -using System.Reflection; +namespace Jint.Tests.Runtime; -namespace Jint.Tests.Runtime +using Jint.Runtime.Interop; + +public class InteropExplicitTypeTests { - public class InteropExplicitTypeTests + public interface I1 + { + string Name { get; } + } + + public class Super + { + public string Name { get; } = "Super"; + } + + public class CI1 : Super, I1 { - public interface I1 + public new string Name { get; } = "CI1"; + + string I1.Name { get; } = "CI1 as I1"; + } + + public class Indexer + { + private readonly T t; + public Indexer(T t) { - string Name { get; } + this.t = t; } - - public class Super + public T this[int index] { - public string Name { get; } = "Super"; + get { return t; } } + } - public class CI1 : Super, I1 + public class InterfaceHolder + { + public InterfaceHolder() { - public new string Name { get; } = "CI1"; + var ci1 = new CI1(); + this.ci1 = ci1; + this.i1 = ci1; + this.super = ci1; - string I1.Name { get; } = "CI1 as I1"; + this.IndexerCI1 = new Indexer(ci1); + this.IndexerI1 = new Indexer(ci1); + this.IndexerSuper = new Indexer(ci1); } - public class Indexer - { - private readonly T t; - public Indexer(T t) - { - this.t = t; - } - public T this[int index] - { - get { return t; } - } - } + public readonly CI1 ci1; + public readonly I1 i1; + public readonly Super super; - public class InterfaceHolder - { - public InterfaceHolder() - { - var ci1 = new CI1(); - this.ci1 = ci1; - this.i1 = ci1; - this.super = ci1; + public CI1 CI1 { get => ci1; } + public I1 I1 { get => i1; } + public Super Super { get => super; } - this.IndexerCI1 = new Indexer(ci1); - this.IndexerI1 = new Indexer(ci1); - this.IndexerSuper = new Indexer(ci1); - } + public CI1 GetCI1() => ci1; + public I1 GetI1() => i1; + public Super GetSuper() => super; - public readonly CI1 ci1; - public readonly I1 i1; - public readonly Super super; + public Indexer IndexerCI1 { get; } + public Indexer IndexerI1 { get; } + public Indexer IndexerSuper { get; } - public CI1 CI1 { get => ci1; } - public I1 I1 { get => i1; } - public Super Super { get => super; } + } - public CI1 GetCI1() => ci1; - public I1 GetI1() => i1; - public Super GetSuper() => super; + private readonly Engine _engine; + private readonly InterfaceHolder holder; - public Indexer IndexerCI1 { get; } - public Indexer IndexerI1 { get; } - public Indexer IndexerSuper { get; } + public InteropExplicitTypeTests() + { + holder = new InterfaceHolder(); + _engine = new Engine(cfg => cfg.AllowClr( + typeof(CI1).Assembly, + typeof(Console).Assembly, + typeof(File).Assembly)) + .SetValue("log", new Action(Console.WriteLine)) + .SetValue("assert", new Action(Assert.True)) + .SetValue("equal", new Action(Assert.Equal)) + .SetValue("holder", holder) + ; + } + [Fact] + public void EqualTest() + { + Assert.Equal(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.i1")); + Assert.NotEqual(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.ci1")); - } + Assert.Equal(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.super")); + Assert.NotEqual(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.ci1")); + } - private readonly Engine _engine; - private readonly InterfaceHolder holder; + [Fact] + public void ExplicitInterfaceFromField() + { + Assert.Equal(holder.i1.Name, _engine.Evaluate("holder.i1.Name")); + Assert.NotEqual(holder.i1.Name, _engine.Evaluate("holder.ci1.Name")); + } - public InteropExplicitTypeTests() - { - holder = new InterfaceHolder(); - _engine = new Engine(cfg => cfg.AllowClr( - typeof(Console).GetTypeInfo().Assembly, - typeof(File).GetTypeInfo().Assembly)) - .SetValue("log", new Action(Console.WriteLine)) - .SetValue("assert", new Action(Assert.True)) - .SetValue("equal", new Action(Assert.Equal)) - .SetValue("holder", holder) - ; - } - [Fact] - public void EqualTest() - { - Assert.Equal(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.i1")); - Assert.NotEqual(_engine.Evaluate("holder.I1"), _engine.Evaluate("holder.ci1")); + [Fact] + public void ExplicitInterfaceFromProperty() + { + Assert.Equal(holder.I1.Name, _engine.Evaluate("holder.I1.Name")); + Assert.NotEqual(holder.I1.Name, _engine.Evaluate("holder.CI1.Name")); + } - Assert.Equal(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.super")); - Assert.NotEqual(_engine.Evaluate("holder.Super"), _engine.Evaluate("holder.ci1")); - } + [Fact] + public void ExplicitInterfaceFromMethod() + { + Assert.Equal(holder.GetI1().Name, _engine.Evaluate("holder.GetI1().Name")); + Assert.NotEqual(holder.GetI1().Name, _engine.Evaluate("holder.GetCI1().Name")); + } - [Fact] - public void ExplicitInterfaceFromField() - { - Assert.Equal(holder.i1.Name, _engine.Evaluate("holder.i1.Name")); - Assert.NotEqual(holder.i1.Name, _engine.Evaluate("holder.ci1.Name")); - } + [Fact] + public void ExplicitInterfaceFromIndexer() + { + Assert.Equal(holder.IndexerI1[0].Name, _engine.Evaluate("holder.IndexerI1[0].Name")); + } - [Fact] - public void ExplicitInterfaceFromProperty() - { - Assert.Equal(holder.I1.Name, _engine.Evaluate("holder.I1.Name")); - Assert.NotEqual(holder.I1.Name, _engine.Evaluate("holder.CI1.Name")); - } - [Fact] - public void ExplicitInterfaceFromMethod() - { - Assert.Equal(holder.GetI1().Name, _engine.Evaluate("holder.GetI1().Name")); - Assert.NotEqual(holder.GetI1().Name, _engine.Evaluate("holder.GetCI1().Name")); - } + [Fact] + public void SuperClassFromField() + { + Assert.Equal(holder.super.Name, _engine.Evaluate("holder.super.Name")); + Assert.NotEqual(holder.super.Name, _engine.Evaluate("holder.ci1.Name")); + } - [Fact] - public void ExplicitInterfaceFromIndexer() - { - Assert.Equal(holder.IndexerI1[0].Name, _engine.Evaluate("holder.IndexerI1[0].Name")); - } + [Fact] + public void SuperClassFromProperty() + { + Assert.Equal(holder.Super.Name, _engine.Evaluate("holder.Super.Name")); + Assert.NotEqual(holder.Super.Name, _engine.Evaluate("holder.CI1.Name")); + } + [Fact] + public void SuperClassFromMethod() + { + Assert.Equal(holder.GetSuper().Name, _engine.Evaluate("holder.GetSuper().Name")); + Assert.NotEqual(holder.GetSuper().Name, _engine.Evaluate("holder.GetCI1().Name")); + } - [Fact] - public void SuperClassFromField() - { - Assert.Equal(holder.super.Name, _engine.Evaluate("holder.super.Name")); - Assert.NotEqual(holder.super.Name, _engine.Evaluate("holder.ci1.Name")); - } + [Fact] + public void SuperClassFromIndexer() + { + Assert.Equal(holder.IndexerSuper[0].Name, _engine.Evaluate("holder.IndexerSuper[0].Name")); + } - [Fact] - public void SuperClassFromProperty() + public struct NullabeStruct : I1 + { + public NullabeStruct() { - Assert.Equal(holder.Super.Name, _engine.Evaluate("holder.Super.Name")); - Assert.NotEqual(holder.Super.Name, _engine.Evaluate("holder.CI1.Name")); } + public string name = "NullabeStruct"; + + public string Name { get => name; } + + string I1.Name { get => "NullabeStruct as I1"; } + } + + public class NullableHolder + { + public I1 I1 { get; set; } + public NullabeStruct? NullabeStruct { get; set; } + } + + [Fact] + public void TypedObjectWrapperForNullableType() + { + var nullableHolder = new NullableHolder(); + _engine.SetValue("nullableHolder", nullableHolder); + _engine.SetValue("nullabeStruct", new NullabeStruct()); + + Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct"), Native.JsValue.Null); + _engine.Evaluate("nullableHolder.NullabeStruct = nullabeStruct"); + Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct.Name"), nullableHolder.NullabeStruct?.Name); + } + + [Fact] + public void ClrHelperUnwrap() + { + Assert.NotEqual(holder.CI1.Name, _engine.Evaluate("holder.I1.Name")); + Assert.Equal(holder.CI1.Name, _engine.Evaluate("clrHelper.unwrap(holder.I1).Name")); + } + + [Fact] + public void ClrHelperWrap() + { + _engine.Execute("Jint = importNamespace('Jint');"); + Assert.NotEqual(holder.I1.Name, _engine.Evaluate("holder.CI1.Name")); + Assert.Equal(holder.I1.Name, _engine.Evaluate("clrHelper.wrap(holder.CI1, Jint.Tests.Runtime.InteropExplicitTypeTests.I1).Name")); + } - [Fact] - public void SuperClassFromMethod() + [Fact] + public void ClrHelperTypeOf() + { + Action runner = engine => { - Assert.Equal(holder.GetSuper().Name, _engine.Evaluate("holder.GetSuper().Name")); - Assert.NotEqual(holder.GetSuper().Name, _engine.Evaluate("holder.GetCI1().Name")); - } + engine.SetValue("clrobj", new object()); + Assert.Equal(engine.Evaluate("System.Object"), engine.Evaluate("clrHelper.typeOf(clrobj)")); + }; - [Fact] - public void SuperClassFromIndexer() + runner.Invoke(new Engine(cfg => { - Assert.Equal(holder.IndexerSuper[0].Name, _engine.Evaluate("holder.IndexerSuper[0].Name")); - } + cfg.AllowClr(); + cfg.Interop.AllowGetType = true; + })); - public struct NullabeStruct: I1 + var ex = Assert.Throws(() => { - public NullabeStruct() + runner.Invoke(new Engine(cfg => { - } - public string name = "NullabeStruct"; + cfg.AllowClr(); + })); + }); + Assert.Equal("Invalid when Engine.Options.Interop.AllowGetType == false", ex.Message); + } + + [Fact] + public void ClrHelperTypeOfForNestedType() + { + var engine = new Engine(cfg => + { + cfg.AllowClr(GetType().Assembly); + cfg.Interop.AllowGetType = true; + }); - public string Name { get => name; } + engine.SetValue("holder", holder); + engine.Execute("Jint = importNamespace('Jint');"); + Assert.Equal(engine.Evaluate("Jint.Tests.Runtime.InteropExplicitTypeTests.CI1"), engine.Evaluate("clrHelper.typeOf(holder.CI1)")); + Assert.Equal(engine.Evaluate("Jint.Tests.Runtime.InteropExplicitTypeTests.I1"), engine.Evaluate("clrHelper.typeOf(holder.I1)")); + } - string I1.Name { get => "NullabeStruct as I1"; } - } + public class TypeHolder + { + public static Type Type => typeof(TypeHolder); + } + + [Fact] + public void ClrHelperTypeToObject() + { + Action runner = engine => + { + engine.SetValue("TypeHolder", typeof(TypeHolder)); + Assert.True(engine.Evaluate("TypeHolder") is TypeReference); + Assert.True(engine.Evaluate("clrHelper.typeToObject(TypeHolder)") is ObjectWrapper); + }; - public class NullableHolder + runner.Invoke(new Engine(cfg => { - public I1? I1 { get; set; } - public NullabeStruct? NullabeStruct { get; set; } - } + cfg.AllowClr(); + cfg.Interop.AllowGetType = true; + })); - [Fact] - public void TestNullable() + var ex = Assert.Throws(() => { - var nullableHolder = new NullableHolder(); - _engine.SetValue("nullableHolder", nullableHolder); - _engine.SetValue("nullabeStruct", new NullabeStruct()); + runner.Invoke(new Engine(cfg => + { + cfg.AllowClr(); + })); + }); + Assert.Equal("Invalid when Engine.Options.Interop.AllowGetType == false", ex.Message); + } - Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct"), Native.JsValue.Null); - _engine.Evaluate("nullableHolder.NullabeStruct = nullabeStruct"); - Assert.Equal(_engine.Evaluate("nullableHolder.NullabeStruct.Name"), nullableHolder.NullabeStruct?.Name); - } + [Fact] + public void ClrHelperObjectToType() + { + Action runner = engine => + { + engine.SetValue("TypeHolder", typeof(TypeHolder)); + Assert.True(engine.Evaluate("TypeHolder.Type") is ObjectWrapper); + Assert.True(engine.Evaluate("clrHelper.objectToType(TypeHolder.Type)") is TypeReference); + }; - [Fact] - public void TestUnwrapClr() + runner.Invoke(new Engine(cfg => { - Assert.NotEqual(holder.CI1.Name, _engine.Evaluate("holder.I1.Name")); - Assert.Equal(holder.CI1.Name, _engine.Evaluate("unwrapClr(holder.I1).Name")); - } + cfg.AllowClr(); + cfg.Interop.AllowGetType = true; + })); + + var ex = Assert.Throws(() => + { + runner.Invoke(new Engine(cfg => + { + cfg.AllowClr(); + })); + }); + Assert.Equal("Invalid when Engine.Options.Interop.AllowGetType == false", ex.Message); } } diff --git a/Jint.Tests/Runtime/InteropTests.cs b/Jint.Tests/Runtime/InteropTests.cs index 07f345a3c5..d8b0ac5368 100644 --- a/Jint.Tests/Runtime/InteropTests.cs +++ b/Jint.Tests/Runtime/InteropTests.cs @@ -1893,6 +1893,18 @@ public void ShouldImportNamespaceNestedNestedType() "); } + [Fact] + public void ShouldGetNestedTypeFromParentType() + { + RunTest(@" + var Shapes = importNamespace('Shapes'); + var usages = Shapes.Circle.Meta.Usage; + assert(usages.Public === 0); + assert(usages.Private === 1); + assert(usages.Internal === 11); + "); + } + [Fact] public void ShouldGetNestedNestedProp() { diff --git a/Jint/Options.cs b/Jint/Options.cs index 63f57f2769..4224613a3a 100644 --- a/Jint/Options.cs +++ b/Jint/Options.cs @@ -120,21 +120,8 @@ internal void Apply(Engine engine) (thisObj, arguments) => new NamespaceReference(engine, TypeConverter.ToString(arguments.At(0)))), PropertyFlag.AllForbidden)); - engine.Realm.GlobalObject.SetProperty("unwrapClr", new PropertyDescriptor(new ClrFunctionInstance( - engine, - "unwrapClr", - (thisObj, arguments) => - { - var arg = arguments.At(0); - if (arg is ObjectWrapper obj) - { - return new ObjectWrapper(engine, obj.Target); - } - else - { - return arg; - } - }), + engine.Realm.GlobalObject.SetProperty("clrHelper", new PropertyDescriptor( + new ObjectWrapper(engine, new ClrHelper(Interop)), PropertyFlag.AllForbidden)); } @@ -183,12 +170,10 @@ private static void AttachExtensionMethodsToPrototype(Engine engine, ObjectInsta foreach (var overloads in methods.GroupBy(x => x.Name)) { + string name = overloads.Key; PropertyDescriptor CreateMethodInstancePropertyDescriptor(ClrFunctionInstance? function) { - var instance = function is null - ? new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList())) - : new MethodInfoFunctionInstance(engine, MethodDescriptor.Build(overloads.ToList()), function); - + var instance = new MethodInfoFunctionInstance(engine, objectType, name, MethodDescriptor.Build(overloads.ToList()), function); return new PropertyDescriptor(instance, PropertyFlag.AllForbidden); } diff --git a/Jint/Runtime/Interop/ClrFunctionInstance.cs b/Jint/Runtime/Interop/ClrFunctionInstance.cs index 7440ab474f..d777dc5a05 100644 --- a/Jint/Runtime/Interop/ClrFunctionInstance.cs +++ b/Jint/Runtime/Interop/ClrFunctionInstance.cs @@ -10,7 +10,6 @@ namespace Jint.Runtime.Interop /// public sealed class ClrFunctionInstance : FunctionInstance, IEquatable { - private readonly string? _name; internal readonly Func _func; public ClrFunctionInstance( @@ -19,9 +18,8 @@ public ClrFunctionInstance( Func func, int length = 0, PropertyFlag lengthFlags = PropertyFlag.AllForbidden) - : base(engine, engine.Realm, name != null ? new JsString(name) : null) + : base(engine, engine.Realm, new JsString(name)) { - _name = name; _func = func; _prototype = engine._originalIntrinsics.Function.PrototypeObject; @@ -76,7 +74,5 @@ public bool Equals(ClrFunctionInstance? other) return false; } - - public override string ToString() => "function " + _name + "() { [native code] }"; } } diff --git a/Jint/Runtime/Interop/ClrHelper.cs b/Jint/Runtime/Interop/ClrHelper.cs new file mode 100644 index 0000000000..e11763216c --- /dev/null +++ b/Jint/Runtime/Interop/ClrHelper.cs @@ -0,0 +1,85 @@ +namespace Jint.Runtime.Interop; + +using Jint.Native; + +public class ClrHelper +{ + private readonly InteropOptions _interopOptions; + + internal ClrHelper(InteropOptions interopOptions) + { + _interopOptions = interopOptions; + } + + /// + /// Call JsValue.ToString(), mainly for NamespaceReference. + /// + public JsValue ToString(JsValue value) + { + return value.ToString(); + } + + /// + /// Cast `obj as ISomeInterface` to `obj` + /// + public JsValue Unwrap(ObjectWrapper obj) + { + return new ObjectWrapper(obj.Engine, obj.Target); + } + + /// + /// Cast `obj` to `obj as ISomeInterface` + /// + public JsValue Wrap(ObjectWrapper obj, TypeReference type) + { + if (!type.ReferenceType.IsInstanceOfType(obj.Target)) + { + ExceptionHelper.ThrowTypeError(type.Engine.Realm, "Argument obj must be an instance of type"); + } + return new ObjectWrapper(obj.Engine, obj.Target, type.ReferenceType); + } + + /// + /// Get `TypeReference(ISomeInterface)` from `obj as ISomeInterface` + /// + public JsValue TypeOf(ObjectWrapper obj) + { + MustAllowGetType(); + return TypeReference.CreateTypeReference(obj.Engine, obj.ClrType); + } + + /// + /// Cast `TypeReference(SomeClass)` to `ObjectWrapper(SomeClass)` + /// + public JsValue TypeToObject(TypeReference type) + { + MustAllowGetType(); + var engine = type.Engine; + return engine.Options.Interop.WrapObjectHandler.Invoke(engine, type.ReferenceType, null) ?? JsValue.Undefined; + } + + /// + /// Cast `ObjectWrapper(SomeClass)` to `TypeReference(SomeClass)` + /// + public JsValue ObjectToType(ObjectWrapper obj) + { + MustAllowGetType(); + if (obj.Target is Type t) + { + return TypeReference.CreateTypeReference(obj.Engine, t); + } + else + { + ExceptionHelper.ThrowArgumentException("Must be an ObjectWrapper of Type", "obj"); + } + return JsValue.Undefined; + } + + private void MustAllowGetType() + { + if (!_interopOptions.AllowGetType) + { + ExceptionHelper.ThrowInvalidOperationException("Invalid when Engine.Options.Interop.AllowGetType == false"); + } + } +} diff --git a/Jint/Runtime/Interop/DefaultObjectConverter.cs b/Jint/Runtime/Interop/DefaultObjectConverter.cs index 8c3a647389..f9739bbfb2 100644 --- a/Jint/Runtime/Interop/DefaultObjectConverter.cs +++ b/Jint/Runtime/Interop/DefaultObjectConverter.cs @@ -37,7 +37,7 @@ internal static class DefaultObjectConverter public static bool TryConvert(Engine engine, object value, Type? type, [NotNullWhen(true)] out JsValue? result) { result = null; - Type valueType = ObjectWrapper.ClrType(value, type); + Type valueType = ObjectWrapper.GetClrType(value, type); var typeMappers = _typeMappers; diff --git a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs index 81deb326ee..8d7385b2a0 100644 --- a/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs +++ b/Jint/Runtime/Interop/MethodInfoFunctionInstance.cs @@ -9,21 +9,24 @@ namespace Jint.Runtime.Interop { internal sealed class MethodInfoFunctionInstance : FunctionInstance { - private static readonly JsString _name = new JsString("Function"); + private readonly Type _targetType; + private readonly string _name; private readonly MethodDescriptor[] _methods; private readonly ClrFunctionInstance? _fallbackClrFunctionInstance; - public MethodInfoFunctionInstance(Engine engine, MethodDescriptor[] methods) - : base(engine, engine.Realm, _name) + public MethodInfoFunctionInstance( + Engine engine, + Type targetType, + string name, + MethodDescriptor[] methods, + ClrFunctionInstance? fallbackClrFunctionInstance = null) + : base(engine, engine.Realm, new JsString(name)) { + _targetType = targetType; + _name = name; _methods = methods; - _prototype = engine.Realm.Intrinsics.Function.PrototypeObject; - } - - public MethodInfoFunctionInstance(Engine engine, MethodDescriptor[] methods, ClrFunctionInstance fallbackClrFunctionInstance) - : this(engine, methods) - { _fallbackClrFunctionInstance = fallbackClrFunctionInstance; + _prototype = engine.Realm.Intrinsics.Function.PrototypeObject; } private static bool IsGenericParameter(object argObj, Type parameterType) @@ -285,5 +288,10 @@ private JsValue[] ProcessParamsArrays(JsValue[] jsArguments, MethodDescriptor me newArgumentsCollection[nonParamsArgumentsCount] = jsArray; return newArgumentsCollection; } + + public override string ToString() + { + return $"function {_targetType}.{_name}() {{ [native code] }}"; + } } } diff --git a/Jint/Runtime/Interop/NamespaceReference.cs b/Jint/Runtime/Interop/NamespaceReference.cs index fd795201ab..e72bb9a124 100644 --- a/Jint/Runtime/Interop/NamespaceReference.cs +++ b/Jint/Runtime/Interop/NamespaceReference.cs @@ -94,7 +94,7 @@ public JsValue GetPath(string path) // and only then in mscorlib. Probelm usage: System.IO.File.CreateText // search in loaded assemblies - var lookupAssemblies = new[] {Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly()}; + var lookupAssemblies = new[] { Assembly.GetCallingAssembly(), Assembly.GetExecutingAssembly() }; foreach (var assembly in lookupAssemblies) { @@ -192,7 +192,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property) public override string ToString() { - return "[Namespace: " + _path + "]"; + return "[CLR namespace: " + _path + "]"; } } } diff --git a/Jint/Runtime/Interop/ObjectWrapper.cs b/Jint/Runtime/Interop/ObjectWrapper.cs index 74eb62a65e..2b76866843 100644 --- a/Jint/Runtime/Interop/ObjectWrapper.cs +++ b/Jint/Runtime/Interop/ObjectWrapper.cs @@ -17,14 +17,13 @@ namespace Jint.Runtime.Interop public sealed class ObjectWrapper : ObjectInstance, IObjectWrapper, IEquatable { private readonly TypeDescriptor _typeDescriptor; - private readonly Type _clrType; public ObjectWrapper(Engine engine, object obj, Type? type = null) : base(engine) { Target = obj; - _clrType = ClrType(obj, type); - _typeDescriptor = TypeDescriptor.Get(_clrType); + ClrType = GetClrType(obj, type); + _typeDescriptor = TypeDescriptor.Get(ClrType); if (_typeDescriptor.LengthProperty is not null) { // create a forwarder to produce length from Count or Length if one of them is present @@ -35,6 +34,7 @@ public ObjectWrapper(Engine engine, object obj, Type? type = null) } public object Target { get; } + internal Type ClrType { get; } public override bool IsArrayLike => _typeDescriptor.IsArrayLike; @@ -51,7 +51,7 @@ public override bool Set(JsValue property, JsValue value, JsValue receiver) if (_properties is null || !_properties.ContainsKey(member)) { // can try utilize fast path - var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member, forWrite: true); + var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member, forWrite: true); if (ReferenceEquals(accessor, ConstantValueAccessor.NullAccessor)) { @@ -163,7 +163,7 @@ private IEnumerable EnumerateOwnPropertyKeys(Types types) else if (includeStrings) { // we take public properties and fields - var type = _clrType; + var type = ClrType; foreach (var p in type.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public)) { var indexParameters = p.GetIndexParameters(); @@ -235,7 +235,7 @@ public override PropertyDescriptor GetOwnProperty(JsValue property) return new PropertyDescriptor(result, PropertyFlag.OnlyEnumerable); } - var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, _clrType, member); + var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, ClrType, member); var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary); if (!isDictionary && !ReferenceEquals(descriptor, PropertyDescriptor.Undefined)) { @@ -254,7 +254,7 @@ public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object tar return member switch { PropertyInfo pi => new PropertyAccessor(pi.Name, pi), - MethodBase mb => new MethodAccessor(MethodDescriptor.Build(new[] {mb})), + MethodBase mb => new MethodAccessor(target.GetType(), member.Name, MethodDescriptor.Build(new[] { mb })), FieldInfo fi => new FieldAccessor(fi), _ => null }; @@ -262,7 +262,7 @@ public static PropertyDescriptor GetPropertyDescriptor(Engine engine, object tar return engine.Options.Interop.TypeResolver.GetAccessor(engine, target.GetType(), member.Name, Factory).CreatePropertyDescriptor(engine, target); } - public static Type ClrType(object obj, Type? type) + internal static Type GetClrType(object obj, Type? type) { if (type is null || type == typeof(object)) { @@ -319,14 +319,14 @@ public bool Equals(ObjectWrapper? other) return true; } - return Equals(Target, other.Target) && Equals(_clrType, other._clrType); + return Equals(Target, other.Target) && Equals(ClrType, other.ClrType); } public override int GetHashCode() { var hashCode = -1468639730; hashCode = hashCode * -1521134295 + Target.GetHashCode(); - hashCode = hashCode * -1521134295 + _clrType.GetHashCode(); + hashCode = hashCode * -1521134295 + ClrType.GetHashCode(); return hashCode; } @@ -368,7 +368,7 @@ public EnumerableIterator(Engine engine, IEnumerable target) : base(engine) public override void Close(CompletionType completion) { - (_enumerator as IDisposable)?.Dispose(); + (_enumerator as IDisposable)?.Dispose(); base.Close(completion); } diff --git a/Jint/Runtime/Interop/Reflection/MethodAccessor.cs b/Jint/Runtime/Interop/Reflection/MethodAccessor.cs index 601e914dc0..3a7a8b80df 100644 --- a/Jint/Runtime/Interop/Reflection/MethodAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/MethodAccessor.cs @@ -4,10 +4,15 @@ namespace Jint.Runtime.Interop.Reflection { internal sealed class MethodAccessor : ReflectionAccessor { + private readonly Type _targetType; + private readonly string _name; private readonly MethodDescriptor[] _methods; - public MethodAccessor(MethodDescriptor[] methods) : base(null!, null!) + public MethodAccessor(Type targetType, string name, MethodDescriptor[] methods) + : base(null!, name) { + _targetType = targetType; + _name = name; _methods = methods; } @@ -24,7 +29,7 @@ protected override void DoSetValue(object target, object? value) public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true) { - return new(new MethodInfoFunctionInstance(engine, _methods), PropertyFlag.AllForbidden); + return new(new MethodInfoFunctionInstance(engine, _targetType, _name, _methods), PropertyFlag.AllForbidden); } } } diff --git a/Jint/Runtime/Interop/Reflection/NestedTypeAccessor.cs b/Jint/Runtime/Interop/Reflection/NestedTypeAccessor.cs new file mode 100644 index 0000000000..c4d7a66e65 --- /dev/null +++ b/Jint/Runtime/Interop/Reflection/NestedTypeAccessor.cs @@ -0,0 +1,22 @@ +namespace Jint.Runtime.Interop.Reflection; + +internal sealed class NestedTypeAccessor : ReflectionAccessor +{ + private readonly TypeReference _typeReference; + + public NestedTypeAccessor(TypeReference typeReference, string name) : base(typeof(Type), name) + { + _typeReference = typeReference; + } + + public override bool Writable => false; + + protected override object? DoGetValue(object target) + { + return _typeReference; + } + + protected override void DoSetValue(object target, object? value) + { + } +} diff --git a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs index ea28ec602e..233f6f05ed 100644 --- a/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs +++ b/Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs @@ -12,7 +12,7 @@ namespace Jint.Runtime.Interop.Reflection /// internal abstract class ReflectionAccessor { - private readonly Type _memberType; + protected readonly Type _memberType; private readonly object? _memberName; private readonly PropertyInfo? _indexer; diff --git a/Jint/Runtime/Interop/TypeReference.cs b/Jint/Runtime/Interop/TypeReference.cs index 92f0f61705..c4c99b3f22 100644 --- a/Jint/Runtime/Interop/TypeReference.cs +++ b/Jint/Runtime/Interop/TypeReference.cs @@ -346,5 +346,10 @@ private static JsValue HasInstance(JsValue thisObject, JsValue[] arguments) return derivedType != null && baseType != null && (derivedType == baseType || derivedType.IsSubclassOf(baseType)); } + + public override string ToString() + { + return "[CLR type: " + ReferenceType + "]"; + } } } diff --git a/Jint/Runtime/Interop/TypeResolver.cs b/Jint/Runtime/Interop/TypeResolver.cs index 744c634e88..af40e876ac 100644 --- a/Jint/Runtime/Interop/TypeResolver.cs +++ b/Jint/Runtime/Interop/TypeResolver.cs @@ -160,7 +160,7 @@ private ReflectionAccessor ResolvePropertyDescriptorFactory( if (explicitMethods?.Count > 0) { - return new MethodAccessor(MethodDescriptor.Build(explicitMethods)); + return new MethodAccessor(type, memberName, MethodDescriptor.Build(explicitMethods)); } // try to find explicit indexer implementations @@ -193,7 +193,7 @@ private ReflectionAccessor ResolvePropertyDescriptorFactory( if (matches.Count > 0) { - return new MethodAccessor(MethodDescriptor.Build(matches)); + return new MethodAccessor(type, memberName, MethodDescriptor.Build(matches)); } } @@ -299,7 +299,16 @@ internal bool TryFindMemberAccessor( if (methods?.Count > 0) { - accessor = new MethodAccessor(MethodDescriptor.Build(methods)); + accessor = new MethodAccessor(type, memberName, MethodDescriptor.Build(methods)); + return true; + } + + // look for nested type + var nestedType = type.GetNestedType(memberName, bindingFlags); + if (nestedType != null) + { + var typeReference = TypeReference.CreateTypeReference(engine, nestedType); + accessor = new NestedTypeAccessor(typeReference, memberName); return true; }