Skip to content

Commit

Permalink
Add interop option ThrowOnUnresolvedMember (#1904)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Jun 27, 2024
1 parent dafb525 commit 4eecccb
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 1 deletion.
24 changes: 23 additions & 1 deletion Jint.Tests/Runtime/InteropTests.MemberAccess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ public TValue this[string key]

public class ClassWithData
{
public int Age => 42;

public DataType Data { get; set; }

public class DataType
Expand All @@ -253,10 +255,30 @@ public void NewTypedObjectFromUntypedInitializerShouldBeMapped()
var engine = new Engine();

engine.SetValue("obj", new ClassWithData());
engine.Execute(@"obj.Data = { Value: '123' };");
engine.Execute("obj.Data = { Value: '123' };");
var obj = engine.Evaluate("obj").ToObject() as ClassWithData;

Assert.Equal("123", obj?.Data.Value);
}

[Fact]
public void CanConfigureStrictAccess()
{
var engine = new Engine();

engine.SetValue("obj", new ClassWithData());
engine.Evaluate("obj.Age").AsNumber().Should().Be(42);
engine.Evaluate("obj.AgeMissing").Should().Be(JsValue.Undefined);

engine = new Engine(options =>
{
options.Interop.ThrowOnUnresolvedMember = true;
});

engine.SetValue("obj", new ClassWithData());
engine.Evaluate("obj.Age").AsNumber().Should().Be(42);

engine.Invoking(e => e.Evaluate("obj.AgeMissing")).Should().Throw<MissingMemberException>();
}
}
}
5 changes: 5 additions & 0 deletions Jint/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,11 @@ public class InteropOptions
/// Should the Array prototype be attached instead of Object prototype to the wrapped interop objects when type looks suitable. Defaults to true.
/// </summary>
public bool AttachArrayPrototype { get; set; } = true;

/// <summary>
/// Whether the engine should throw an error when a member is not found on a CLR object. Defaults to false.
/// </summary>
public bool ThrowOnUnresolvedMember { get; set; }
}

public class ConstraintOptions
Expand Down
5 changes: 5 additions & 0 deletions Jint/Runtime/Interop/TypeResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,11 @@ private ReflectionAccessor ResolvePropertyDescriptorFactory(
}
}

if (engine.Options.Interop.ThrowOnUnresolvedMember)
{
throw new MissingMemberException($"Cannot access property '{memberName}' on type '{type.FullName}");
}

return ConstantValueAccessor.NullAccessor;
}

Expand Down

0 comments on commit 4eecccb

Please sign in to comment.