felixhao28 / JSCPP

A simple C++ interpreter written in JavaScript

Home Page:https://felixhao28.github.io/JSCPP/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

If the loop nesting is empty, it becomes an infinite loop.

ahogappa0613 opened this issue · comments

I've found what appears to be a bug.

You will end up with an infinite loop, code like this:

#include<stdio.h>
int main() {
    while(true){
        
    }
    return 0;
}

This seemed to have been fixed with a fix of debugger.ts:

continue() {
        while (true) {
            const done = this.next();
            if (done !== false) { return done; }
            const curStmt = this.nextNode();
+           if (curStmt === this.prevNode) { return false; }
            for (const name of Object.keys(this.stopConditions)) {
                const active = this.stopConditions[name];
                if (active) {
                    if (this.conditions[name](this.prevNode, curStmt)) {
                        return false;
                    }
                }
            }
        }
    }

However, the following program will not work

#include<stdio.h>
int main() {
    while(true == true){
        
    }
    return 0;
}

What should I do in such a case?

An infinite loop is not exactly easy to detect during runtime (sometimes it is even the desired behavior). If you are trying to detect infinite loops to prevent abuses, I suggest running JSCPP in a WebWorker or a separate thread/process and set a timeout to kill it when needed.

I just realized there is a "maxTimeout" option. You can use this to see if it works in your favor.

var JSCPP = require("JSCPP");
var code =    "#include <iostream>"
            + "using namespace std;"
            + "int main() {"
            + "    while(true == true){"
            + "    "
            + "    }"
            + "    return 0;"
            + "}"
;
try {
  var exitcode = JSCPP.run(code, "", { maxTimeout: 5000 ]);
  console.info("program exited with code " + exitcode);
} catch (e) {
  if (e.message === "Time limit exceeded.") {
    alert("Program did not finish in 5000ms, possiblely due to an infinite loop.");
  }
}