Files
Aer/modules/math/math.c
T

865 lines
33 KiB
C

/**
* @PROJECT AerScript Interpreter
* @COPYRIGHT See COPYING in the top level directory
* @FILE modules/math/math.c
* @DESCRIPTION Mathematical class module for AerScript Interpreter
* @DEVELOPERS Symisc Systems <devel@symisc.net>
* Rafal Kupiec <belliash@codingworkshop.eu.org>
*/
#include <float.h>
#include <math.h>
#include "math.h"
/* DBL_TRUE_MIN is C11; the module is compiled as C99 with GNU extensions. */
#ifndef DBL_TRUE_MIN
#define DBL_TRUE_MIN 4.9406564584124654e-324
#endif
/* Full-precision constants, published as Math class constants. */
#define MATH_PI 3.14159265358979323846
#define MATH_E 2.71828182845904523536
#define MATH_TAU 6.28318530717958647692
#define MATH_LN2 0.69314718055994530942
#define MATH_LN10 2.30258509299404568402
#define MATH_LOG2E 1.44269504088896340736
#define MATH_LOG10E 0.43429448190325182765
#define MATH_SQRT2 1.41421356237309504880
#define MATH_SQRT1_2 0.70710678118654752440
#define MATH_EULER_GAMMA 0.57721566490153286061
/* Double mantissa limit: past 2^52 Round() returns the value unchanged. */
#define MATH_TWO_POW_52 4503599627370496.0
/* Class names used by the module. */
#define MCLS_EXC "MathException"
#define MCLS_MATH "Math"
/* Native type shorthands. MIXED keeps strings/bools out of the overload
* filter so the callbacks can report a MathException instead of a fatal. */
#define MTY(T) { PH7_TYPE_##T, 0, 0 }
#define MP(N,T) { N, MTY(T), 0, 0, 0, 0 }
#define MPN(N,X) { N, X, 0, 0, 0, 0 }
/* ------------------------------------------------------------------ */
/* MathException support */
/* ------------------------------------------------------------------ */
static const char *MathErrorDescription(int nErr) {
switch(nErr) {
case MATH_ERROR_NONE: return "No error";
case MATH_ERROR_ARGUMENT_OUT_OF_RANGE: return "Argument out of range";
case MATH_ERROR_ARGUMENT: return "Invalid argument";
case MATH_ERROR_OVERFLOW: return "Overflow";
case MATH_ERROR_ARITHMETIC: return "Arithmetic error";
case MATH_ERROR_DIVIDE_BY_ZERO: return "Divide by zero";
default: return "Unknown error code";
}
}
/* Fetch an inherited (protected) attribute slot straight off the instance.
* PH7_ClassInstanceFetchAttr walks the attribute table without a scope check,
* so the base Exception fields are reachable from this module. */
static ph7_value *MathInstField(ph7_class_instance *pInst, const char *zName) {
SyString s;
if(pInst == 0) {
return 0;
}
SyStringInitFromBuf(&s, zName, (sxu32)SyStrlen(zName));
return PH7_ClassInstanceFetchAttr(pInst, &s);
}
/* Stamp the inherited Exception file/line fields with the first script frame
* of the active call stack. Native frames ([NATIVE], line 0) are skipped so
* catch(Exception $e) observes the place in the script that raised the error. */
static void MathStampSite(ph7_vm *pVm, ph7_class_instance *pInst) {
SySet sTrace;
VmDebugTrace *pTrace;
ph7_value *pField;
if(VmExtractDebugTrace(pVm, &sTrace) != SXRET_OK) {
return;
}
while(SySetGetNextEntry(&sTrace, (void **)&pTrace) == SXRET_OK) {
if(pTrace->pFile == 0 || pTrace->nLine == 0) {
continue;
}
if(pTrace->pFile->nByte == sizeof("[NATIVE]") - 1 &&
SyMemcmp(pTrace->pFile->zString, "[NATIVE]", sizeof("[NATIVE]") - 1) == 0) {
continue;
}
pField = MathInstField(pInst, "file");
if(pField) {
PH7_MemObjRelease(pField);
PH7_MemObjInit(pVm, pField);
(void)ph7_value_string(pField, pTrace->pFile->zString, (int)pTrace->pFile->nByte);
}
pField = MathInstField(pInst, "line");
if(pField) {
(void)ph7_value_int64(pField, (ph7_int64)pTrace->nLine);
}
break;
}
SySetRelease(&sTrace);
}
/* Throw a real MathException object; temporary scalars are always released
* and the instance reference dropped on every error path. */
static int MathThrow(ph7_context *pCtx, int nErr, const char *zMsg) {
ph7_vm *pVm = pCtx->pVm;
ph7_class *pClass;
ph7_class_instance *pInst;
ph7_class_method *pCons;
ph7_value *pObj, *apArg[2], *aTmp[2];
sxi32 rc;
sxu32 n;
if(pVm->iPendingTransfer) {
return PH7_EXCEPTION; /* a handler exception takes precedence */
}
pClass = PH7_VmExtractClass(pVm, MCLS_EXC, sizeof(MCLS_EXC) - 1, FALSE);
if(pClass == 0) {
return PH7_ABORT;
}
pInst = PH7_NewClassInstance(pVm, pClass);
if(pInst == 0) {
PH7_VmMemoryError(pVm);
return PH7_ABORT;
}
for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) {
aTmp[n] = ph7_context_new_scalar(pCtx);
if(aTmp[n] == 0) {
while(n > 0) {
--n;
ph7_context_release_value(pCtx, aTmp[n]);
}
PH7_ClassInstanceUnref(pInst);
PH7_VmMemoryError(pVm);
return PH7_ABORT;
}
}
pObj = ph7_context_new_scalar(pCtx);
if(pObj == 0) {
for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) {
ph7_context_release_value(pCtx, aTmp[n]);
}
PH7_ClassInstanceUnref(pInst);
PH7_VmMemoryError(pVm);
return PH7_ABORT;
}
ph7_value_string(aTmp[0], zMsg, -1);
ph7_value_int(aTmp[1], nErr);
for(n = 0 ; n < SX_ARRAYSIZE(apArg) ; ++n) {
apArg[n] = aTmp[n];
}
pCons = PH7_ClassExtractMethod(pClass, "__construct", sizeof("__construct") - 1);
if(pCons) {
rc = PH7_VmCallClassMethod(pVm, pInst, pCons, 0, 2, apArg);
if(pInst->iRef < 1) {
pInst->iRef = 1;
}
for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) {
ph7_context_release_value(pCtx, aTmp[n]);
}
if(rc != PH7_OK) {
ph7_context_release_value(pCtx, pObj);
PH7_ClassInstanceUnref(pInst);
return rc;
}
} else {
for(n = 0 ; n < SX_ARRAYSIZE(aTmp) ; ++n) {
ph7_context_release_value(pCtx, aTmp[n]);
}
}
MathStampSite(pVm, pInst);
if(pInst->iRef < 1) {
pInst->iRef = 1;
}
PH7_MemObjRelease(pObj);
pObj->x.pOther = pInst;
MemObjSetType(pObj, MEMOBJ_OBJ);
rc = ph7_result_value(pCtx, pObj);
ph7_context_release_value(pCtx, pObj);
return rc == PH7_OK ? PH7_EXCEPTION : rc;
}
/* ------------------------------------------------------------------ */
/* Method callbacks: MathException */
/* ------------------------------------------------------------------ */
static int MathExceptionConstruct(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_value *pResult = ph7_context_new_scalar(pCtx);
sxi32 rc;
SXUNUSED(nArg);
if(pResult == 0) {
return PH7_ABORT;
}
/* Run the base constructor so message/code/file/line/trace/previous keep
* the ordinary Exception semantics for directly constructed instances.
* parent:: lookup is required here: a plain virtual dispatch of
* '__construct' on the receiver would resolve back to this callback.
* apArg[1] is always present: the VM fills an omitted code from the
* registered pDefault snapshot (MATH_ERROR_NONE). */
rc = ph7_context_parent(pCtx, "__construct", 2, apArg, pResult);
return rc;
}
static int MathExceptionDescription(ph7_context *pCtx, int nArg, ph7_value **apArg) {
int nErr = nArg > 0 ? ph7_value_to_int(apArg[0]) : -1;
return ph7_result_string(pCtx, MathErrorDescription(nErr), -1);
}
/* ------------------------------------------------------------------ */
/* Argument helpers */
/* ------------------------------------------------------------------ */
/* Numeric operand: only genuine int/float values are accepted. Strings,
* bools, arrays, objects and NULL all raise ERROR_ARGUMENT (no coercion). */
static int MathOperand(ph7_context *pCtx, ph7_value *pArg, int *pIsInt,
ph7_int64 *pInt, double *pReal) {
if(pArg == 0 || (pArg->nType & MEMOBJ_NULL) ||
(!ph7_value_is_int(pArg) && !ph7_value_is_float(pArg))) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected an int or float argument");
}
*pIsInt = ph7_value_is_int(pArg) ? 1 : 0;
if(*pIsInt) {
*pInt = ph7_value_to_int64(pArg);
*pReal = (double)*pInt;
} else {
*pReal = ph7_value_to_double(pArg);
*pInt = 0;
}
return PH7_OK;
}
static int MathNumber(ph7_context *pCtx, ph7_value *pArg, double *pOut) {
int bIsInt;
ph7_int64 iVal;
return MathOperand(pCtx, pArg, &bIsInt, &iVal, pOut);
}
static int MathInteger(ph7_context *pCtx, ph7_value *pArg, ph7_int64 *pOut) {
if(pArg == 0 || (pArg->nType & MEMOBJ_NULL) || !ph7_value_is_int(pArg)) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected an integer argument");
}
*pOut = ph7_value_to_int64(pArg);
return PH7_OK;
}
/* ------------------------------------------------------------------ */
/* Shared float method bodies */
/* ------------------------------------------------------------------ */
static int MathUnaryFloat(ph7_context *pCtx, int nArg, ph7_value **apArg,
double (*xFunc)(double)) {
double x;
int rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected one numeric argument");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) {
return rc;
}
return ph7_result_double(pCtx, xFunc(x));
}
static int MathBinaryFloat(ph7_context *pCtx, int nArg, ph7_value **apArg,
double (*xFunc)(double, double)) {
double x, y;
int rc;
if(nArg < 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Expected two numeric arguments");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) {
return rc;
}
rc = MathNumber(pCtx, apArg[1], &y);
if(rc != PH7_OK) {
return rc;
}
return ph7_result_double(pCtx, xFunc(x, y));
}
#define MATH_UNARY(Name, Func) \
static int Name(ph7_context *pCtx, int nArg, ph7_value **apArg) { \
return MathUnaryFloat(pCtx, nArg, apArg, Func); \
}
#define MATH_BINARY(Name, Func) \
static int Name(ph7_context *pCtx, int nArg, ph7_value **apArg) { \
return MathBinaryFloat(pCtx, nArg, apArg, Func); \
}
MATH_UNARY(MathSqrt, sqrt)
MATH_UNARY(MathExp, exp)
MATH_UNARY(MathFloor, floor)
MATH_UNARY(MathCeiling, ceil)
MATH_UNARY(MathCos, cos)
MATH_UNARY(MathSin, sin)
MATH_UNARY(MathTan, tan)
MATH_UNARY(MathAcos, acos)
MATH_UNARY(MathAsin, asin)
MATH_UNARY(MathAtan, atan)
MATH_UNARY(MathCosh, cosh)
MATH_UNARY(MathSinh, sinh)
MATH_UNARY(MathTanh, tanh)
MATH_UNARY(MathAcosh, acosh)
MATH_UNARY(MathAsinh, asinh)
MATH_UNARY(MathAtanh, atanh)
MATH_UNARY(MathCbrt, cbrt)
MATH_UNARY(MathLog2, log2)
MATH_UNARY(MathLog10, log10)
MATH_UNARY(MathTruncate, trunc)
MATH_BINARY(MathAtan2, atan2)
MATH_BINARY(MathHypot, hypot)
MATH_BINARY(MathPow, pow)
MATH_BINARY(MathRemainder, fmod)
MATH_BINARY(MathIEEEremainder, remainder)
MATH_BINARY(MathCopySign, copysign)
/* ------------------------------------------------------------------ */
/* Method callbacks: Math */
/* ------------------------------------------------------------------ */
static int MathAbs(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 iVal;
double x;
int bIsInt, rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Abs() expects a value");
}
rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &x);
if(rc != PH7_OK) {
return rc;
}
if(bIsInt) {
/* -SMALLEST_INT64 is undefined; check before negating. */
if(iVal == SMALLEST_INT64) {
return MathThrow(pCtx, MATH_ERROR_OVERFLOW, "Abs() overflows for the smallest integer");
}
return ph7_result_int64(pCtx, iVal < 0 ? -iVal : iVal);
}
return ph7_result_double(pCtx, fabs(x));
}
static int MathSign(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 iVal;
double x;
int bIsInt, rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Sign() expects a value");
}
rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &x);
if(rc != PH7_OK) {
return rc;
}
if(bIsInt) {
return ph7_result_int(pCtx, iVal > 0 ? 1 : (iVal < 0 ? -1 : 0));
}
if(isnan(x)) {
return MathThrow(pCtx, MATH_ERROR_ARITHMETIC, "Sign() is undefined for NaN");
}
return ph7_result_int(pCtx, x > 0.0 ? 1 : (x < 0.0 ? -1 : 0));
}
static int MathLog(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 iVal;
double a, b;
int bIsInt, bHasBase, rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Log() expects a value");
}
rc = MathOperand(pCtx, apArg[0], &bIsInt, &iVal, &a);
if(rc != PH7_OK) {
return rc;
}
/* The default newBase is a NULL snapshot, delivered by the VM as VOID;
* a zero base is a genuine argument. Strings/bools still reach
* MathNumber(), which reports ERROR_ARGUMENT without coercion. */
bHasBase = nArg > 1 && apArg[1] != 0 && (apArg[1]->nType & (MEMOBJ_VOID | MEMOBJ_NULL)) == 0;
if(!bHasBase) {
return ph7_result_double(pCtx, log(a));
}
rc = MathNumber(pCtx, apArg[1], &b);
if(rc != PH7_OK) {
return rc;
}
if(isnan(a) || isnan(b)) {
return ph7_result_double(pCtx, NAN);
}
if(b == 1.0) {
return ph7_result_double(pCtx, NAN);
}
if(a != 1.0 && (b == 0.0 || b == INFINITY)) {
return ph7_result_double(pCtx, NAN);
}
return ph7_result_double(pCtx, log(a) / log(b));
}
/* Max/Min compare as floats whenever either operand is a float. NaN wins;
* on a tie the sign bit decides, so Max(-0.0, 0.0) is +0.0 and
* Min(-0.0, 0.0) is -0.0. */
static int MathExtreme(ph7_context *pCtx, int nArg, ph7_value **apArg, int bWantMax) {
ph7_int64 ia, ib;
double a, b;
int ba, bb, rc;
if(nArg != 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT,
bWantMax ? "Max() expects exactly two arguments" : "Min() expects exactly two arguments");
}
rc = MathOperand(pCtx, apArg[0], &ba, &ia, &a);
if(rc != PH7_OK) {
return rc;
}
rc = MathOperand(pCtx, apArg[1], &bb, &ib, &b);
if(rc != PH7_OK) {
return rc;
}
if(isnan(a) || isnan(b)) {
return ph7_result_double(pCtx, NAN);
}
if(ba && bb) {
return ph7_result_int64(pCtx, bWantMax ? (ia > ib ? ia : ib) : (ia < ib ? ia : ib));
}
if(a > b) {
return ph7_result_double(pCtx, bWantMax ? a : b);
}
if(b > a) {
return ph7_result_double(pCtx, bWantMax ? b : a);
}
/* Numeric tie: +0 outranks -0 for Max and loses for Min. */
if(bWantMax) {
return ph7_result_double(pCtx, signbit(a) ? b : a);
}
return ph7_result_double(pCtx, signbit(a) ? a : b);
}
static int MathMax(ph7_context *pCtx, int nArg, ph7_value **apArg) {
return MathExtreme(pCtx, nArg, apArg, 1);
}
static int MathMin(ph7_context *pCtx, int nArg, ph7_value **apArg) {
return MathExtreme(pCtx, nArg, apArg, 0);
}
static int MathClamp(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 iv, iMin, iMax;
double v, dMin, dMax;
int bAllInt = 1, bIsInt, rc;
if(nArg != 3) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Clamp() expects exactly three arguments");
}
rc = MathOperand(pCtx, apArg[0], &bIsInt, &iv, &v);
if(rc != PH7_OK) return rc;
bAllInt = bIsInt;
rc = MathOperand(pCtx, apArg[1], &bIsInt, &iMin, &dMin);
if(rc != PH7_OK) return rc;
bAllInt = bAllInt && bIsInt;
rc = MathOperand(pCtx, apArg[2], &bIsInt, &iMax, &dMax);
if(rc != PH7_OK) return rc;
bAllInt = bAllInt && bIsInt;
/* Compare integral bounds before converting to double: INT64_MAX and
* INT64_MAX - 1 collapse to the same double, hiding min > max. For real
* bounds a NaN makes '>' false, which is the .NET Math.Clamp(double)
* behavior: the comparisons below then simply fall through to value. */
if(bAllInt ? (iMin > iMax) : (dMin > dMax)) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Clamp() requires min <= max");
}
if(bAllInt) {
if(iv < iMin) return ph7_result_int64(pCtx, iMin);
if(iv > iMax) return ph7_result_int64(pCtx, iMax);
return ph7_result_int64(pCtx, iv);
}
if(v < dMin) return ph7_result_double(pCtx, dMin);
if(v > dMax) return ph7_result_double(pCtx, dMax);
return ph7_result_double(pCtx, v);
}
static double MathToRadiansFn(double x) {
return x * (MATH_PI / 180.0);
}
static double MathToDegreesFn(double x) {
return x * (180.0 / MATH_PI);
}
MATH_UNARY(MathToRadians, MathToRadiansFn)
MATH_UNARY(MathToDegrees, MathToDegreesFn)
/* .NET BitIncrement: NaN and +inf pass through, -inf saturates to -DBL_MAX,
* either zero becomes the smallest positive subnormal. */
static double MathBitIncrementFn(double x) {
if(isnan(x) || x == INFINITY) return x;
if(x == -INFINITY) return -DBL_MAX;
if(x == 0.0) return DBL_TRUE_MIN;
return nextafter(x, INFINITY);
}
static double MathBitDecrementFn(double x) {
if(isnan(x) || x == -INFINITY) return x;
if(x == INFINITY) return DBL_MAX;
if(x == 0.0) return -DBL_TRUE_MIN;
return nextafter(x, -INFINITY);
}
MATH_UNARY(MathBitIncrement, MathBitIncrementFn)
MATH_UNARY(MathBitDecrement, MathBitDecrementFn)
/* MaxMagnitude/MinMagnitude propagate NaN and break |x| == |y| ties with
* Max/Min, which prefer +0 over -0. */
static int MathMagnitude(ph7_context *pCtx, int nArg, ph7_value **apArg, int bWantMax) {
double x, y, ax, ay;
int rc;
if(nArg != 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT,
bWantMax ? "MaxMagnitude() expects exactly two arguments" :
"MinMagnitude() expects exactly two arguments");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) return rc;
rc = MathNumber(pCtx, apArg[1], &y);
if(rc != PH7_OK) return rc;
if(isnan(x) || isnan(y)) return ph7_result_double(pCtx, NAN);
ax = fabs(x);
ay = fabs(y);
if(ax > ay) return ph7_result_double(pCtx, x);
if(ay > ax) return ph7_result_double(pCtx, y);
if(bWantMax) return ph7_result_double(pCtx, signbit(x) ? y : x);
return ph7_result_double(pCtx, signbit(x) ? x : y);
}
static int MathMaxMagnitude(ph7_context *pCtx, int nArg, ph7_value **apArg) {
return MathMagnitude(pCtx, nArg, apArg, 1);
}
static int MathMinMagnitude(ph7_context *pCtx, int nArg, ph7_value **apArg) {
return MathMagnitude(pCtx, nArg, apArg, 0);
}
static int MathILogB(ph7_context *pCtx, int nArg, ph7_value **apArg) {
double x;
int rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "ILogB() expects a value");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) {
return rc;
}
if(x == 0.0) return ph7_result_int(pCtx, (-2147483647 - 1));
if(isnan(x) || isinf(x)) return ph7_result_int(pCtx, 2147483647);
return ph7_result_int(pCtx, ilogb(x));
}
static int MathScaleB(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 n;
double x;
int rc;
if(nArg < 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "ScaleB() expects a value and an exponent");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) return rc;
rc = MathInteger(pCtx, apArg[1], &n);
if(rc != PH7_OK) return rc;
if(n < (-2147483647 - 1) || n > 2147483647) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT_OUT_OF_RANGE,
"ScaleB() exponent is outside the int32 range");
}
return ph7_result_double(pCtx, scalbn(x, (int)n));
}
static int MathFusedMultiplyAdd(ph7_context *pCtx, int nArg, ph7_value **apArg) {
double x, y, z;
int rc;
if(nArg < 3) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FusedMultiplyAdd() expects three values");
}
rc = MathNumber(pCtx, apArg[0], &x);
if(rc != PH7_OK) return rc;
rc = MathNumber(pCtx, apArg[1], &y);
if(rc != PH7_OK) return rc;
rc = MathNumber(pCtx, apArg[2], &z);
if(rc != PH7_OK) return rc;
return ph7_result_double(pCtx, fma(x, y, z));
}
/* Java-style integer division/modulo: round the quotient towards -infinity.
* The INT64_MIN / -1 quotient (+2^63) is unrepresentable, so FloorDiv raises
* ERROR_OVERFLOW instead of negating SMALLEST_INT64 (undefined in C). */
static int MathFloorDiv(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 a, b, q, r;
int rc;
if(nArg < 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FloorDiv() expects two integers");
}
rc = MathInteger(pCtx, apArg[0], &a);
if(rc != PH7_OK) return rc;
rc = MathInteger(pCtx, apArg[1], &b);
if(rc != PH7_OK) return rc;
if(b == 0) {
return MathThrow(pCtx, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero");
}
if(b == -1) {
if(a == SMALLEST_INT64) {
return MathThrow(pCtx, MATH_ERROR_OVERFLOW, "FloorDiv() overflows for the smallest integer");
}
return ph7_result_int64(pCtx, -a);
}
q = a / b;
r = a % b;
if(r != 0 && ((r < 0) != (b < 0))) {
--q;
}
return ph7_result_int64(pCtx, q);
}
static int MathFloorMod(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 a, b, r;
int rc;
if(nArg < 2) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "FloorMod() expects two integers");
}
rc = MathInteger(pCtx, apArg[0], &a);
if(rc != PH7_OK) return rc;
rc = MathInteger(pCtx, apArg[1], &b);
if(rc != PH7_OK) return rc;
if(b == 0) {
return MathThrow(pCtx, MATH_ERROR_DIVIDE_BY_ZERO, "Division by zero");
}
if(b == -1) {
return ph7_result_int64(pCtx, 0);
}
r = a % b;
if(r != 0 && ((r < 0) != (b < 0))) {
r += b;
}
return ph7_result_int64(pCtx, r);
}
/* Exact powers of ten used by Round(); a table avoids pow(10,n) drift. */
static double MathPow10(int n) {
static const double aPow10[] = {
1.0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7,
1.0e8, 1.0e9, 1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15
};
return aPow10[n];
}
static double MathRoundMidpoint(double x, int mode) {
double f, r;
switch(mode) {
/* C99 round() is half away from zero. floor(x + 0.5)/ceil(x - 0.5)
* mis-round the largest double below the midpoint: adding 0.5 to
* 0.49999999999999994 rounds up to 1.0 before floor() sees it. */
case 1: return round(x);
case 2: return trunc(x);
case 3: return floor(x);
case 4: return ceil(x);
default: /* ROUND_TO_EVEN */
f = floor(x);
r = x - f;
if(r > 0.5) return f + 1.0;
if(r < 0.5) return f;
return fmod(f, 2.0) == 0.0 ? f : f + 1.0;
}
}
/* Round(value, digits, mode). There is deliberately no two-argument
* Round(value, mode) overload: pass Round(value, 0, mode) instead.
* The integral and fractional parts are split with modf() before scaling by a
* power of ten. Scaling the whole value would round the intermediate product
* (2.675 * 100 is exactly 267.5 in binary floating point) and turn a value
* that is actually stored just below the midpoint into 2.68; scaling only the
* fraction keeps Round(2.675, 2) at 2.67. For digits == 0 there is no scaling
* to protect, so the whole value is rounded directly: the midpoint parity
* check must see the real integral part, not the isolated fraction. */
static int MathRound(ph7_context *pCtx, int nArg, ph7_value **apArg) {
ph7_int64 iDigits, iMode, iDummy;
double value, scaled, result, scale, intPart;
int bIsInt, bNegative, rc;
if(nArg < 1) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT, "Round() expects a value");
}
rc = MathOperand(pCtx, apArg[0], &bIsInt, &iDummy, &value);
if(rc != PH7_OK) return rc;
rc = MathInteger(pCtx, nArg > 1 ? apArg[1] : 0, &iDigits);
if(rc != PH7_OK) return rc;
rc = MathInteger(pCtx, nArg > 2 ? apArg[2] : 0, &iMode);
if(rc != PH7_OK) return rc;
if(iDigits < 0 || iDigits > 15) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT_OUT_OF_RANGE,
"Round() digits must be between 0 and 15");
}
if(iMode < 0 || iMode > 4) {
return MathThrow(pCtx, MATH_ERROR_ARGUMENT,
"Round() mode is not a known MidpointRounding value");
}
if(isnan(value) || isinf(value) || fabs(value) >= MATH_TWO_POW_52) {
return ph7_result_double(pCtx, value);
}
scale = MathPow10((int)iDigits);
if(iDigits == 0) {
/* Round the whole value: ROUND_TO_EVEN needs the parity of the real
* integral part, which is lost when the fraction is split off (the
* split fraction always has f == 0 and would round every midpoint
* down to the even candidate below it). */
result = MathRoundMidpoint(value, (int)iMode);
bNegative = signbit(value) ? 1 : 0;
} else {
scaled = modf(value, &intPart) * scale;
if(!isfinite(scaled)) {
return ph7_result_double(pCtx, value);
}
bNegative = signbit(scaled) ? 1 : 0;
result = intPart + MathRoundMidpoint(scaled, (int)iMode) / scale;
}
if(result == 0.0 && bNegative) {
result = -0.0;
}
return ph7_result_double(pCtx, result);
}
/* ------------------------------------------------------------------ */
/* Native class registration */
/* ------------------------------------------------------------------ */
static ph7_constant_def aMathConst[] = {
{ "PI", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "E", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "TAU", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "LN2", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "LN10", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "LOG2E", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "LOG10E", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "SQRT2", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "SQRT1_2", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "EULER_GAMMA", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ROUND_TO_EVEN", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ROUND_AWAY_FROM_ZERO", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ROUND_TO_ZERO", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ROUND_TO_NEGATIVE_INFINITY", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ROUND_TO_POSITIVE_INFINITY", 0, PH7_MEMBER_PUBLIC, 0, 0 },
};
static const double aMathValue[] = {
MATH_PI, MATH_E, MATH_TAU, MATH_LN2, MATH_LN10,
MATH_LOG2E, MATH_LOG10E, MATH_SQRT2, MATH_SQRT1_2, MATH_EULER_GAMMA
};
static ph7_constant_def aExceptionConst[] = {
{ "ERROR_NONE", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ERROR_ARGUMENT_OUT_OF_RANGE", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ERROR_ARGUMENT", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ERROR_OVERFLOW", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ERROR_ARITHMETIC", 0, PH7_MEMBER_PUBLIC, 0, 0 },
{ "ERROR_DIVIDE_BY_ZERO", 0, PH7_MEMBER_PUBLIC, 0, 0 },
};
static const int aExceptionValue[] = {
MATH_ERROR_NONE, MATH_ERROR_ARGUMENT_OUT_OF_RANGE, MATH_ERROR_ARGUMENT,
MATH_ERROR_OVERFLOW, MATH_ERROR_ARITHMETIC, MATH_ERROR_DIVIDE_BY_ZERO
};
static sxi32 MathRegisterClasses(ph7_vm *pVm) {
static ph7_param_def aExcCtor[] = {
MP("message", STRING), MP("code", INT)
};
static const ph7_param_def aExcDesc[] = { MP("code", INT) };
static const ph7_param_def aOne[] = { MP("value", MIXED) };
static const ph7_param_def aTwo[] = { MP("x", MIXED), MP("y", MIXED) };
static const ph7_param_def aThree[] = {
MP("x", MIXED), MP("y", MIXED), MP("z", MIXED)
};
static ph7_param_def aRound[] = {
MP("value", MIXED), MP("digits", INT), MP("mode", INT)
};
static ph7_param_def aLog[] = {
MP("value", MIXED), MPN("newBase", MTY(MIXED))
};
static const ph7_param_def aScaleB[] = {
MP("x", MIXED), MP("n", INT)
};
static const ph7_method_def aExcMethod[] = {
{ "__construct", MTY(VOID), aExcCtor, 2, MathExceptionConstruct, 0, 0 },
{ "GetDescription", MTY(STRING), aExcDesc, 1, MathExceptionDescription, 0,
PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC }
};
static const ph7_method_def aMathMethod[] = {
{ "Abs", MTY(MIXED), aOne, 1, MathAbs, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Acos", MTY(FLOAT), aOne, 1, MathAcos, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Acosh", MTY(FLOAT), aOne, 1, MathAcosh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Asin", MTY(FLOAT), aOne, 1, MathAsin, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Asinh", MTY(FLOAT), aOne, 1, MathAsinh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Atan", MTY(FLOAT), aOne, 1, MathAtan, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Atanh", MTY(FLOAT), aOne, 1, MathAtanh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Atan2", MTY(FLOAT), aTwo, 2, MathAtan2, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "BitDecrement", MTY(FLOAT), aOne, 1, MathBitDecrement, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "BitIncrement", MTY(FLOAT), aOne, 1, MathBitIncrement, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Cbrt", MTY(FLOAT), aOne, 1, MathCbrt, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Ceiling", MTY(FLOAT), aOne, 1, MathCeiling, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Clamp", MTY(MIXED), aThree, 3, MathClamp, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "CopySign", MTY(FLOAT), aTwo, 2, MathCopySign, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Cos", MTY(FLOAT), aOne, 1, MathCos, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Cosh", MTY(FLOAT), aOne, 1, MathCosh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Exp", MTY(FLOAT), aOne, 1, MathExp, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Floor", MTY(FLOAT), aOne, 1, MathFloor, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "FloorDiv", MTY(INT), aTwo, 2, MathFloorDiv, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "FloorMod", MTY(INT), aTwo, 2, MathFloorMod, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "FusedMultiplyAdd", MTY(FLOAT), aThree, 3, MathFusedMultiplyAdd, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Hypot", MTY(FLOAT), aTwo, 2, MathHypot, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "IEEERemainder", MTY(FLOAT), aTwo, 2, MathIEEEremainder, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "ILogB", MTY(INT), aOne, 1, MathILogB, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Log", MTY(FLOAT), aLog, 2, MathLog, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Log10", MTY(FLOAT), aOne, 1, MathLog10, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Log2", MTY(FLOAT), aOne, 1, MathLog2, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Max", MTY(MIXED), aTwo, 2, MathMax, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "MaxMagnitude", MTY(FLOAT), aTwo, 2, MathMaxMagnitude, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Min", MTY(MIXED), aTwo, 2, MathMin, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "MinMagnitude", MTY(FLOAT), aTwo, 2, MathMinMagnitude, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Pow", MTY(FLOAT), aTwo, 2, MathPow, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Remainder", MTY(FLOAT), aTwo, 2, MathRemainder, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Round", MTY(FLOAT), aRound, 3, MathRound, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "ScaleB", MTY(FLOAT), aScaleB, 2, MathScaleB, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Sign", MTY(INT), aOne, 1, MathSign, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Sin", MTY(FLOAT), aOne, 1, MathSin, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Sinh", MTY(FLOAT), aOne, 1, MathSinh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Sqrt", MTY(FLOAT), aOne, 1, MathSqrt, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Tan", MTY(FLOAT), aOne, 1, MathTan, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Tanh", MTY(FLOAT), aOne, 1, MathTanh, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "ToDegrees", MTY(FLOAT), aOne, 1, MathToDegrees, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "ToRadians", MTY(FLOAT), aOne, 1, MathToRadians, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
{ "Truncate", MTY(FLOAT), aOne, 1, MathTruncate, 0, PH7_MEMBER_PUBLIC | PH7_MEMBER_STATIC },
};
static const char *const aExcBase[] = { "Exception" };
ph7_class_def sExc = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, MCLS_EXC,
0, 0, aExceptionConst, SX_ARRAYSIZE(aExceptionConst),
aExcMethod, SX_ARRAYSIZE(aExcMethod), 0, aExcBase, 1, 0, 0, 0, 0 };
ph7_class_def sMath = { sizeof(ph7_class_def), PH7_CLASS_DEF_VERSION, MCLS_MATH,
0, 0, aMathConst, SX_ARRAYSIZE(aMathConst),
aMathMethod, SX_ARRAYSIZE(aMathMethod),
PH7_DECL_FINAL | PH7_DECL_VIRTUAL, 0, 0, 0, 0, 0, 0 };
ph7_value *apMath[SX_ARRAYSIZE(aMathConst)];
ph7_value *apExc[SX_ARRAYSIZE(aExceptionConst)];
ph7_value *apDefault[4];
sxu32 n;
sxi32 rc = PH7_OK;
SyZero(apMath, sizeof(apMath));
SyZero(apExc, sizeof(apExc));
SyZero(apDefault, sizeof(apDefault));
/* Constant and default snapshots. A fresh scalar is NULL, which is the
* exact default required for Log()'s optional newBase. */
for(n = 0 ; n < SX_ARRAYSIZE(apMath) ; ++n) {
apMath[n] = ph7_new_scalar(pVm);
if(apMath[n] == 0) { rc = PH7_NOMEM; goto Cleanup; }
if(n < SX_ARRAYSIZE(aMathValue)) {
ph7_value_double(apMath[n], aMathValue[n]);
} else {
ph7_value_int(apMath[n], (int)(n - SX_ARRAYSIZE(aMathValue)));
}
aMathConst[n].pValue = apMath[n];
}
for(n = 0 ; n < SX_ARRAYSIZE(apExc) ; ++n) {
apExc[n] = ph7_new_scalar(pVm);
if(apExc[n] == 0) { rc = PH7_NOMEM; goto Cleanup; }
ph7_value_int(apExc[n], aExceptionValue[n]);
aExceptionConst[n].pValue = apExc[n];
}
for(n = 0 ; n < 2 ; ++n) {
apDefault[n] = ph7_new_scalar(pVm);
if(apDefault[n] == 0) { rc = PH7_NOMEM; goto Cleanup; }
ph7_value_int(apDefault[n], 0);
}
/* A fresh scalar is NULL: this is Log()'s omitted-base sentinel. */
apDefault[2] = ph7_new_scalar(pVm);
if(apDefault[2] == 0) { rc = PH7_NOMEM; goto Cleanup; }
/* MathException("message") gets code 0 from this snapshot, as in JSON. */
apDefault[3] = ph7_new_scalar(pVm);
if(apDefault[3] == 0) { rc = PH7_NOMEM; goto Cleanup; }
ph7_value_int(apDefault[3], MATH_ERROR_NONE);
aRound[1].pDefault = apDefault[0];
aRound[2].pDefault = apDefault[1];
aLog[1].pDefault = apDefault[2];
aExcCtor[1].pDefault = apDefault[3];
rc = ph7_create_class(pVm, &sExc);
if(rc == PH7_OK) rc = ph7_create_class(pVm, &sMath);
Cleanup:
aRound[1].pDefault = 0;
aRound[2].pDefault = 0;
aLog[1].pDefault = 0;
aExcCtor[1].pDefault = 0;
for(n = 0 ; n < SX_ARRAYSIZE(apDefault) ; ++n) {
if(apDefault[n]) {
ph7_release_value(pVm, apDefault[n]);
}
}
for(n = 0 ; n < SX_ARRAYSIZE(apExc) ; ++n) {
if(apExc[n]) {
ph7_release_value(pVm, apExc[n]);
aExceptionConst[n].pValue = 0;
}
}
for(n = 0 ; n < SX_ARRAYSIZE(apMath) ; ++n) {
if(apMath[n]) {
ph7_release_value(pVm, apMath[n]);
aMathConst[n].pValue = 0;
}
}
return rc;
}
PH7_PRIVATE sxi32 initializeModule(ph7_vm *pVm, ph7_real *ver, SyString *desc) {
desc->zString = MODULE_DESC;
*ver = MODULE_VER;
return MathRegisterClasses(pVm);
}