Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Jint.Tests/Runtime/InteropTests.MemberAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -301,4 +301,23 @@ public void ShouldRespectExplicitHiding()
engine.Evaluate("obj.x").AsBoolean().Should().BeTrue();
engine.Evaluate("obj.y").AsNumber().Should().Be(3);
}

[Fact]
public void ShouldSkipEnumIndexerWhenNoMatch()
{
var engine = new Engine();
engine.SetValue("obj", new ObjectWithEnumIndexer());
engine.Evaluate("obj.Foo()").AsString().Should().Be("Foo called");
}

private class ObjectWithEnumIndexer
{
public string this[TestEnumInt32 key]
{
get => "";
set { }
}

public string Foo() => "Foo called";
}
}
37 changes: 26 additions & 11 deletions Jint/Runtime/Interop/DefaultTypeConverter.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
using System;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Acornima.Ast;
using Jint.Extensions;
using Jint.Native;
using Jint.Native.Function;
using Jint.Native.Object;
using Jint.Pooling;
using Jint.Runtime.Descriptors;
using Expression = System.Linq.Expressions.Expression;

#pragma warning disable IL2026
Expand Down Expand Up @@ -118,14 +113,10 @@ private bool TryConvert(

if (type.IsEnum)
{
var integer = System.Convert.ChangeType(value, intType, formatProvider);
if (integer == null)
if (EnumTryParse(type, value.ToString(), out converted))
{
ExceptionHelper.ThrowArgumentOutOfRangeException();
return true;
}

converted = Enum.ToObject(type, integer);
return true;
}

var valueType = value.GetType();
Expand Down Expand Up @@ -276,6 +267,30 @@ private bool TryConvert(
}
}

private static bool EnumTryParse(Type enumType, string? value, [NotNullWhen(true)] out object? result)
{
if (value is null)
{
result = null;
return false;
}

#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
return Enum.TryParse(enumType, value, ignoreCase: false, out result!);
#else
try
{
result = Enum.Parse(enumType, value, ignoreCase: false);
return true;
}
catch (ArgumentException)
{
result = null!;
return false;
}
#endif
}

private Func<object, Delegate> BuildTargetBinderDelegate(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type delegateType,
JsCallDelegate function)
Expand Down