Skip to content
This repository has been archived by the owner on Oct 13, 2024. It is now read-only.

Commit

Permalink
Merge pull request #19 from SahilK-027/main
Browse files Browse the repository at this point in the history
Loop Iteration Limit to Handle Infinite While Loops
  • Loading branch information
shashankbhosagi authored Jul 21, 2023
2 parents 82b745c + 224bfbd commit 422e2de
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 17 additions & 0 deletions BackEnd/Interpreter/Statements/Loop/While_statement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,19 @@ export const evaluate_boolean_while_statement = (
stmt: WhileStatement,
env: Environment,
): RuntimeVal => {
let iterationCnt = 0;
let breakLoop = false;
let evaluatedCondition = evaluate(stmt.condition, env) as BooleanVal;
const startTime = performance.now();

while (evaluatedCondition.value && !breakLoop) {
iterationCnt++;

// Check for infinite loop
if (env.checkInfiniteLoop(iterationCnt)) {
break;
}

// Create a new environment for each iteration
const whileEnv = new Environment(env);
for (const statement of stmt.body) {
Expand Down Expand Up @@ -59,10 +68,18 @@ export const evaluate_numeric_while_statement = (
stmt: WhileStatement,
env: Environment,
): RuntimeVal => {
let iterationCnt = 0;
let breakLoop = false;
let evaluatedCondition = evaluate(stmt.condition, env) as NumberVal;

while (evaluatedCondition.value && !breakLoop) {
iterationCnt++;

// Check for infinite loop
if (env.checkInfiniteLoop(iterationCnt)) {
break;
}

// Create a new environment for each iteration
const whileEnv = new Environment(env);
for (const statement of stmt.body) {
Expand Down
12 changes: 11 additions & 1 deletion BackEnd/Scope/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default class Environment {
private parent?: Environment;
private variables: Map<string, RuntimeVal>;
private constants: Set<string>;

private MAX_ALLOWED_ITERATIONS: number;
/**
* Creates an instance of the Environment class.
* @param parentENV - The parent environment (optional).
Expand All @@ -17,6 +17,16 @@ export default class Environment {
this.parent = parentENV;
this.variables = new Map();
this.constants = new Set();
this.MAX_ALLOWED_ITERATIONS = 102702;
}

public checkInfiniteLoop(
iterationCnt: number,
): Boolean {
if (iterationCnt > this.MAX_ALLOWED_ITERATIONS) {
throw `TIME LIMIT EXCEEDED...`;
}
return false;
}

/**
Expand Down

0 comments on commit 422e2de

Please sign in to comment.