/**
 * Modern Albufeira Prolog Interpreter
 *
 * Warranty & Liability
 * To the extent permitted by applicable law and unless explicitly
 * otherwise agreed upon, XLOG Technologies AG makes no warranties
 * regarding the provided information. XLOG Technologies AG assumes
 * no liability that any problems might be solved with the information
 * provided by XLOG Technologies AG.
 *
 * Rights & License
 * All industrial property rights regarding the information - copyright
 * and patent rights in particular - are the sole property of XLOG
 * Technologies AG. If the company was not the originator of some
 * excerpts, XLOG Technologies AG has at least obtained the right to
 * reproduce, change and translate the information.
 *
 * Reproduction is restricted to the whole unaltered document. Reproduction
 * of the information is only allowed for non-commercial uses. Selling,
 * giving away or letting of the execution of the library is prohibited.
 * The library can be distributed as part of your applications and libraries
 * for execution provided this comment remains unchanged.
 *
 * Restrictions
 * Only to be distributed with programs that add significant and primary
 * functionality to the library. Not to be distributed with additional
 * software intended to replace any components of the library.
 *
 * Trademarks
 * Jekejeke is a registered trademark of XLOG Technologies AG.
 */

import {check_integer, is_bigint, exec_eval, exec_build,
    widen_bigint, norm_bigint, make_error, Compound,
    set, make_check, norm_float,
    exec_unify, make_arithmetic,
} from "../nova/core.mjs";

/*********************************************************************/
/* Random Numbers                                                    */
/*********************************************************************/

/**
 * random(F):
 * The predicate succeeds in F with a uniform random 64-bit
 * floating point value in the interval [0..1).
 */
function test_random(args) {
    let alpha = norm_float(Math.random());
    return exec_unify(args[0], alpha);
}

/*********************************************************************/
/* msb/2, lsb/2 and popcount/2                                       */
/*********************************************************************/

/**
 * msb(X):
 * If X is an integer, then the function returns the most significant bit.
 */
function arit_msb(args) {
    let alpha = exec_eval(args[0]);
    check_integer(alpha);
    return bigint_msb(alpha < 0 ? ~alpha : alpha);
}

/**
 * lsb(X):
 * If X is an integer, then the function returns the least significant bit.
 */
function arit_lsb(args) {
    let alpha = exec_eval(args[0]);
    check_integer(alpha);
    return bigint_msb(alpha & -alpha);
}

function bigint_msb(alpha) {
    if (!is_bigint(alpha)) {
        return 31 - Math.clz32(alpha);
    } else {
        alpha = alpha.toString(16);
        return 31 - Math.clz32(parseInt(alpha.at(0), 16)) + (alpha.length - 1) * 4;
    }
}

/**
 * popcount(X):
 * If X is an integer, then the function returns the number of ones.
 */
function arit_popcount(args) {
    let alpha = exec_eval(args[0]);
    check_integer(alpha);
    if (alpha < 0) {
        alpha = -alpha;
        return bigint_popcount(alpha) + bigint_msb(alpha & -alpha) - 1;
    } else {
        return bigint_popcount(alpha);
    }
}

function bigint_popcount(alpha) {
    if (!is_bigint(alpha)) {
        return smallint_popcount(alpha);
    } else {
        alpha = alpha.toString(16);
        let res = 0;
        let i = alpha.length % 8;
        if (i > 0)
            res += smallint_popcount(parseInt(alpha.substring(0,i), 16));
        for (; i < alpha.length; i+=8)
            res += smallint_popcount(parseInt(alpha.substring(i,i+8), 16));
        return res;
    }
}

function smallint_popcount(i) {
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}

/*********************************************************************/
/* testbit/2, sqrtrem/3 and isqrt/2                                  */
/*********************************************************************/

/**
 * testbit(X, Y):
 * The predicate succeeds when X /\ (1 << Y) =\= 0.
 */
function test_testbit(args) {
    let alpha = exec_build(args[0]);
    check_integer(alpha);
    let beta = exec_build(args[1]);
    check_integer(beta);
    if (beta < 0)
        throw make_error(new Compound("domain_error",
            ["not_less_than_zero", beta]));
    return number_testbit(alpha, beta);
}

function number_testbit(alpha, beta) {
    if (!is_bigint(alpha) && !is_bigint(beta)) {
        if (beta < 31) {
            return (alpha & (1 << beta)) !== 0;
        } else {
            return alpha < 0;
        }
    } else {
        return (widen_bigint(alpha) & (1n << widen_bigint(beta))) !== 0n;
    }
}

/**
 * sqrtrem(X, Y, Z):
 * If X is an integer then the predicate succeeds in Y with the
 * integer square root of X, and in Z with the remainder X-Y*Y.
 */
function test_sqrtrem(args) {
    let alpha = exec_build(args[0]);
    check_integer(alpha);
    let ressqrt;
    let resrem;
    if (!is_bigint(alpha)) {
        if (alpha < 0)
            throw make_error(new Compound("domain_error",
                ["not_less_than_zero", alpha]));
        ressqrt = Math.floor(Math.sqrt(alpha));
        resrem = alpha-ressqrt*ressqrt;
    } else {
        if (alpha < 0n)
            throw make_error(new Compound("domain_error",
                ["not_less_than_zero", alpha]));
        let j = bigint_sqrt(alpha);
        ressqrt = norm_bigint(j);
        resrem = norm_bigint(alpha-j*j);
    }
    if (!exec_unify(args[1], ressqrt))
        return false;
    return exec_unify(args[2], resrem);
}

/**
 * isqrt(X, Y):
 * If X is an integer then the predicate succeeds in Y with the
 * integer square root of X.
 */
function arit_isqrt(args) {
    let alpha = exec_eval(args[0]);
    check_integer(alpha);
    let ressqrt;
    if (!is_bigint(alpha)) {
        if (alpha < 0)
            throw make_error(new Compound("domain_error",
                ["not_less_than_zero", alpha]));
        ressqrt = Math.floor(Math.sqrt(alpha));
    } else {
        if (alpha < 0n)
            throw make_error(new Compound("domain_error",
                ["not_less_than_zero", alpha]));
        let j = bigint_sqrt(alpha);
        ressqrt = norm_bigint(j);
    }
    return ressqrt;
}

function bigint_sqrt(n) {
    let x0 = n >> 1n;
    for (;;) {
        let x1 = (n / x0 + x0) >> 1n;
        if (x1 >= x0) {
            return x0;
        }
        x0 = x1;
    }
}

/*********************************************************************/
/* Bit Lib Init                                                      */
/*********************************************************************/

export function main() {
    set("random", 1, make_check(test_random));
    set("msb", 2, make_arithmetic(arit_msb));
    set("lsb", 2, make_arithmetic(arit_lsb));
    set("popcount", 2, make_arithmetic(arit_popcount));
    set("testbit", 2, make_check(test_testbit));
    set("sqrtrem", 3, make_check(test_sqrtrem));
    set("isqrt", 2, make_arithmetic(arit_isqrt));
}

