/* Common code for the PPL Java interface tests.
   Copyright (C) 2001-2010 Roberto Bagnara
   Copyright (C) 2010-2026 BUGSENG srl (http://bugseng.com)

This file is part of the Parma Polyhedra Library (PPL).

The PPL is free software; you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published by
the Free Software Foundation; version 3 of the License only.

The PPL is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>.

For the most up-to-date information see the Parma Polyhedra Library
site: https://bugseng.com/ppl . */

import parma_polyhedra_library.*;

public class ppl_java_generated_tests {
    static {
        try {
            System.loadLibrary("ppl_java");
        }
        catch (UnsatisfiedLinkError  e) {
            System.out.println("Unable to load the library");
            System.out.println(e.getMessage());
            System.exit(-1);
        }
    }

    // Success state.
    static boolean globally_ok;

    // Common stuff. We can add other objects if we need them later.
    static Coefficient coeff_0;
    static Coefficient coeff_5;
    static Variable var_C;
    static Variables_Set var_set_A;
    static Linear_Expression le_A;

    static Constraint constraint1;
    static Constraint constraint2;
    static Congruence congruence1;
    static Generator generator1;
    static Grid_Generator grid_generator1;

    static Constraint_System constraints1;
    static Constraint_System constraints2;
    static Congruence_System congruences1;
    static Congruence_System congruences2;
    static Generator_System generators1;
    static Grid_Generator_System grid_generators1;

    static By_Reference<Boolean> bool_by_ref1;
    static By_Reference<Boolean> bool_by_ref2;
    static By_Reference<Integer> int_by_ref1;
    static By_Reference<Integer> zero_by_ref1;

    static Partial_Function partial_function;

    // One-dimensional ascending chains with independently specified limits.
    static Constraint_System constraints_widen_current;
    static Constraint_System constraints_widen_previous;
    static Constraint_System constraints_widen_expected;
    static Constraint_System constraints_widen_limits;
    static Congruence_System congruences_widen_current;
    static Congruence_System congruences_widen_previous;
    static Congruence_System congruences_widen_expected;
    static Congruence_System congruences_widen_limits;

    static Constraint_System interval_constraints(int upper) {
        Variable a = new Variable(0);
        Linear_Expression x = new Linear_Expression_Variable(a);
        Linear_Expression zero
            = new Linear_Expression_Coefficient(new Coefficient(0));
        Constraint_System result = new Constraint_System();
        result.add(new Constraint(x, Relation_Symbol.GREATER_OR_EQUAL, zero));
        if (upper >= 0) {
            Linear_Expression bound
                = new Linear_Expression_Coefficient(new Coefficient(upper));
            result.add(new Constraint(x, Relation_Symbol.LESS_OR_EQUAL, bound));
        }
        return result;
    }

    static Congruence_System scalar_grid(int modulus) {
        Congruence_System result = new Congruence_System();
        result.add(new Congruence(new Linear_Expression_Variable(new Variable(0)),
                   new Linear_Expression_Coefficient(new Coefficient(0)),
                   new Coefficient(modulus)));
        return result;
    }


    // Common initialization.
    public static void initialize() {

        // Initialize output variables.
        PPL_Test.initialize();

        // [0,9] grows to [0,10]; widening removes the unstable upper bound.
        // These bounds are beyond the box widening's default stop points.
        constraints_widen_previous = interval_constraints(9);
        constraints_widen_current = interval_constraints(10);
        constraints_widen_expected = interval_constraints(-1);
        constraints_widen_limits = new Constraint_System();
        // 4Z grows to Z; grid widening drops the unstable periodicity.
        congruences_widen_previous = scalar_grid(4);
        congruences_widen_current = scalar_grid(1);
        congruences_widen_expected = new Congruence_System();
        congruences_widen_limits = new Congruence_System();

        // Coefficient declaration.
        coeff_0 = new Coefficient("0");
        Coefficient coeff_1 = new Coefficient(1);
        Coefficient coeff_2 = new Coefficient(2);
        Coefficient coeff_4 = new Coefficient(4);
        coeff_5 = new Coefficient("5");
        Coefficient coeff_10 = new Coefficient("10");

        // Variable declarations.
        Variable A = new Variable(0);
        Variable C = new Variable(2);
        var_C = C;
        var_set_A = new Variables_Set();
        var_set_A.add(A);

        // Linear_Expression declarations.
        Linear_Expression le_0 = new Linear_Expression_Coefficient(coeff_0);
        Linear_Expression le_5 = new Linear_Expression_Coefficient(coeff_5);
        le_A = new Linear_Expression_Variable(A);
        Linear_Expression le_2A = le_A.times(coeff_2);
        Linear_Expression le_C = new Linear_Expression_Variable(C);
        Linear_Expression le_2A_plus_C = le_2A.sum(le_C);
        Linear_Expression le_40A_plus_10C = le_2A_plus_C.times(coeff_10);

        PPL_Test.print_if_noisy("Printing a linear expression (2A + C): ");
        PPL_Test.println_if_noisy(le_2A_plus_C.toString());

        // Constraint declarations.
        Constraint c_5_geq_0
          = new Constraint(le_5, Relation_Symbol.GREATER_OR_EQUAL, le_0);
        constraint1 = c_5_geq_0;
        Constraint c_C_eq_5
          = new Constraint(le_C, Relation_Symbol.EQUAL, le_5);
        Constraint c_2A_eq_5
          = new Constraint(le_2A, Relation_Symbol.EQUAL, le_5);
        Constraint c_2A_plus_C_eq_2A
          = new Constraint(le_2A_plus_C, Relation_Symbol.EQUAL, le_2A);
        Constraint c_2A_plus_C_geq_5
          = new Constraint(le_2A_plus_C,
                           Relation_Symbol.GREATER_OR_EQUAL,
                           le_5);
        PPL_Test.print_if_noisy("Printing a constraint (2A + C >= 5): ");
        PPL_Test.println_if_noisy(c_2A_plus_C_geq_5.toString());

        Congruence cg_2A_eq_5 = new Congruence(le_2A, le_5, coeff_0);
        Congruence cg_C_eq_5 = new Congruence(le_C, le_5, coeff_0);
        Congruence cg_C_int = new Congruence(le_C, le_0, coeff_1);
        congruence1 = cg_2A_eq_5;
        PPL_Test.print_if_noisy("Printing a congruence (2A == 5): ");
        PPL_Test.println_if_noisy(cg_2A_eq_5.toString());

        // Constraint_System declarations.
        constraints1 = new Constraint_System();
        constraints1.add(c_5_geq_0);
        constraints1.add(c_C_eq_5);
        PPL_Test.print_if_noisy("Printing a constraint system (C == 5):");
        PPL_Test.println_if_noisy(constraints1.toString());

        constraints2 = new Constraint_System();
        constraints2.add(c_2A_plus_C_eq_2A);
        constraints2.add(c_2A_eq_5);

        congruences1 = new Congruence_System();
        congruences1.add(cg_2A_eq_5);
        congruences1.add(cg_C_eq_5);
        PPL_Test.print_if_noisy("Printing a congruence system: ");
        PPL_Test.println_if_noisy(congruences1.toString());

        congruences2 = new Congruence_System();
        congruences2.add(cg_C_int);

        // Generator declarations.
        Generator g1 = Generator.point(le_40A_plus_10C, coeff_1);
        generator1 = g1;
        Generator g2 = Generator.point(le_40A_plus_10C, coeff_2);
        Generator g4 = Generator.point(le_A, coeff_4);
        PPL_Test.print_if_noisy("Printing a generator (p(40A + 10C)):");
        PPL_Test.println_if_noisy(g1.toString());

        // Generator_System declaration.
        generators1 = new Generator_System();
        generators1.add(g1);
        generators1.add(g2);
        generators1.add(g4);
        PPL_Test.print_if_noisy("Printing a generator system: ");
        PPL_Test.println_if_noisy(generators1.toString());

        // Grid_Generator declarations.
        Grid_Generator gg1
          = Grid_Generator.grid_point(le_40A_plus_10C, coeff_1);
        grid_generator1 = gg1;
        Grid_Generator gg2
          = Grid_Generator.grid_point(le_40A_plus_10C, coeff_2);
        Grid_Generator gg4
          = Grid_Generator.grid_point(le_A, coeff_4);

        // Grid_Generator_System declaration.
        grid_generators1 = new Grid_Generator_System();
        grid_generators1.add(gg1);
        grid_generators1.add(gg2);
        grid_generators1.add(gg4);

        bool_by_ref1 = new By_Reference<Boolean>(true);
        bool_by_ref2 = new By_Reference<Boolean>(true);

        int_by_ref1 = new By_Reference<Integer>(1);
        zero_by_ref1 = new By_Reference<Integer>(0);

        partial_function = new Partial_Function();
        partial_function.insert(0, 2);
        partial_function.insert(2, 0);
        partial_function.insert(1, 1);
    }

    // Helper method.
    static void report_success_or_failure(boolean locally_ok) {
        if (locally_ok)
            PPL_Test.println_if_noisy("Success");
        else {
            PPL_Test.println_if_noisy("Failure");
            globally_ok = false;
        }
    }


    static void check(String name, boolean condition) {
        if (!condition) throw new AssertionError("generated Java test: " + name);
    }

    // Fixtures use only the selected class supplied by the generated test.
    // Native methods under test are called directly in each test body.
    static final class Fixture<T> implements AutoCloseable {
        final Class<T> type;
        final java.util.List<T> owned = new java.util.ArrayList<T>();
        Fixture(Class<T> type) { this.type = type; }
        T own(T value) { owned.add(value); return value; }
        T element(int dimension, Degenerate_Element element) throws Exception {
            return own(type.getConstructor(long.class, Degenerate_Element.class)
                       .newInstance((long) dimension, element));
        }
        T make(int dimension, Constraint... constraints) throws Exception {
            T result = element(dimension, Degenerate_Element.UNIVERSE);
            Constraint_System system = new Constraint_System();
            for (Constraint constraint : constraints) system.add(constraint);
            type.getMethod("refine_with_constraints", Constraint_System.class).invoke(result, system);
            return result;
        }
        T grid(int dimension, Congruence... congruences) throws Exception {
            T result = element(dimension, Degenerate_Element.UNIVERSE);
            Congruence_System system = new Congruence_System();
            for (Congruence congruence : congruences) system.add(congruence);
            type.getMethod("refine_with_congruences", Congruence_System.class).invoke(result, system);
            return result;
        }
        T point(int value) throws Exception { return make(1, eq(x(0), n(value))); }
        T set(int... values) throws Exception {
            T result = element(1, Degenerate_Element.EMPTY);
            for (int value : values)
                type.getMethod("upper_bound_assign", type).invoke(result, point(value));
            return result;
        }
        T copy(T value) throws Exception {
            return own(type.getConstructor(type).newInstance(value));
        }
        void same(String name, T expected, T actual) throws Exception {
            check(name, (Boolean) type.getMethod("equals", Object.class).invoke(actual, expected));
            check(name + ": validity", (Boolean) type.getMethod("OK").invoke(actual));
        }
        public void close() throws Exception {
            for (int i = owned.size(); i-- > 0;) type.getMethod("free").invoke(owned.get(i));
        }
    }

    static Linear_Expression x(int id) { return new Linear_Expression_Variable(new Variable(id)); }
    static Linear_Expression n(int value) { return new Linear_Expression_Coefficient(new Coefficient(value)); }
    static Linear_Expression n(java.math.BigInteger value) { return new Linear_Expression_Coefficient(new Coefficient(value)); }
    static Linear_Expression times(int value, Linear_Expression e) { return e.times(new Coefficient(value)); }
    static Constraint eq(Linear_Expression a, Linear_Expression b) { return new Constraint(a, Relation_Symbol.EQUAL, b); }
    static Constraint ge(Linear_Expression a, Linear_Expression b) { return new Constraint(a, Relation_Symbol.GREATER_OR_EQUAL, b); }
    static Constraint le(Linear_Expression a, Linear_Expression b) { return new Constraint(a, Relation_Symbol.LESS_OR_EQUAL, b); }
    static Constraint gt(Linear_Expression a, Linear_Expression b) { return new Constraint(a, Relation_Symbol.GREATER_THAN, b); }
    static Constraint lt(Linear_Expression a, Linear_Expression b) { return new Constraint(a, Relation_Symbol.LESS_THAN, b); }
    static Congruence congruence(Linear_Expression e, int residue, int modulus) {
        return new Congruence(e, n(residue), new Coefficient(modulus));
    }
    static boolean exact_halves(String name) {
        return name.contains("Polyhedron") || name.contains("Grid") || name.contains("Rational_Box")
            || name.contains("Float_Box") || name.contains("Double_Box") || name.contains("_mpq_class");
    }
    static boolean strict_boundaries(String name) {
        return name.contains("NNC_Polyhedron") || name.contains("Rational_Box");
    }
    static void rational(String name, Coefficient numerator, Coefficient denominator, int num, int den) {
        check(name + ": positive denominator", denominator.getBigInteger().signum() > 0);
        check(name, numerator.getBigInteger().multiply(java.math.BigInteger.valueOf(den)).equals(
                    denominator.getBigInteger().multiply(java.math.BigInteger.valueOf(num))));
    }
    static void relation(String name, Poly_Con_Relation actual, int expected) {
        for (int bit = 1; bit <= 8; bit *= 2)
            check(name + ": relation flag " + bit,
                  actual.implies(new Poly_Con_Relation(bit)) == ((expected & bit) != 0));
    }
    static void relation(String name, Poly_Gen_Relation actual, int expected) {
        check(name, actual.implies(Poly_Gen_Relation.subsumes()) == (expected != 0));
    }
    static java.math.BigInteger coefficient(Linear_Expression e, int variable) {
        if (e instanceof Linear_Expression_Variable)
            return java.math.BigInteger.valueOf(((Linear_Expression_Variable)e).argument().id() == variable ? 1 : 0);
        if (e instanceof Linear_Expression_Coefficient) return java.math.BigInteger.ZERO;
        if (e instanceof Linear_Expression_Unary_Minus)
            return coefficient(((Linear_Expression_Unary_Minus)e).argument(), variable).negate();
        if (e instanceof Linear_Expression_Sum) {
            Linear_Expression_Sum sum = (Linear_Expression_Sum)e;
            return coefficient(sum.left_hand_side(), variable).add(coefficient(sum.right_hand_side(), variable));
        }
        if (e instanceof Linear_Expression_Difference) {
            Linear_Expression_Difference difference = (Linear_Expression_Difference)e;
            return coefficient(difference.left_hand_side(), variable).subtract(coefficient(difference.right_hand_side(), variable));
        }
        if (e instanceof Linear_Expression_Times) {
            Linear_Expression_Times product = (Linear_Expression_Times)e;
            return product.coefficient().getBigInteger().multiply(coefficient(product.linear_expression(), variable));
        }
        throw new AssertionError("unrecognized expression node");
    }

    // Compile cases as separate methods to stay within JVM bytecode limits.
    interface CheckedTest { void execute() throws Exception; }
    static void run(CheckedTest test) throws Exception { test.execute(); }

    static void release(Object... values) throws Exception {
        for (Object value : values) value.getClass().getMethod("free").invoke(value);
    }
