]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/lambda4.ml
Failure in case of empty problem, to be fixed
[fireball-separation.git] / ocaml / lambda4.ml
1 open Util
2 open Util.Vars
3 open Pure
4 open Num
5
6 let bomb = ref(`Var(-1,-666));;
7
8 (*
9  The number of arguments which can applied to numbers
10  safely, depending on the encoding of numbers.
11  For Scott's encoding, two.
12 *)
13 let num_more_args = 2;;
14 let _very_verbose = false;;
15
16 let verbose s =
17  if _very_verbose then prerr_endline s
18 ;;
19
20 let convergent_dummy = `N ~-1;
21
22 type problem =
23  { freshno: int
24  ; div: i_var option (* None = bomb *)
25  ; conv: i_n_var list (* the inerts that must converge *)
26  ; ps: i_n_var list (* the n-th inert must become n *)
27  ; sigma: (int * nf) list (* the computed substitution *)
28  ; deltas: (int * nf) list ref list (* collection of all branches *)
29  ; initialSpecialK: int
30  ; label : string
31  ; var_names : string list (* names of the original free variables *)
32 };;
33
34 let all_terms p =
35  (match p.div with None -> [] | Some t -> [(t :> i_n_var)])
36  @ p.conv
37  @ p.ps
38 ;;
39
40 let sum_arities p =
41  let rec aux = function
42  | `N _ -> 0
43  | `Var(_,ar) -> if ar = min_int then 0 else max 0 ar (*assert (ar >= 0); ar*)
44  | `Lam(_,t) -> aux t
45  | `I(v,args) -> aux (`Var v) + aux_many (Listx.to_list args)
46  | `Match(u,(_,ar),_,_,args) -> aux (u :> nf) + (if ar = min_int then 0 else ar - 1) + aux_many args
47  and aux_many tms = List.fold_right ((+) ++ aux) tms 0 in
48  aux_many (all_terms p :> nf list)
49  ;;
50
51 let count_fakevars p =
52  let rec aux = function
53  | `N _ -> 0
54  | `Var(_,ar) -> if ar = min_int then 1 else 0
55  | `Lam(_,t) -> aux t
56  | `I(v,args) -> aux (`Var v) + aux_many (Listx.to_list args)
57  | `Match(u,v,_,_,args) -> aux (u :> nf) + aux (`Var v) + aux_many args
58  and aux_many tms = List.fold_right ((+) ++ aux) tms 0 in
59  aux_many (all_terms p :> nf list)
60 ;;
61
62 (* let problem_measure p = count_fakevars p, sum_arities p;;
63 let string_of_measure (a,b) = "(fakevars="^string_of_int a^",sum_arities="^string_of_int b^")" *)
64
65 let problem_measure p = sum_arities p;;
66 let string_of_measure = string_of_int;;
67
68 let string_of_problem label ({freshno; div; conv; ps; deltas} as p) =
69  Console.print_hline ();
70  prerr_string ("\n(* DISPLAY PROBLEM (" ^ label ^ ") - ");
71  let nl = "\n" in
72  let deltas = String.concat (nl^"   ") (List.map (fun r -> String.concat " <> " (List.map (fun (i,_) -> string_of_int i) !r)) deltas) in
73  let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
74  "measure="^string_of_measure(problem_measure p) (* ^ " freshno = " ^ string_of_int freshno*)
75  ^ nl ^ "   Discriminating sets (deltas):"
76  ^ nl ^ "   " ^ deltas ^ (if deltas = " " then "" else nl) ^ "*)"
77  ^"(* DIVERGENT  *)" ^ nl
78  ^"     "^ (match div with None -> "None" | Some div -> "(Some\""^ print ~l (div :> nf) ^"\")") ^ nl
79  ^"  (* CONVERGENT *) [" ^ nl ^ "  "
80  ^ String.concat "\n  " (List.map (fun t -> "(* _ *) " ^ (if t = convergent_dummy then "" else "\""^ print ~l (t :> nf) ^"\";")) conv) ^
81  (if conv = [] then "" else nl)
82  ^ "] (* NUMERIC    *) [" ^ nl ^ " "
83  ^ String.concat "\n " (List.mapi (fun i t -> " (* "^ string_of_int i ^" *) \"" ^ print ~l (t :> nf) ^ "\";") ps)
84  ^ nl ^ "] [\"*\"];;" ^ nl
85 ;;
86
87
88 let failwithProblem p reason =
89  print_endline (string_of_problem "FAIL" p);
90  failwith reason
91 ;;
92
93 let make_fresh_var p arity =
94  let freshno = p.freshno + 1 in
95  {p with freshno}, `Var(freshno,arity)
96 ;;
97
98 let make_fresh_vars p arities =
99  List.fold_right
100   (fun arity (p, vars) -> let p, var = make_fresh_var p arity in p, var::vars)
101   arities
102   (p, [])
103 ;;
104
105 let simple_expand_match ps =
106  let rec aux level = function
107   | #i_num_var as t -> (aux_i_num_var level t :> nf)
108   | `Lam(b,t) -> `Lam(b,aux (level+1) t)
109  and aux_i_num_var level = function
110   | `Match(u,v,bs_lift,bs,args) as torig ->
111     let (u : i_num_var) = aux_i_num_var level u in
112     bs := List.map (fun (n, x) -> n, aux 0 x) !bs;
113     (try
114        (match u with
115          | #i_n_var as u ->
116             let i = index_of ~eq:eta_eq (lift (-level) u) (ps :> nf list) in (* can raise Not_found *)
117             let t = cast_to_i_num_var (mk_match (`N i) v bs_lift bs (args :> nf list)) in
118             if t <> torig then
119              aux_i_num_var level t
120             else raise Not_found
121          | _ -> raise Not_found)
122       with Not_found ->
123        cast_to_i_num_var (mk_appl (`Match(u,v,bs_lift,bs,[])) (List.map (aux level) args)))
124   | `I(v,args) -> cast_to_i_num_var (mk_appl (`Var v) (List.map (aux level) (Listx.to_list args)))
125   | `N _ | `Var _ as t -> t
126  in aux_i_num_var 0
127 ;;
128
129 let fixpoint f =
130  let rec aux x = let x' = f x in if x <> x' then aux x' else x in aux
131 ;;
132
133 let rec super_simplify_ps ps =
134  fixpoint (List.map (fun x -> cast_to_i_n_var (simple_expand_match ps (x :> i_num_var))))
135 ;;
136
137 let rec super_simplify_ps_with_match ps =
138  fixpoint (List.map (cast_to_i_num_var ++ (simple_expand_match ps)))
139 ;;
140
141 let super_simplify ({div; ps; conv} as p) =
142   let ps = super_simplify_ps p.ps p.ps in
143   let conv = super_simplify_ps ps p.conv in
144   let div = option_map (fun div ->
145    let divs = super_simplify_ps p.ps ([div] :> i_n_var list) in
146     List.hd divs) div in
147   {p with div=option_map cast_to_i_var div; ps; conv}
148
149 exception ExpandedToLambda;;
150
151 let subst_in_problem x inst ({freshno; div; conv; ps; sigma} as p) =
152  let len_ps = List.length ps in
153 (*(let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
154 prerr_endline ("# INST0: " ^ string_of_var x ^ " := " ^ print ~l inst));*)
155  let rec aux ((freshno,acc_ps,acc_new_ps) as acc) =
156   function
157   | [] -> acc
158   | t::todo_ps ->
159 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
160      let t = subst false false x inst (t :> nf) in
161 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
162      let freshno,new_t,acc_new_ps =
163       expand_match (freshno,acc_ps@`Var(max_int/3,-666)::todo_ps,acc_new_ps) t
164      in
165       aux (freshno,acc_ps@[new_t],acc_new_ps) todo_ps
166
167   (* cut&paste from aux above *)
168   and aux' ps ((freshno,acc_conv,acc_new_ps) as acc) =
169    function
170    | [] -> acc
171    | t::todo_conv ->
172 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
173       (* try *)
174        let t = subst false false x inst (t :> nf) in
175 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
176        let freshno,new_t,acc_new_ps =
177         expand_match (freshno,ps,acc_new_ps) t
178        in
179         aux' ps (freshno,acc_conv@[new_t],acc_new_ps) todo_conv
180       (* with ExpandedToLambda -> aux' ps (freshno,acc_conv@[`N(-1)],acc_new_ps) todo_conv *)
181
182   (* cut&paste from aux' above *)
183   and aux'' ps (freshno,acc_new_ps) =
184    function
185    | None -> freshno, None, acc_new_ps
186    | Some t ->
187       let t = subst false false x inst (t :> nf) in
188       let freshno,new_t,acc_new_ps =
189        expand_match (freshno,ps,acc_new_ps) t
190       in
191        freshno,Some new_t,acc_new_ps
192
193   and expand_match ((freshno,acc_ps,acc_new_ps) as acc) t =
194    match t with
195    | `Match(u',orig,bs_lift,bs,args) ->
196         let freshno,u,acc_new_ps = expand_match acc (u' :> nf) in
197         let acc_new_ps,i =
198          match u with
199          | `N i -> acc_new_ps,i
200          | _ ->
201             let ps = List.map (fun t -> cast_to_i_num_var (subst false false x inst (t:> nf))) (acc_ps@acc_new_ps) in
202             let super_simplified_ps = super_simplify_ps_with_match ps ps in
203 (*prerr_endline ("CERCO u:" ^ print (fst u :> nf));
204 List.iter (fun x -> prerr_endline ("IN: " ^ print (fst x :> nf))) ps;
205 List.iter (fun x -> prerr_endline ("IN2: " ^ print (fst x :> nf))) super_simplified_ps;*)
206             match index_of_opt ~eq:eta_eq super_simplified_ps u with
207                Some i -> acc_new_ps, i
208              | None -> acc_new_ps@[u], len_ps + List.length acc_new_ps
209         in
210          let freshno=
211           if List.exists (fun (j,_) -> i=j) !bs then
212            freshno
213           else
214            let freshno,v = freshno+1, `Var (freshno+1, -666) in (* make_fresh_var freshno in *)
215            bs := !bs @ [i, v] ;
216            freshno in
217 (*prerr_endlie ("t DA RIDURRE:" ^ print (`Match(`N i,arity,bs_lift,bs,args) :> nf) ^ " more_args=" ^ string_of_int more_args);*)
218          let t = mk_match (`N i) orig bs_lift bs args in
219 (*prerr_endline ("NUOVO t:" ^ print (fst t :> nf) ^ " more_args=" ^ string_of_int (snd t));*)
220           expand_match (freshno,acc_ps,acc_new_ps) t
221    | `Lam _ -> raise ExpandedToLambda
222    | #i_n_var as x ->
223       let x = simple_expand_match (acc_ps@acc_new_ps) x in
224       freshno,cast_to_i_num_var x,acc_new_ps in
225
226  let freshno,old_ps,new_ps = aux (freshno,[],[]) (ps :> i_num_var list) in
227  let freshno,conv,new_ps = aux' old_ps (freshno,[],new_ps) (conv :> i_num_var list) in
228  let freshno,div,new_ps = aux'' old_ps (freshno,new_ps) (div :> i_num_var option) in
229  let div = option_map cast_to_i_var div in
230  let ps = List.map cast_to_i_n_var (old_ps @ new_ps) in
231  let conv = List.map cast_to_i_n_var conv in
232 (let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
233 prerr_endline ("# INST: " ^ string_of_var x ^ " := " ^ print ~l inst));
234  let p = {p with freshno; div; conv; ps} in
235  ( (* check if double substituting a variable *)
236   if List.exists (fun (x',_) -> x = x') sigma
237    then failwithProblem p ("Variable "^ string_of_var x ^"replaced twice")
238  );
239  let p = {p with sigma = sigma@[x,inst]} in
240  let p = super_simplify p in
241  prerr_endline (string_of_problem "instantiate" p);
242  p
243 ;;
244
245 exception Dangerous
246
247 let arity_of arities k =
248  let _,pos,y = List.find (fun (v,_,_) -> v=k) arities in
249  let arity = match y with `Var _ -> 0 | `I(_,args) -> Listx.length args | `N _ -> assert false in
250  arity + if pos = -1 then - 1 else 0
251 ;;
252
253 let rec dangerous arities showstoppers =
254  function
255     `N _
256   | `Var _
257   | `Lam _ -> ()
258   | `Match(t,_,liftno,bs,args) ->
259       (* CSC: XXX partial dependency on the encoding *)
260       (match t with
261           `N _ -> List.iter (dangerous arities showstoppers) args
262         | `Match _ as t -> dangerous arities showstoppers t ; List.iter (dangerous arities showstoppers) args
263         | `Var(x,_) -> dangerous_inert arities showstoppers x args num_more_args
264         | `I((x,_),args') -> dangerous_inert arities showstoppers x (Listx.to_list args' @ args) num_more_args
265       )
266   | `I((k,_),args) -> dangerous_inert arities showstoppers k (Listx.to_list args) 0
267
268 and dangerous_inert arities showstoppers k args more_args =
269  List.iter (dangerous arities showstoppers) args ;
270  if List.mem k showstoppers then raise Dangerous else
271  try
272   let arity = arity_of arities k in
273   if List.length args + more_args > arity then raise Dangerous else ()
274  with
275   Not_found -> ()
276
277 (* cut & paste from above *)
278 let rec dangerous_conv arities showstoppers =
279  function
280     `N _
281   | `Var _
282   | `Lam _ -> []
283   | `Match(t,_,liftno,bs,args) ->
284       (* CSC: XXX partial dependency on the encoding *)
285       (match t with
286           `N _ -> concat_map (dangerous_conv arities showstoppers) args
287         | `Match _ as t -> dangerous_conv arities showstoppers t @ concat_map (dangerous_conv arities showstoppers) args
288         | `Var(x,_) -> dangerous_inert_conv arities showstoppers x [] args 2
289         | `I((x,_),args') -> dangerous_inert_conv arities showstoppers x (Listx.to_list args') args 2
290       )
291   | `I((k,_),args) -> dangerous_inert_conv arities showstoppers k (Listx.to_list args) [] 0
292
293 and dangerous_inert_conv arities showstoppers k args match_args more_args =
294  let all_args = args @ match_args in
295  let dangerous_args = concat_map (dangerous_conv arities showstoppers) all_args in
296  if dangerous_args = [] then (
297  if List.mem k showstoppers then k :: concat_map free_vars all_args else
298  try
299   let arity = arity_of arities k in
300 prerr_endline ("dangerous_inert_conv: ar=" ^ string_of_int arity ^ " k="^string_of_var k ^ " listlenargs=" ^ (string_of_int (List.length args)) ^ " more_args=" ^ string_of_int more_args);
301   if more_args > 0 (* match argument*) && List.length args = arity then []
302   else if List.length all_args + more_args > arity then k :: concat_map free_vars all_args else []
303  with
304   Not_found -> []
305  ) else k :: concat_map free_vars all_args
306
307 (* inefficient algorithm *)
308 let rec edible arities div ps conv showstoppers =
309  let rec aux showstoppers =
310   function
311      [] -> showstoppers
312    | x::xs when List.exists (fun y -> hd_of x = Some y) showstoppers ->
313       (* se la testa di x e' uno show-stopper *)
314       let new_showstoppers = sort_uniq (showstoppers @ free_vars (x :> nf)) in
315       (* aggiungi tutte le variabili libere di x *)
316       if List.length showstoppers <> List.length new_showstoppers then
317        aux new_showstoppers ps
318       else
319        aux showstoppers xs
320    | x::xs ->
321       match hd_of x with
322          None -> aux showstoppers xs
323        | Some h ->
324           try
325            dangerous arities showstoppers (x : i_n_var :> nf) ;
326            aux showstoppers xs
327           with
328            Dangerous ->
329             aux (sort_uniq (h::showstoppers)) ps
330   in
331     let showstoppers = sort_uniq (aux showstoppers ps) in
332     let dangerous_conv =
333      List.map (dangerous_conv arities showstoppers) (conv :> nf list) in
334
335 prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
336 List.iter (fun l -> prerr_endline (String.concat " " (List.map string_of_var l))) dangerous_conv;
337
338     let showstoppers' = showstoppers @ List.concat dangerous_conv in
339     let showstoppers' = sort_uniq (match div with
340      | None -> showstoppers'
341      | Some div ->
342        if List.exists ((=) (hd_of_i_var div)) showstoppers'
343        then showstoppers' @ free_vars (div :> nf) else showstoppers') in
344     if showstoppers <> showstoppers' then edible arities div ps conv showstoppers' else showstoppers', dangerous_conv
345 ;;
346
347 let precompute_edible_data {ps; div} xs =
348  (match div with None -> [] | Some div -> [hd_of_i_var div, -1, (div :> i_n_var)]) @
349   List.map (fun hd ->
350    let i, tm = Util.findi (fun y -> hd_of y = Some hd) ps in
351     hd, i, tm
352    ) xs
353 ;;
354
355 let critical_showstoppers p =
356   let p = super_simplify p in
357   let hd_of_div = match p.div with None -> [] | Some t -> [hd_of_i_var t] in
358   let showstoppers_step =
359   concat_map (fun bs ->
360     let heads = List.map (fun (i,_) -> List.nth p.ps i) !bs in
361     let heads = List.sort compare (hd_of_div @ filter_map hd_of heads) in
362     snd (split_duplicates heads)
363     ) p.deltas @
364      if List.exists (fun t -> [hd_of t] = List.map (fun x -> Some x) hd_of_div) p.conv
365      then hd_of_div else [] in
366   let showstoppers_step = sort_uniq showstoppers_step in
367   let showstoppers_eat =
368    let heads_and_arities =
369     List.sort (fun (k,_) (h,_) -> compare k h)
370      (filter_map (function `Var(k,_) -> Some (k,0) | `I((k,_),args) -> Some (k,Listx.length args) | _ -> None ) p.ps) in
371    let rec multiple_arities =
372     function
373        []
374      | [_] -> []
375      | (x,i)::(y,j)::tl when x = y && i <> j ->
376          x::multiple_arities tl
377      | _::tl -> multiple_arities tl in
378    multiple_arities heads_and_arities in
379
380   let showstoppers_eat = sort_uniq showstoppers_eat in
381   let showstoppers_eat = List.filter
382     (fun x -> not (List.mem x showstoppers_step))
383     showstoppers_eat in
384   List.iter (fun v -> prerr_endline ("DANGEROUS STEP: " ^ string_of_var v)) showstoppers_step;
385   List.iter (fun v -> prerr_endline ("DANGEROUS EAT: " ^ string_of_var v)) showstoppers_eat;
386   p, showstoppers_step, showstoppers_eat
387   ;;
388
389 let eat p =
390   let ({ps} as p), showstoppers_step, showstoppers_eat = critical_showstoppers p in
391   let showstoppers = showstoppers_step @ showstoppers_eat in
392   let heads = List.sort compare (filter_map hd_of ps) in
393   let arities = precompute_edible_data p (uniq heads) in
394   let showstoppers, showstoppers_conv =
395    edible arities p.div ps p.conv showstoppers in
396   let l = List.filter (fun (x,_,_) -> not (List.mem x showstoppers)) arities in
397   let p =
398   List.fold_left (fun p (x,pos,(xx : i_n_var)) -> if pos = -1 then p else
399    let n = match xx with `I(_,args) -> Listx.length args | _ -> 0 in
400    let v = `N(pos) in
401    let inst = make_lams v n in
402 (let l = Array.to_list (Array.init (p.freshno + 1) string_of_var) in
403 prerr_endline ("# INST_IN_EAT: " ^ string_of_var x ^ " := " ^ print ~l inst));
404    { p with sigma = p.sigma @ [x,inst] }
405    ) p l in
406   (* to avoid applied numbers in safe positions that
407      trigger assert failures subst_in_problem x inst p*)
408  let ps =
409   List.map (fun t ->
410    try
411     let _,j,_ = List.find (fun (h,_,_) -> hd_of t = Some h) l in
412     `N j
413    with Not_found -> t
414   ) ps in
415  let p = match p.div with
416   | None -> p
417   | Some div ->
418    if List.mem (hd_of_i_var div) showstoppers
419    then p
420    else
421     let n = match div with `I(_,args) -> Listx.length args | `Var _ -> 0 in
422     let p, bomb' = make_fresh_var p (-666) in
423     (if !bomb <> `Var (-1,-666) then
424      failwithProblem p
425       ("Bomb was duplicated! It was " ^ string_of_nf !bomb ^
426        ", tried to change it to " ^ string_of_nf bomb'));
427     bomb := bomb';
428     prerr_endline ("Just created bomb var: " ^ string_of_nf !bomb);
429     let x = hd_of_i_var div in
430     let inst = make_lams !bomb n in
431     prerr_endline ("# INST (div): " ^ string_of_var x ^ " := " ^ string_of_nf inst);
432     let p = {p with div=None} in
433     (* subst_in_problem (hd_of_i_var div) inst p in *)
434      {p with sigma=p.sigma@[x,inst]} in
435      let dangerous_conv = showstoppers_conv in
436 let _ = prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
437 List.iter (fun l -> prerr_endline (String.concat " " (List.map string_of_var l))) dangerous_conv; in
438  let conv =
439    List.map (function s,t ->
440     try
441      if s <> [] then t else (
442      (match t with | `Var _ -> raise Not_found | _ -> ());
443      let _ = List.find (fun h -> hd_of t = Some h) showstoppers in
444       t)
445     with Not_found -> match hd_of t with
446      | None -> assert (t = convergent_dummy); t
447      | Some h ->
448       prerr_endline ("FREEZING " ^ string_of_var h);
449       convergent_dummy
450    ) (List.combine showstoppers_conv p.conv) in
451  List.iter
452   (fun bs ->
453     bs :=
454      List.map
455       (fun (n,t as res) ->
456         match List.nth ps n with
457            `N m -> m,t
458          | _ -> res
459       ) !bs
460   ) p.deltas ;
461  let old_conv = p.conv in
462  let p = { p with ps; conv } in
463  if l <> [] || old_conv <> conv
464   then prerr_endline (string_of_problem "eat" p);
465  if List.for_all (function `N _ -> true | _ -> false) ps && p.div = None then
466   `Finished p
467  else
468   `Continue p
469
470 let instantiate p x n =
471  (if hd_of_i_var (cast_to_i_var !bomb) = x
472    then failwithProblem p ("BOMB (" ^ string_of_nf !bomb ^ ") cannot be instantiated!"));
473  let arity_of_x = max_arity_tms x (all_terms p) in
474  (if arity_of_x = None then failwithProblem p "step on var non occurring in problem");
475  (if Util.option_get(arity_of_x) = min_int then failwithProblem p "step on fake variable");
476  (if Util.option_get(arity_of_x) <= 0 then failwithProblem p "step on var of non-positive arity");
477  let n = (prerr_endline "WARNING: using constant initialSpecialK"); p.initialSpecialK in
478  (* AC: Once upon a time, it was:
479     let arities = Num.compute_arities x (n+1) (all_terms p :> nf list) in *)
480  (* let arities = Array.to_list (Array.make (n+1) 0) in *)
481  let arities = Array.to_list (Array.make (n+1) min_int) in
482  let p,vars = make_fresh_vars p arities in
483  let args = Listx.from_list (vars :> nf list) in
484  let bs = ref [] in
485  (* 666, since it will be replaced anyway during subst: *)
486  let inst = `Lam(false,`Match(`I((0,min_int),Listx.map (lift 1) args),(x,-666),1,bs,[])) in
487  let p = {p with deltas=bs::p.deltas} in
488  subst_in_problem x inst p
489 ;;
490
491 let compute_special_k tms =
492  let rec aux k (t: nf) = Pervasives.max k (match t with
493  | `Lam(b,t) -> aux (k + if b then 1 else 0) t
494  | `I(n, tms) -> Listx.max (Listx.map (aux 0) tms)
495  | `Match(t, _, liftno, bs, args) ->
496      List.fold_left max 0 (List.map (aux 0) ((t :> nf)::args@List.map snd !bs))
497  | `N _
498  | `Var _ -> 0
499  ) in Listx.max (Listx.map (aux 0) tms)
500 ;;
501
502 let auto_instantiate (n,p) =
503  let p, showstoppers_step, showstoppers_eat = critical_showstoppers p in
504  let x =
505   match showstoppers_step, showstoppers_eat with
506   | [], y::_ ->
507      prerr_endline ("INSTANTIATING CRITICAL TO EAT " ^ string_of_var y); y
508   | [], [] ->
509      let heads =
510       (* Choose only variables still alive (with arity > 0) *)
511       List.sort compare (filter_map (
512        fun t -> match t with `Var _ -> None | x -> if arity_of_hd x <= 0 then None else hd_of x
513       ) ((match p.div with Some t -> [(t :> i_n_var)] | _ -> []) @ p.ps)) in
514      (match heads with
515       | [] ->
516          (try
517            fst (List.find (((<) 0) ++ snd) (concat_map free_vars' (p.conv :> nf list)))
518           with
519            Not_found -> assert false)
520       | x::_ ->
521          prerr_endline ("INSTANTIATING TO EAT " ^ string_of_var x);
522          x)
523   | x::_, _ ->
524       prerr_endline ("INSTANTIATING " ^ string_of_var x);
525       x in
526 (* Strategy that  decreases the special_k to 0 first (round robin)
527 1:11m42 2:14m5 3:11m16s 4:14m46s 5:12m7s 6:6m31s *)
528  let x =
529   try
530    match
531     hd_of (List.find (fun t ->
532      compute_special_k (Listx.Nil (t :> nf)) > 0 && arity_of_hd t > 0
533      ) (all_terms p))
534    with
535     | None -> assert false
536     | Some x ->
537        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var x);
538        x
539   with
540    Not_found ->
541     let arity_of_x = max_arity_tms x (all_terms p) in
542     assert (Util.option_get arity_of_x > 0);
543     x in
544 (* Instantiate in decreasing order of compute_special_k
545 1:15m14s 2:13m14s 3:4m55s 4:4m43s 5:4m34s 6:6m28s 7:3m31s
546 let x =
547  try
548   (match hd_of (snd (List.hd (List.sort (fun c1 c2 -> - compare (fst c1) (fst c2)) (filter_map (function `I _ as t -> Some (compute_special_k (Listx.Nil (t :> nf)),t) | _ -> None) (all_terms p))))) with
549       None -> assert false
550     | Some x ->
551        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var x);
552        x)
553  with
554   Not_found -> x
555 in*)
556  let special_k =
557      compute_special_k (Listx.from_list (all_terms p :> nf list) )in
558  if special_k < n then
559   prerr_endline ("@@@@ NEW INSTANTIATE PHASE (" ^ string_of_int special_k ^ ") @@@@");
560  let p = instantiate p x special_k in
561  special_k,p
562
563
564 let rec auto_eat (n,p) =
565  prerr_endline "{{{{{{{{ Computing measure before auto_instantiate }}}}}}";
566  let m = problem_measure p in
567  let (n,p') = auto_instantiate (n,p) in
568  match eat p' with
569  | `Finished p -> p
570  | `Continue p ->
571      prerr_endline "{{{{{{{{ Computing measure inafter auto_instantiate }}}}}}";
572      let delta = problem_measure p - m in
573      (* let delta = m - problem_measure p' in *)
574      if delta >= 0
575       then
576        (failwith
577        ("Measure did not decrease (+=" ^ string_of_int delta ^ ")"))
578       else prerr_endline ("$ Measure decreased of " ^ string_of_int delta);
579      auto_eat (n,p)
580 ;;
581
582 let auto p n =
583  prerr_endline ("@@@@ FIRST INSTANTIATE PHASE (" ^ string_of_int n ^ ") @@@@");
584  match eat p with
585  | `Finished p -> p
586  | `Continue p -> auto_eat (n,p)
587 ;;
588
589 (*
590 0 = snd
591
592       x y = y 0    a y = k  k z = z 0  c y = k   y u = u h1 h2 0          h2 a = h3
593 1 x a c    1 a 0 c  1 k c    1 c 0      1 k        1 k                     1 k
594 2 x a y    2 a 0 y  2 k y    2 y 0      2 y 0      2 h2 0                  2 h3
595 3 x b y    3 b 0 y  3 b 0 y  3 b 0 y    3 b 0 y    3 b 0 (\u. u h1 h2 0)   3 b 0 (\u. u h1 (\w.h3) 0)
596 4 x b c    4 b 0 c  4 b 0 c  4 b 0 c    4 b 0 c    4 b 0 c                 4 b 0 c
597 5 x (b e)  5 b e 0  5 b e 0  5 b e 0    5 b e 0    5 b e 0                 5 b e 0
598 6 y y      6 y y    6 y y    6 y y      6 y y      6 h1 h1 h2 0 h2 0       6 h1 h1 (\w. h3) 0 (\w. h3) 0
599
600                                 l2 _ = l3
601 b u = u l1 l2 0                 e _ _ _ _ = f                         l3 n = n j 0
602 1 k                             1 k                                  1 k
603 2 h3                            2 h3                                 2 h3
604 3 l2 0 (\u. u h1 (\w. h3) 0)    3 l3 (\u. u h1 (\w. h3) 0)           3 j h1 (\w. h3) 0 0
605 4 l2 0 c                        4 l3 c                               4 c j 0
606 5 e l1 l2 0 0                   5 f                                  5 f
607 6 h1 h1 (\w. h3) 0 (\w. h3) 0   6 h1 h1 (\w. h3) 0 (\w. h3) 0        6 h1 h1 (\w. h3) 0 (\w. h3) 0
608 *)
609
610 (*
611                 x n = n 0 ?
612 x a (b (a c))   a 0 = 1 ? (b (a c))   8
613 x a (b d')      a 0 = 1 ? (b d')      7
614 x b (a c)       b 0 = 1 ? (a c)       4
615 x b (a c')      b 0 = 1 ? (a c')      5
616
617 c = 2
618 c' = 3
619 a 2 = 4  (* a c *)
620 a 3 = 5  (* a c' *)
621 d' = 6
622 b 6 = 7  (* b d' *)
623 b 4 = 8  (* b (a c) *)
624 b 0 = 1
625 a 0 = 1
626 *)
627
628 (************** Tests ************************)
629
630 let optimize_numerals p =
631   let replace_in_sigma perm =
632     let rec aux = function
633     | `N n -> `N (List.nth perm n)
634     | `I _ -> assert false
635     | `Var _ as t -> t
636     | `Lam(v,t) -> `Lam(v, aux t)
637     | `Match(_,_,_,bs,_) as t -> (bs := List.map (fun (n,t) -> (List.nth perm n, t)) !bs); t
638     in List.map (fun (n,t) -> (n,aux t))
639   in
640   let deltas' = List.mapi (fun n d -> (n, List.map fst !d)) p.deltas in
641   let maxs = Array.to_list (Array.init (List.length deltas') (fun _ -> 0)) in
642   let max = List.fold_left max 0 (concat_map snd deltas') in
643   let perm,_ = List.fold_left (fun (perm, maxs) (curr_n:int) ->
644       let containing = filter_map (fun (i, bs) -> if List.mem curr_n bs then Some i else None) deltas' in
645       (* (prerr_endline (string_of_int curr_n ^ " occurs in: " ^ (String.concat " " (List.map string_of_int containing)))); *)
646       let neww = List.fold_left Pervasives.max 0 (List.mapi (fun n max -> if List.mem n containing then max else 0) maxs) in
647       let maxs = List.mapi (fun i m -> if List.mem i containing then neww+1 else m) maxs in
648       (neww::perm, maxs)
649     ) ([],maxs) (Array.to_list (Array.init (max+1) (fun x -> x))) in
650   replace_in_sigma (List.rev perm) p.sigma
651 ;;
652
653 let env_of_sigma freshno sigma should_explode =
654  let rec aux n =
655   if n > freshno then
656    []
657   else
658    let e = aux (n+1) in
659    (try
660     e,Pure.lift (-n-1) (snd (List.find (fun (i,_) -> i = n) sigma)),[]
661    with
662     Not_found ->
663      if should_explode && n = hd_of_i_var (cast_to_i_var !bomb)
664       then ([], (let f t = Pure.A(t,t) in f (Pure.L (f (Pure.V 0)))), [])
665       else ([],Pure.V n,[]))::e
666  in aux 0
667 ;;
668 (* ************************************************************************** *)
669
670 type result = [
671  | `Separable of (int * Num.nf) list
672  | `Unseparable of string
673 ]
674
675 let check p =
676  (* check if there are duplicates in p.ps *)
677  (* FIXME what about initial fragments? *)
678  if (let rec f = function
679      | [] -> false
680      | hd::tl -> List.exists (eta_eq hd) tl || f tl in
681    f p.ps)
682   then Some "ps contains duplicate entries"
683  (* check if div occurs somewhere in ps@conv *)
684  else match p.div with
685   | None -> None
686   | Some div ->
687      if (List.exists (eta_subterm div) (p.ps@p.conv))
688       then Some "div occurs as subterm in ps or conv"
689       else None
690 ;;
691
692 let solve p =
693  prerr_endline (string_of_problem "main" p);
694  match check p with
695  | Some s -> `Unseparable s
696  | None ->
697  bomb := `Var(-1,-666);
698  Console.print_hline();
699  let p_finale = auto p p.initialSpecialK in
700  let freshno,sigma = p_finale.freshno, p_finale.sigma in
701  prerr_endline ("------- <DONE> ------ measure=. \n ");
702  let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
703  List.iter (fun (x,inst) -> prerr_endline (string_of_var x ^ " := " ^ print ~l inst)) sigma;
704
705   prerr_endline "---------<OPT>----------";
706   let sigma = optimize_numerals p_finale in (* optimize numerals *)
707   let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
708   List.iter (fun (x,inst) -> prerr_endline (string_of_var x ^ " := " ^ print ~l inst)) sigma;
709
710   prerr_endline "---------<PURE>---------";
711   let t_of_nf t = ToScott.t_of_nf (t :> nf) in
712   let div = option_map t_of_nf p.div in
713   let conv = List.map t_of_nf p.conv in
714   let ps = List.map t_of_nf p.ps in
715
716   let sigma' = List.map (fun (x,inst) -> x, ToScott.t_of_nf inst) sigma in
717   let e' = env_of_sigma freshno sigma' false (* FIXME shoudl_explode *) in
718
719   prerr_endline "--------<REDUCE>---------";
720   let pure_bomb = ToScott.t_of_nf (!bomb) in (* Pure.B *)
721   (function Some div ->
722    print_endline (Pure.print div);
723    let t = Pure.mwhd (e',div,[]) in
724    prerr_endline ("*:: " ^ (Pure.print t));
725    assert (t = pure_bomb)
726   | None -> ()) div;
727   List.iter (fun n ->
728     verbose ("_::: " ^ (Pure.print n));
729     let t = Pure.mwhd (e',n,[]) in
730     verbose ("_:: " ^ (Pure.print t));
731     assert (t <> pure_bomb)
732   ) conv ;
733   List.iteri (fun i n ->
734     verbose ((string_of_int i) ^ "::: " ^ (Pure.print n));
735     let t = Pure.mwhd (e',n,[]) in
736     verbose ((string_of_int i) ^ ":: " ^ (Pure.print t));
737     assert (t = Scott.mk_n i)
738   ) ps ;
739   prerr_endline "-------- </DONE> --------";
740   `Separable p_finale.sigma
741 ;;
742
743 let zero = `Var(0,0);;
744
745 let append_zero =
746  function
747   | `I _
748   | `Var _ as i -> cast_to_i_n_var (mk_app i zero)
749   | `N _ -> raise (Parser.ParsingError " numbers in ps")
750 ;;
751
752 let tmp (label, div, conv, nums, var_names) =
753  (* DA SPOSTARE NEI TEST: *)
754  let ps = List.map append_zero nums in (* crea lista applicando zeri o dummies *)
755  let ps = sort_uniq ~compare:eta_compare (ps :> nf list) in
756  let ps = List.map (cast_to_i_n_var) ps in
757
758  (* TODO: *)
759  (* replace div with bottom in problem??? *)
760  let all_tms = (match div with None -> [] | Some div -> [(div :> i_n_var)]) @ nums @ conv in
761  if all_tms = [] then failwith "FIXME: empty problem";
762  let initialSpecialK = compute_special_k (Listx.from_list (all_tms :> nf list)) in
763  let freshno = List.length var_names in
764  let deltas =
765   let dummy = `Var (max_int / 2, -666) in
766    [ ref (Array.to_list (Array.init (List.length ps) (fun i -> i, dummy))) ] in
767  {freshno; div; conv; ps; sigma=[]; deltas; initialSpecialK; var_names; label}
768 ;;
769
770 let problem_of ~div ~conv ~nums =
771  let all_tms = (match div with None -> [] | Some div -> [div]) @ nums @ conv in
772  let all_tms, var_names = Parser.parse' all_tms in
773  let div, (ps, conv) = match div with
774    | None -> None, list_cut (List.length nums, all_tms)
775    | Some _ -> Some (List.hd all_tms), list_cut (List.length nums, List.tl all_tms) in
776
777  let div =
778   match div with
779    | None -> None
780    | Some (`I _ as t) -> Some t
781    | _ -> raise (Parser.ParsingError "div is not an inert or BOT in the initial problem") in
782  let conv = Util.filter_map (
783   function
784   | #i_n_var as t -> Some t
785   | `Lam _ -> None
786   | _ -> raise (Parser.ParsingError "A term in conv is not i_n_var")
787   ) conv in
788  let ps = List.map (
789   function
790    | #i_n_var as y -> y
791    | _ -> raise (Parser.ParsingError "A term in num is not i_n_var")
792   ) ps in
793  tmp("missing label", div, conv, ps, var_names)
794 ;;