Browse Source

Fix statement counting code in MaxStatementsConstraint (#2035)

* Fix MaxStatementsConstraint

Current implementation of MaxStatementsConstraint allows one more statement to be executed.

* Add unit test
Nicolay Fedarkevich 6 months ago
parent
commit
d928fec045

+ 14 - 0
Jint.Tests/Runtime/ExecutionConstraintTests.cs

@@ -13,6 +13,20 @@ public class ExecutionConstraintTests
         );
     }
 
+    [Fact]
+    public void ShouldCountStatementsPrecisely()
+    {
+        var script = "var x = 0; x++; x + 5";
+
+        // Should not throw if MaxStatements is not exceeded.
+        new Engine(cfg => cfg.MaxStatements(3)).Execute(script);
+
+        // Should throw if MaxStatements is exceeded.
+        Assert.Throws<StatementsCountOverflowException>(
+            () => new Engine(cfg => cfg.MaxStatements(2)).Evaluate(script)
+        );
+    }
+
     [Fact]
     public void ShouldThrowMemoryLimitExceeded()
     {

+ 1 - 1
Jint/Constraints/MaxStatementsConstraint.cs

@@ -18,7 +18,7 @@ public sealed class MaxStatementsConstraint : Constraint
 
     public override void Check()
     {
-        if (MaxStatements > 0 && _statementsCount++ > MaxStatements)
+        if (MaxStatements > 0 && ++_statementsCount > MaxStatements)
         {
             ExceptionHelper.ThrowStatementsCountOverflowException();
         }