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