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