Skip to content

Commit

Permalink
Check recursion limit in VisitorLevelSpecification (#991)
Browse files Browse the repository at this point in the history
Check recursion limit in `VisitorLevelSpecification` instead of relying on Java's StackOverflowError.

The current implementation may not work, JVM may kill the process when StackOverflowError occurs.
```
  default IExpr acceptChecked(IVisitor visitor) {
    try {
      return accept(visitor);
    } catch (StackOverflowError soe) {
      RecursionLimitExceeded.throwIt(Integer.MAX_VALUE, this);
    }
    return F.NIL;
  }
```

Co-authored-by: Duy Tran <mail@duytran.com>
  • Loading branch information
tranleduy2000 and Duy Tran committed May 23, 2024
1 parent 83453c6 commit a0002b6
Showing 1 changed file with 11 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package org.matheclipse.core.visit;

import java.util.function.Function;

import org.matheclipse.core.basic.Config;
import org.matheclipse.core.eval.EvalEngine;
import org.matheclipse.core.eval.exception.RecursionLimitExceeded;
import org.matheclipse.core.eval.exception.SymjaMathException;
import org.matheclipse.core.expression.F;
import org.matheclipse.core.interfaces.IASTMutable;
Expand Down Expand Up @@ -188,6 +191,7 @@ public IExpr visit(IAssociation assoc) {
int[] minDepth = new int[] {0};
try {
fCurrentLevel++;
checkRecursionLimit(assoc);
if (fIncludeHeads) {
// no include head for associations
}
Expand Down Expand Up @@ -228,6 +232,7 @@ public IExpr visit(IASTMutable ast) {
int[] minDepth = new int[] {0};
try {
fCurrentLevel++;
checkRecursionLimit(ast);
if (fIncludeHeads) {
final IExpr temp = ast.get(0).accept(this);
if (temp.isPresent()) {
Expand Down Expand Up @@ -270,6 +275,12 @@ public IExpr visit(IASTMutable ast) {
return result[0];
}

private void checkRecursionLimit(IExpr expr) {
if (this.fCurrentLevel > EvalEngine.get().getRecursionLimit()) {
RecursionLimitExceeded.throwIt(this.fCurrentLevel, expr);
}
}

/**
* Can be overridden in derived visitors.
*
Expand Down

0 comments on commit a0002b6

Please sign in to comment.