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

Add interop option ThrowOnUnresolvedMember #1904

Merged
merged 1 commit into from
Jun 27, 2024
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
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