(* Common part of the OCaml generated tests.  -*- Tuareg -*-
   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 . *)

open Ppl_ocaml
open Printf

let print_string_if_very_noisy = function str ->
  let less_noisy = "LESS_NOISY"
  in let very_noisy = try Sys.getenv "PPL_VERY_NOISY_TESTS"
    with Not_found -> less_noisy
  in
    if (very_noisy != less_noisy)
    then print_string str;
;;

let print_string_if_noisy = function str ->
  let quiet = "QUIET"
  in let noisy = try Sys.getenv "PPL_NOISY_TESTS"
    with Not_found -> quiet
  in
    if (noisy != quiet)
    then print_string str
    else print_string_if_very_noisy str;
;;

(* Keep large generated initializers out of the native compiler main body. *)
let[@inline never] run_case body = body () ;;

(* Check outcomes are independent of diagnostic verbosity. *)
let check name condition =
  if not condition then failwith ("generated OCaml test: " ^ name)
;;

(* Values returned by the foreign interface must be canonical OCaml Booleans. *)
let check_bool name (expected : bool) (actual : bool) =
  let value = Obj.repr actual in
  check (name ^ ": noncanonical Boolean")
    (Obj.is_int value && (value == Obj.repr false || value == Obj.repr true));
  check name (actual = expected)
;;

let check_relation name expected actual =
  check name (List.sort compare actual = List.sort compare expected)
;;

let check_rational name expected numerator denominator =
  check (name ^ ": positive denominator") (Z.sign denominator > 0);
  check name (Q.equal (Q.make numerator denominator) expected)
;;

let rec homogeneous_coefficient variable = function
  | Variable v -> Z.of_int (if v = variable then 1 else 0)
  | Coefficient _ -> Z.of_int 0
  | Unary_Plus e -> homogeneous_coefficient variable e
  | Unary_Minus e -> Z.neg (homogeneous_coefficient variable e)
  | Plus (e,f) -> Z.add (homogeneous_coefficient variable e) (homogeneous_coefficient variable f)
  | Minus (e,f) -> Z.sub (homogeneous_coefficient variable e) (homogeneous_coefficient variable f)
  | Times (n,e) -> Z.mul n (homogeneous_coefficient variable e)
;;

let rec eval_linear_expression coordinates = function
  | Variable v -> List.nth coordinates v
  | Coefficient n -> Q.of_bigint n
  | Unary_Plus e -> eval_linear_expression coordinates e
  | Unary_Minus e -> Q.neg (eval_linear_expression coordinates e)
  | Plus (e,f) -> Q.add (eval_linear_expression coordinates e) (eval_linear_expression coordinates f)
  | Minus (e,f) -> Q.sub (eval_linear_expression coordinates e) (eval_linear_expression coordinates f)
  | Times (n,e) -> Q.mul (Q.of_bigint n) (eval_linear_expression coordinates e)
;;

(* Fixture capabilities follow the declared domain families. *)
let has_prefix text prefix =
  String.length text >= String.length prefix
  && String.sub text 0 (String.length prefix) = prefix
;;

let has_fragment text fragment =
  let rec search i =
    i + String.length fragment <= String.length text
    && (String.sub text i (String.length fragment) = fragment || search (i+1))
  in search 0
;;

let test_exact_halves name =
  List.exists (has_fragment name)
    ["Polyhedron"; "Grid"; "Rational_Box"; "Float_Box"; "Double_Box"; "_mpq_class"]
;;

let test_strict_boundaries name =
  List.exists (has_fragment name) ["NNC_Polyhedron"; "Rational_Box"]
;;

let print_int_if_very_noisy = function num ->
  let less_noisy = "LESS_NOISY"
  in let very_noisy = try Sys.getenv "PPL_VERY_NOISY_TESTS"
    with Not_found -> less_noisy
  in
    if (very_noisy != less_noisy)
    then print_int num;
;;

let print_int_if_noisy = function num ->
  let quiet = "QUIET"
  in let noisy = try Sys.getenv "PPL_NOISY_TESTS"
    with Not_found -> quiet
  in
    if (noisy != quiet)
    then print_int num
    else print_int_if_very_noisy num;
;;

let print_bool_if_very_noisy = function b ->
  let less_noisy = "LESS_NOISY"
  in let very_noisy = try Sys.getenv "PPL_VERY_NOISY_TESTS"
    with Not_found -> less_noisy
  in
    if (very_noisy != less_noisy)
    then printf "%b" b;
;;

let print_bool_if_noisy = function b ->
  let quiet = "QUIET"
  in let noisy = try Sys.getenv "PPL_NOISY_TESTS"
    with Not_found -> quiet
  in
    if (noisy != quiet)
    then printf "%b" b
    else print_bool_if_very_noisy b;
;;

let rec print_linear_expression = function
    Variable v ->
      print_string_if_noisy "V(";
      print_int_if_noisy v;
      print_string_if_noisy ")";
  | Coefficient c ->
      print_int_if_noisy(Z.to_int c)
  | Unary_Minus e ->
      print_string_if_noisy "-(";
      print_linear_expression e;
      print_string_if_noisy ")";
  | Unary_Plus e ->
      print_linear_expression e
  | Plus (e1, e2) ->
      print_string_if_noisy "(";
      print_linear_expression e1;
      print_string_if_noisy " + ";
      print_linear_expression e2;
      print_string_if_noisy ")";
  | Minus (e1, e2) ->
      print_string_if_noisy "(";
      print_linear_expression e1;
      print_string_if_noisy " - ";
      print_linear_expression e2;
      print_string_if_noisy ")";
  | Times (c, e) ->
      print_int_if_noisy(Z.to_int c);
      print_string_if_noisy "*(";
      print_linear_expression e;
      print_string_if_noisy ")";
;;

let print_constraint = function
    Less_Than (le1, le2) ->
      print_linear_expression le1;
      print_string_if_noisy " < ";
      print_linear_expression le2;
      print_string_if_noisy ", ";
  | Less_Or_Equal (le1, le2) ->
      print_linear_expression le1;
      print_string_if_noisy " <= ";
      print_linear_expression le2;
      print_string_if_noisy ", ";
  | Equal (le1, le2) ->
      print_linear_expression le1;
      print_string_if_noisy " == ";
      print_linear_expression le2;
      print_string_if_noisy ", ";
  | Greater_Than (le1, le2) ->
      print_linear_expression le1;
      print_string_if_noisy " > ";
      print_linear_expression le2;
      print_string_if_noisy ", ";
  | Greater_Or_Equal (le1, le2) ->
      print_linear_expression le1;
      print_string_if_noisy " >= ";
      print_linear_expression le2;
      print_string_if_noisy ", ";
;;

let print_generator = function
    Ray (le1) ->
      print_string_if_noisy "Ray: ";
      print_linear_expression le1;
      print_string_if_noisy ", ";
  |  Line (le1) ->
       print_string_if_noisy "Line: ";
       print_linear_expression le1;
       print_string_if_noisy ", ";
  | Point (le1, c) ->
      print_string_if_noisy "Point: ";
      print_linear_expression le1;
      print_string_if_noisy " den: ";
      print_int_if_noisy(Z.to_int c);
      print_string_if_noisy ", ";
  | Closure_Point (le1, c) ->
      print_string_if_noisy "Closure_Point: ";
      print_linear_expression le1;
      print_string_if_noisy " den: ";
      print_int_if_noisy(Z.to_int c);
      print_string_if_noisy ", ";;

let print_congruence = function x,y,z ->
  print_linear_expression x;
  print_string_if_noisy " %= ";
  print_linear_expression y;
  print_string_if_noisy " mod ";
  print_int_if_noisy(Z.to_int z);
  print_string_if_noisy ", ";;


let print_grid_generator = function
  |  Grid_Line (le1) ->
      print_string_if_noisy "Line: ";
      print_linear_expression le1;
      print_string_if_noisy ", ";
  | Grid_Point (le1, c) ->
      print_string_if_noisy "Point: ";
      print_linear_expression le1;
      print_string_if_noisy " den: ";
      print_int_if_noisy(Z.to_int c);
      print_string_if_noisy ", ";
  | Grid_Parameter (le1, c) ->
      print_string_if_noisy "Parameter: ";
      print_linear_expression le1;
      print_string_if_noisy " den: ";
      print_int_if_noisy(Z.to_int c);
      print_string_if_noisy ", ";;

(* Build linear expressions the hard way. *)

print_string_if_noisy "Build linear expressions manually:\n" ;;

let rec v0 = Variable 0
and v1 = Variable 1
and v2 = Variable 2
and n = Coefficient (Z.of_int 3)
and e1 = Plus (v2, v2)
and e2 = Times ((Z.of_int 7), v0)
and e3 = Plus (n, v2)
;;

print_linear_expression v0; print_string_if_noisy "\n" ;;
print_linear_expression v1; print_string_if_noisy "\n" ;;
print_linear_expression v2; print_string_if_noisy "\n" ;;
print_linear_expression n; print_string_if_noisy "\n" ;;
print_linear_expression e1; print_string_if_noisy "\n" ;;
print_linear_expression e2; print_string_if_noisy "\n" ;;

(* See whether operators can make life better. *)

print_string_if_noisy "Build linear expressions with operators:\n" ;;

let linear_expression_of_int n = Coefficient (Z.of_int n) ;;
let linear_expression_plus e1 e2 = Plus (e1, e2) ;;
let linear_expression_minus e1 e2 = Minus (e1, e2) ;;
let linear_expression_times v2 e = Times (v2, e) ;;
let linear_constraint_eq e1 e2 = Equal (e1, e2) ;;
let linear_constraint_lt e1 e2 = Less_Than (e1, e2) ;;
let linear_constraint_gt e1 e2 = Greater_Than (e1, e2) ;;
let linear_constraint_le e1 e2 = Less_Or_Equal (e1, e2) ;;
let linear_constraint_ge e1 e2 = Greater_Or_Equal (e1, e2) ;;

let ( +/ ) = linear_expression_plus
let ( -/ ) = linear_expression_minus
let ( */ ) = linear_expression_times
let ( =/ ) = linear_constraint_eq
let ( </ ) = linear_constraint_lt
let ( >/ ) = linear_constraint_gt
let ( <=/ ) = linear_constraint_le
let ( >=/ ) = linear_constraint_ge

let e3 =
  (Z.of_int 3) */ v0
  +/
  (Z.of_int 4) */ v1
  -/
  (linear_expression_of_int 7)
;;

print_linear_expression e3; print_string_if_noisy "\n" ;;

(* Build some PPL::C_Polyhedron. *)

let constraint1 = (e2 >=/ e2);;
let constraints1 = [e1 =/ n; e1 <=/ e1; e1 >=/ e1 -/ n] ;;
let generator1 = Point (e3, (Z.of_int 1));;
let generators1 = [Point (e2, (Z.of_int 1)); Point (e1, (Z.of_int 2))] ;;
let congruence1 = (e2, e2 , (Z.of_int 1));;
let congruences1 = [e1, (linear_expression_of_int 5), (Z.of_int 0)];;
let grid_generator1 = Grid_Point (e3, (Z.of_int 1));;
let grid_generators1 = [Grid_Point (e3, (Z.of_int 1))];;

let mip1 =  ppl_new_MIP_Problem 10 constraints1 e3 Maximization;;
let objective_func = ppl_MIP_Problem_objective_function mip1;;
print_string_if_noisy "\n";;
print_linear_expression objective_func;;
let i = ppl_MIP_Problem_space_dimension mip1;;
print_string_if_noisy "\n";;
print_int_if_noisy i;;
let i = ppl_MIP_Problem_constraints mip1;;
print_string_if_noisy "\n";;
List.iter print_constraint i;;

let constraint01 = (v0 >=/ (linear_expression_of_int 1));;
let constraints01 = [(v0 >=/ (linear_expression_of_int 1));
                     (v1 >=/ (linear_expression_of_int 1));
                     (v2 >=/ (linear_expression_of_int 1))];;
let constraints02 = [(v0 <=/ (linear_expression_of_int 1));
                     (v1 >=/ (linear_expression_of_int 1))];;
let constraints03 = [(v0 >=/ (linear_expression_of_int 2));
                     (v1 >=/ (linear_expression_of_int 1));
                     (v2 >=/ (linear_expression_of_int 1))];;
let constraints04 = [(v0 >=/ (linear_expression_of_int 2))];;
let congruence01 = (v0, (linear_expression_of_int 0), (Z.of_int 2));;
let congruences01 = [(v0, (linear_expression_of_int 0), (Z.of_int 2));
                    (v1, (linear_expression_of_int 0), (Z.of_int 1));
                    (v2, (linear_expression_of_int 0), (Z.of_int 1))];;
let congruences02 = [(v0, (linear_expression_of_int 1), (Z.of_int 3));
                    (v1, (linear_expression_of_int 0), (Z.of_int 1));
                    (v2, (linear_expression_of_int 0), (Z.of_int 1))];;
let congruences03 = [(v0, (linear_expression_of_int 0), (Z.of_int 4));
                    (v1, (linear_expression_of_int 0), (Z.of_int 1));
                    (v2, (linear_expression_of_int 0), (Z.of_int 1))];;
let congruences04 = [(v0, (linear_expression_of_int 0), (Z.of_int 4))];;

(* Bounds beyond the default Box stop points make widening lose the upper
   bound in every supported widening/extrapolation used here. Limits are
   empty so these fixtures isolate the widening and token effects. *)
let constraints_widen_current =
  [v0 >=/ linear_expression_of_int 0; v0 <=/ linear_expression_of_int 10];;
let constraints_widen_previous =
  [v0 >=/ linear_expression_of_int 0; v0 <=/ linear_expression_of_int 9];;
let constraints_widen_expected = [v0 >=/ linear_expression_of_int 0];;
let constraints_widen_limits = [];;

(* Widening Z against 4Z loses the non-stationary period. *)
let congruences_widen_current =
  [(v0, linear_expression_of_int 0, Z.of_int 1)];;
let congruences_widen_previous =
  [(v0, linear_expression_of_int 0, Z.of_int 4)];;
let congruences_widen_expected = [];;
let congruences_widen_limits = [];;

(* Powerset views retain their root, and reject stale/native-unsafe access. *)
let view_gc () = Gc.full_major (); Gc.full_major (); Gc.compact ();;
let invalid_view text action =
  try action (); failwith ("accepted " ^ text)
  with Invalid_argument message ->
    let n = String.length text in
    let rec contains i = i + n <= String.length message &&
      (String.sub message i n = text || contains (i+1)) in
    check ("wrong view error: " ^ message) (contains 0);;

let powerset_iterator_lifetimes make first last copy next prev equal drop range
                                refine query swap size dimension ok dump =
  let retention mode =
    let owner = Weak.create 1 and parent = Weak.create 1 in
    let make_view () =
      let p = make () in Weak.set owner 0 (Some p);
      let i = first p in Weak.set parent 0 (Some i);
      if mode = 0 then i else if mode = 1 then last p else copy i in
    let view = make_view () in
    view_gc ();
    check "cursor must retain powerset" (Weak.check owner 0);
    if mode = 2 then check "copy must not retain parent cursor" (not (Weak.check parent 0));
    check "retained cursor usable" (equal view (copy view));
    ignore (Sys.opaque_identity view) in
  List.iter retention [0;1;2];
  let weak = Weak.create 1 in
  let exercise () =
    let p = make () in Weak.set weak 0 (Some p);
    let i = first p in view_gc ();
    check "owner retained" (Weak.check weak 0);
    check "cursor valid" (equal i (copy i)) in
  exercise (); view_gc ();
  check "owner leaked after final view" (not (Weak.check weak 0));
  let p = make () and q = make () in
  let i = first p and e = last p and foreign = first q in
  invalid_view "boundary" (fun () -> prev i);
  invalid_view "boundary" (fun () -> next e);
  invalid_view "different powersets" (fun () -> ignore (equal i foreign));
  invalid_view "another powerset" (fun () -> drop p foreign);
  invalid_view "range" (fun () -> range p e i);
  invalid_view "end iterator" (fun () -> drop p e);
  let duplicate = copy i in
  drop p i;
  check "drop cursor must advance" (equal i (last p));
  invalid_view "no longer valid" (fun () -> next duplicate);
  invalid_view "no longer valid" (fun () -> next e);
  let p = make () and q = make () in
  let i = first p and j = first q in
  swap p q;
  invalid_view "no longer valid" (fun () -> next i);
  invalid_view "no longer valid" (fun () -> next j);
  let i = first p in ignore (query p);
  invalid_view "no longer valid" (fun () -> next i);
  let i = first p in
  ignore (size p); ignore (dimension p); ignore (ok p); ignore (dump p);
  next i;
  let i = first p in refine p;
  invalid_view "no longer valid" (fun () -> next i);
  (* Stale iterator finalization must never touch the native list. *)
  view_gc ();;

let powerset_disjunct_lifetimes make first last get copy dimension refine add
                                 root_refine =
  let owner = Weak.create 1 and parent = Weak.create 1 in
  let detached () =
    let p = make () in Weak.set owner 0 (Some p);
    let i = first p in Weak.set parent 0 (Some i); get i in
  let view = detached () in view_gc ();
  check "disjunct must retain root" (Weak.check owner 0);
  check "disjunct need not retain cursor" (not (Weak.check parent 0));
  check "retained disjunct usable" (dimension view = 1);
  invalid_view "read-only" (fun () -> refine view);
  let owned = copy view in refine owned;
  let p = make () in
  let i = first p in let borrowed = get i in
  invalid_view "end iterator" (fun () -> ignore (get (last p)));
  add p borrowed;
  invalid_view "no longer valid" (fun () -> ignore (dimension borrowed));
  check "owned copy independent" (dimension owned = 1);
  let fresh = get (first p) in root_refine p;
  invalid_view "no longer valid" (fun () -> ignore (dimension fresh));
  let weak = Weak.create 1 in
  let release () =
    let p = make () in Weak.set weak 0 (Some p);
    let v = get (first p) in view_gc ();
    check "view retains root" (Weak.check weak 0);
    check "view valid" (dimension v = 1) in
  release (); view_gc ();
  check "disjunct owner leaked" (not (Weak.check weak 0));;
