Skip to content

Commit

Permalink
Improve invalid class private member access member errors (#1922)
Browse files Browse the repository at this point in the history
  • Loading branch information
lahma authored Jul 22, 2024
1 parent 995e8c9 commit dc129c7
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
31 changes: 31 additions & 0 deletions Jint.Tests/Runtime/ClassTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Jint.Runtime;

namespace Jint.Tests.Runtime;

public class ClassTests
Expand Down Expand Up @@ -45,4 +47,33 @@ get doubleWidth () {
Assert.Equal(10, engine.Evaluate("board.width"));
Assert.Equal(20, engine.Evaluate("board.doubleWidth "));
}

[Fact]
public void PrivateMemberAccessOutsideOfClass()
{
var ex = Assert.Throws<JavaScriptException>(() => new Engine().Evaluate
(
"""
class A { }
new A().#nonexistent = 1;
"""
));

Assert.Equal("Unexpected identifier '#nonexistent'", ex.Message);
}

[Fact]
public void PrivateMemberAccessAgainstUnknownMemberInConstructor()
{
var ex = Assert.Throws<JavaScriptException>(() => new Engine().Evaluate
(
"""
class A { constructor() { #nonexistent = 2; } }
new A();
"""
));

Assert.Equal("Unexpected identifier '#nonexistent'", ex.Message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ protected override object EvaluateInternal(EvaluationContext context)
var engine = context.Engine;
var env = engine.ExecutionContext.PrivateEnvironment;

var privateIdentifier = env!.ResolvePrivateIdentifier(_privateIdentifierString);
var privateIdentifier = env?.ResolvePrivateIdentifier(_privateIdentifierString);
if (privateIdentifier is not null)
{
return privateIdentifier;
}

ExceptionHelper.ThrowReferenceError(engine.Realm, "TODO Not found!!");
ExceptionHelper.ThrowSyntaxError(engine.Realm, $"Unexpected identifier '#{_privateIdentifierString}'");
return null;
}
}

0 comments on commit dc129c7

Please sign in to comment.