From dc129c7cd511569e097f969441377e9e30b28a58 Mon Sep 17 00:00:00 2001 From: Marko Lahma Date: Mon, 22 Jul 2024 21:33:11 +0300 Subject: [PATCH] Improve invalid class private member access member errors (#1922) --- Jint.Tests/Runtime/ClassTests.cs | 31 +++++++++++++++++++ .../JintPrivateIdentifierExpression.cs | 4 +-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/Jint.Tests/Runtime/ClassTests.cs b/Jint.Tests/Runtime/ClassTests.cs index b644451425..970e61aa1a 100644 --- a/Jint.Tests/Runtime/ClassTests.cs +++ b/Jint.Tests/Runtime/ClassTests.cs @@ -1,3 +1,5 @@ +using Jint.Runtime; + namespace Jint.Tests.Runtime; public class ClassTests @@ -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(() => new Engine().Evaluate + ( + """ + class A { } + + new A().#nonexistent = 1; + """ + )); + + Assert.Equal("Unexpected identifier '#nonexistent'", ex.Message); + } + + [Fact] + public void PrivateMemberAccessAgainstUnknownMemberInConstructor() + { + var ex = Assert.Throws(() => new Engine().Evaluate + ( + """ + class A { constructor() { #nonexistent = 2; } } + new A(); + """ + )); + + Assert.Equal("Unexpected identifier '#nonexistent'", ex.Message); + } } diff --git a/Jint/Runtime/Interpreter/Expressions/JintPrivateIdentifierExpression.cs b/Jint/Runtime/Interpreter/Expressions/JintPrivateIdentifierExpression.cs index 77090bbf85..03764c7f37 100644 --- a/Jint/Runtime/Interpreter/Expressions/JintPrivateIdentifierExpression.cs +++ b/Jint/Runtime/Interpreter/Expressions/JintPrivateIdentifierExpression.cs @@ -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; } }