Check Division by Zero in JavascriptEngine


#1

Hi Jules, 

 

I am playing around with the marvelous JavascriptEngine and discovered that it really hates division by zero. If you type '1 / 0' into the editor of the Demo, it instantly crashes, which makes stupid script developers a bit too powerful for my taste :)

It would be no problem to catch the exception everytime you run a script, but why didn't you implement the check right at the spot?


 struct DivideOp  : public BinaryOperator
    {
        DivideOp (const CodeLocation& l, ExpPtr& a, ExpPtr& b) noexcept : BinaryOperator (l, a, b, TokenTypes::divide) {}
        var getWithDoubles (double a, double b) const override  { return a / b; }
        var getWithInts (int64 a, int64 b) const override       { return a / b; }
    };

something like



var getWithInts (int64 a, int64 b) const override       { return b == 0 ? var::undefined() : a / b;  }
var getWithDoubles (double a, double b) const override  { return b == 0.0 ? var::undefined() : a / b; }

would prevent the division by zero problem while giving a nice feedback if you do something stupid and doesn't introduce too much overhead.


#2

Excellent suggestion! Is 'undefined' the correct value for a divide by zero in JS?


#3

Well, there is something called 'Infinity':

http://www.w3schools.com/jsref/jsref_infinity.asp

but I don't know how important this is. I think most of the time you made something wrong if you divide by zero, so I guess getting var::undefined should be enough of a hint...

If you check it in, don't forget the modulo operator!


#4

Hmm, looks like the correct thing to do would actually be to return a double which is set to infinity, as that's what other JS interpreters do.