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