Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve dictionary based CLR interop #1127

Merged
merged 1 commit into from
Apr 15, 2022
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
36 changes: 31 additions & 5 deletions Jint.Tests/Runtime/InteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -514,12 +514,9 @@ public void CanUseIndexOnList()
list.Add("Goofy");

_engine.SetValue("list", list);
_engine.Evaluate("list[1] = 'Donald Duck';");

RunTest(@"
list[1] = 'Donald Duck';
assert(list[1] === 'Donald Duck');
");

Assert.Equal("Donald Duck", _engine.Evaluate("list[1]").AsString());
Assert.Equal("Mickey Mouse", list[0]);
Assert.Equal("Donald Duck", list[1]);
}
Expand Down Expand Up @@ -2798,6 +2795,35 @@ public void ShouldGetIteratorForListAndDictionary()
Assert.Equal("a,1b,2c,3", _engine.Evaluate(Script));
}

[Fact]
public void ShouldNotIntroduceNewPropertiesWhenTraversing()
{
_engine.SetValue("x", new Dictionary<string, int> { { "First", 1 }, { "Second", 2 } });

Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

Assert.Equal("x['First']: 1", _engine.Evaluate("\"x['First']: \" + x['First']"));
Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

Assert.Equal("x['Third']: undefined", _engine.Evaluate("\"x['Third']: \" + x['Third']"));
Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

Assert.Equal(JsValue.Undefined, _engine.Evaluate("x.length"));
Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

Assert.Equal(2, _engine.Evaluate("x.Count").AsNumber());
Assert.Equal("[\"First\",\"Second\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

_engine.Evaluate("x.Clear();");

Assert.Equal("[]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

_engine.Evaluate("x['Fourth'] = 4;");
Assert.Equal("[\"Fourth\"]", _engine.Evaluate("JSON.stringify(Object.keys(x))"));

Assert.False(_engine.Evaluate("Object.prototype.hasOwnProperty.call(x, 'Third')").AsBoolean());
}

private class Profile
{
public int AnyProperty => throw new NotSupportedException("NOT SUPPORTED");
Expand Down
13 changes: 10 additions & 3 deletions Jint/Runtime/Interop/ObjectWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,11 @@ public override PropertyDescriptor GetOwnProperty(JsValue property)

var member = property.ToString();

if (_typeDescriptor.IsStringKeyedGenericDictionary)
// if type is dictionary, we cannot enumerate anything other than keys
// and we cannot store accessors as dictionary can change dynamically

var isDictionary = _typeDescriptor.IsStringKeyedGenericDictionary;
if (isDictionary)
{
if (_typeDescriptor.TryGetValue(Target, member, out var value))
{
Expand All @@ -235,8 +239,11 @@ public override PropertyDescriptor GetOwnProperty(JsValue property)
}

var accessor = _engine.Options.Interop.TypeResolver.GetAccessor(_engine, Target.GetType(), member);
var descriptor = accessor.CreatePropertyDescriptor(_engine, Target);
SetProperty(member, descriptor);
var descriptor = accessor.CreatePropertyDescriptor(_engine, Target, enumerable: !isDictionary);
if (!isDictionary)
{
SetProperty(member, descriptor);
}
return descriptor;
}

Expand Down
4 changes: 2 additions & 2 deletions Jint/Runtime/Interop/Reflection/ConstantValueAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ protected override void DoSetValue(object target, object value)
throw new InvalidOperationException();
}

public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target)
public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true)
{
return ConstantValue is null
? PropertyDescriptor.Undefined
: new(ConstantValue, PropertyFlag.AllForbidden);
}
}
}
}
18 changes: 13 additions & 5 deletions Jint/Runtime/Interop/Reflection/IndexerAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ IndexerAccessor ComposeIndexerFactory(PropertyInfo candidate, Type paramType)
// get contains key method to avoid index exception being thrown in dictionaries
paramTypeArray[0] = paramType;
var containsKeyMethod = targetType.GetMethod(nameof(IDictionary<string, string>.ContainsKey), paramTypeArray);
if (containsKeyMethod is null)
if (containsKeyMethod is null && targetType.IsAssignableFrom(typeof(IDictionary)))
{
paramTypeArray[0] = typeof(object);
containsKeyMethod = targetType.GetMethod(nameof(IDictionary.Contains), paramTypeArray);
Expand Down Expand Up @@ -130,7 +130,7 @@ protected override object DoGetValue(object target)
return null;
}

object[] parameters = {_key};
object[] parameters = { _key };

if (_containsKey != null)
{
Expand All @@ -150,13 +150,21 @@ protected override void DoSetValue(object target, object value)
ExceptionHelper.ThrowInvalidOperationException("Indexer has no public setter.");
}

object[] parameters = {_key, value};
object[] parameters = { _key, value };
_setter!.Invoke(target, parameters);
}

public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target)
public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true)
{
if (_containsKey != null)
{
if (_containsKey.Invoke(target, new[] { _key }) as bool? != true)
{
return PropertyDescriptor.Undefined;
}
}

return new ReflectionDescriptor(engine, this, target, false);
}
}
}
}
2 changes: 1 addition & 1 deletion Jint/Runtime/Interop/Reflection/MethodAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ protected override void DoSetValue(object target, object value)
{
}

public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target)
public override PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true)
{
return new(new MethodInfoFunctionInstance(engine, _methods), PropertyFlag.AllForbidden);
}
Expand Down
6 changes: 3 additions & 3 deletions Jint/Runtime/Interop/Reflection/ReflectionAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ protected virtual object ConvertValueToSet(Engine engine, object value)
return engine.ClrTypeConverter.Convert(value, _memberType, CultureInfo.InvariantCulture);
}

public virtual PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target)
public virtual PropertyDescriptor CreatePropertyDescriptor(Engine engine, object target, bool enumerable = true)
{
return new ReflectionDescriptor(engine, this, target, true);
return new ReflectionDescriptor(engine, this, target, enumerable);
}
}
}
}
2 changes: 1 addition & 1 deletion Jint/Runtime/Interop/TypeReference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ private PropertyDescriptor CreatePropertyDescriptor(string name)
{
var key = new Tuple<Type, string>(ReferenceType, name);
var accessor = _memberAccessors.GetOrAdd(key, x => ResolveMemberAccessor(x.Item1, x.Item2));
return accessor.CreatePropertyDescriptor(_engine, ReferenceType);
return accessor.CreatePropertyDescriptor(_engine, ReferenceType, enumerable: true);
}

private ReflectionAccessor ResolveMemberAccessor(Type type, string name)
Expand Down