]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/lambda4.ml
Detection of divergents
[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 (* 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 "nth" -> "`" ^ 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
440     let n = match div with `I(_,args) -> Listx.length args | `Var _ -> 0 in
441     let p, bomb' = make_fresh_var p (-666) in
442     (if !bomb <> `Var (-1,-666) then
443      failwithProblem p
444       ("Bomb was duplicated! It was " ^ string_of_nf !bomb ^
445        ", tried to change it to " ^ string_of_nf bomb'));
446     bomb := bomb';
447     prerr_endline ("Just created bomb var: " ^ string_of_nf !bomb);
448     let x = hd_of_i_var div in
449     let inst = make_lams !bomb n in
450     let p = {p with div=None} in
451     (* subst_in_problem (hd_of_i_var div) inst p in *)
452      {p with sigma=p.sigma@[x,inst]} in
453      let dangerous_conv = showstoppers_conv in
454 prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
455 List.iter (fun l -> prerr_endline (String.concat " " (List.map (string_of_var p.var_names) l))) dangerous_conv;
456  let conv =
457    List.map (function s,t ->
458     try
459      if s <> [] then t else (
460      (match t with | `Var _ -> raise Not_found | _ -> ());
461      let _ = List.find (fun h -> hd_of t = Some h) inedible in
462       t)
463     with Not_found -> match hd_of t with
464      | None -> assert (t = convergent_dummy); t
465      | Some h ->
466       prerr_endline ("FREEZING " ^ string_of_var p.var_names h);
467       convergent_dummy
468    ) (List.combine showstoppers_conv p.conv) in
469  List.iter
470   (fun bs ->
471     bs :=
472      List.map
473       (fun (n,t as res) ->
474         match List.nth ps n with
475            `N m -> m,t
476          | _ -> res
477       ) !bs
478   ) p.deltas ;
479  let old_conv = p.conv in
480  let p = { p with ps; conv } in
481  if l <> [] || old_conv <> conv
482   then prerr_endline (string_of_problem "eat" p);
483  if List.for_all (function `N _ -> true | _ -> false) ps && p.div = None then
484   `Finished p
485  else
486   `Continue p
487
488 let instantiate p x n =
489  (if hd_of_i_var (cast_to_i_var !bomb) = x
490    then failwithProblem p ("BOMB (" ^ string_of_nf !bomb ^ ") cannot be instantiated!"));
491  let arity_of_x = max_arity_tms x (all_terms p) in
492  (if arity_of_x = None then failwithProblem p "step on var non occurring in problem");
493  (if Util.option_get(arity_of_x) = min_int then failwithProblem p "step on fake variable");
494  (if Util.option_get(arity_of_x) <= 0 then failwithProblem p "step on var of non-positive arity");
495  let n = (prerr_endline "WARNING: using constant initialSpecialK"); p.initialSpecialK in
496  (* AC: Once upon a time, it was:
497     let arities = Num.compute_arities x (n+1) (all_terms p :> nf list) in *)
498  (* let arities = Array.to_list (Array.make (n+1) 0) in *)
499  let arities = Array.to_list (Array.make (n+1) min_int) in
500  let p,vars = make_fresh_vars p arities in
501  let args = Listx.from_list (vars :> nf list) in
502  let bs = ref [] in
503  (* 666, since it will be replaced anyway during subst: *)
504  let inst = `Lam(false,`Match(`I((0,min_int),Listx.map (lift 1) args),(x,-666),1,bs,[])) in
505  let p = {p with deltas=bs::p.deltas} in
506  subst_in_problem x inst p
507 ;;
508
509 let compute_special_k tms =
510  let rec aux k (t: nf) = Pervasives.max k (match t with
511  | `Lam(b,t) -> aux (k + if b then 1 else 0) t
512  | `I(n, tms) -> Listx.max (Listx.map (aux 0) tms)
513  | `Match(t, _, liftno, bs, args) ->
514      List.fold_left max 0 (List.map (aux 0) ((t :> nf)::args@List.map snd !bs))
515  | `N _
516  | `Var _ -> 0
517  ) in
518  let rec aux' top t = match t with
519  | `Lam(_,t) -> aux' false t
520  | `I((_,ar), tms) -> max ar
521      (Listx.max (Listx.map (aux' false) (tms :> nf Listx.listx)))
522  | `Match(t, _, liftno, bs, args) ->
523      List.fold_left max 0 (List.map (aux' false) ((t :> nf)::(args :> nf list)@List.map snd !bs))
524  | `N _
525  | `Var _ -> 0 in
526  Listx.max (Listx.map (aux 0) tms) + Listx.max (Listx.map (aux' true) tms)
527 ;;
528
529 let auto_instantiate (n,p) =
530  let p, showstoppers_step, showstoppers_eat = critical_showstoppers p in
531  let x =
532   match showstoppers_step, showstoppers_eat with
533   | [], y::_ ->
534      prerr_endline ("INSTANTIATING CRITICAL TO EAT " ^ string_of_var p.var_names y); y
535   | [], [] ->
536      let heads =
537       (* Choose only variables still alive (with arity > 0) *)
538       List.sort compare (filter_map (
539        fun t -> match t with `Var _ -> None | x -> if arity_of_hd x <= 0 then None else hd_of x
540       ) ((match p.div with Some t -> [(t :> i_n_var)] | _ -> []) @ p.ps)) in
541      (match heads with
542       | [] ->
543          (try
544            fst (List.find (((<) 0) ++ snd) (concat_map free_vars' (p.conv :> nf list)))
545           with
546            Not_found -> assert false)
547       | x::_ ->
548          prerr_endline ("INSTANTIATING TO EAT " ^ string_of_var p.var_names x);
549          x)
550   | x::_, _ ->
551       prerr_endline ("INSTANTIATING " ^ string_of_var p.var_names x);
552       x in
553  let special_k =
554      compute_special_k (Listx.from_list (all_terms p :> nf list) )in
555  if special_k < n then
556   prerr_endline ("@@@@ NEW INSTANTIATE PHASE (" ^ string_of_int special_k ^ ") @@@@");
557  let p = instantiate p x special_k in
558  special_k,p
559
560
561 let rec auto_eat (n,p) =
562  prerr_endline "{{{{{{{{ Computing measure before auto_instantiate }}}}}}";
563  let m = problem_measure p in
564  let (n,p') = auto_instantiate (n,p) in
565  match eat p' with
566  | `Finished p -> p
567  | `Continue p ->
568      prerr_endline "{{{{{{{{ Computing measure inafter auto_instantiate }}}}}}";
569      let delta = problem_measure p - m in
570      (* let delta = m - problem_measure p' in *)
571      if delta >= 0
572       then
573        (failwith
574        ("Measure did not decrease (+=" ^ string_of_int delta ^ ")"))
575       else prerr_endline ("$ Measure decreased of " ^ string_of_int delta);
576      auto_eat (n,p)
577 ;;
578
579 let auto p n =
580  prerr_endline ("@@@@ FIRST INSTANTIATE PHASE (" ^ string_of_int n ^ ") @@@@");
581  match eat p with
582  | `Finished p -> p
583  | `Continue p -> auto_eat (n,p)
584 ;;
585
586 (*
587 0 = snd
588
589       x y = y 0    a y = k  k z = z 0  c y = k   y u = u h1 h2 0          h2 a = h3
590 1 x a c    1 a 0 c  1 k c    1 c 0      1 k        1 k                     1 k
591 2 x a y    2 a 0 y  2 k y    2 y 0      2 y 0      2 h2 0                  2 h3
592 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)
593 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
594 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
595 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
596
597                                 l2 _ = l3
598 b u = u l1 l2 0                 e _ _ _ _ = f                         l3 n = n j 0
599 1 k                             1 k                                  1 k
600 2 h3                            2 h3                                 2 h3
601 3 l2 0 (\u. u h1 (\w. h3) 0)    3 l3 (\u. u h1 (\w. h3) 0)           3 j h1 (\w. h3) 0 0
602 4 l2 0 c                        4 l3 c                               4 c j 0
603 5 e l1 l2 0 0                   5 f                                  5 f
604 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
605 *)
606
607 (*
608                 x n = n 0 ?
609 x a (b (a c))   a 0 = 1 ? (b (a c))   8
610 x a (b d')      a 0 = 1 ? (b d')      7
611 x b (a c)       b 0 = 1 ? (a c)       4
612 x b (a c')      b 0 = 1 ? (a c')      5
613
614 c = 2
615 c' = 3
616 a 2 = 4  (* a c *)
617 a 3 = 5  (* a c' *)
618 d' = 6
619 b 6 = 7  (* b d' *)
620 b 4 = 8  (* b (a c) *)
621 b 0 = 1
622 a 0 = 1
623 *)
624
625 (************** Tests ************************)
626
627 let optimize_numerals p =
628   let replace_in_sigma perm =
629     let rec aux = function
630     | `N n -> `N (List.nth perm n)
631     | `I _ -> assert false
632     | `Var _ as t -> t
633     | `Lam(v,t) -> `Lam(v, aux t)
634     | `Match(_,_,_,bs,_) as t -> (bs := List.map (fun (n,t) -> (List.nth perm n, t)) !bs); t
635     in List.map (fun (n,t) -> (n,aux t))
636   in
637   let deltas' = List.mapi (fun n d -> (n, List.map fst !d)) p.deltas in
638   let maxs = Array.to_list (Array.init (List.length deltas') (fun _ -> 0)) in
639   let max = List.fold_left max 0 (concat_map snd deltas') in
640   let perm,_ = List.fold_left (fun (perm, maxs) (curr_n:int) ->
641       let containing = filter_map (fun (i, bs) -> if List.mem curr_n bs then Some i else None) deltas' in
642       (* (prerr_endline (string_of_int curr_n ^ " occurs in: " ^ (String.concat " " (List.map string_of_int containing)))); *)
643       let neww = List.fold_left Pervasives.max 0 (List.mapi (fun n max -> if List.mem n containing then max else 0) maxs) in
644       let maxs = List.mapi (fun i m -> if List.mem i containing then neww+1 else m) maxs in
645       (neww::perm, maxs)
646     ) ([],maxs) (Array.to_list (Array.init (max+1) (fun x -> x))) in
647   replace_in_sigma (List.rev perm) p.sigma
648 ;;
649
650 let env_of_sigma freshno sigma should_explode =
651  let rec aux n =
652   if n > freshno then
653    []
654   else
655    let e = aux (n+1) in
656    (try
657     e,Pure.lift (-n-1) (snd (List.find (fun (i,_) -> i = n) sigma)),[]
658    with
659     Not_found ->
660     if n = hd_of_i_var (cast_to_i_var !bomb)
661      then ([], Pure.omega should_explode, [])
662      else ([], Pure.V n, []) ) :: e
663  in aux 0
664 ;;
665 (* ************************************************************************** *)
666
667 type result = [
668  | `Separable of (int * Num.nf) list
669  | `Unseparable of string
670 ]
671
672 let check p =
673  (* TODO check if there are duplicates in p.ps
674      before it was: ps = sort_uniq ~compare:eta_compare (ps :> nf list) *)
675  (* FIXME what about initial fragments? *)
676  if (let rec f = function
677      | [] -> false
678      | hd::tl -> List.exists (eta_eq hd) tl || f tl in
679    f p.ps)
680   then Some "ps contains duplicate entries"
681  (* check if div occurs somewhere in ps@conv *)
682  else match p.div with
683   | None -> None
684   | Some div ->
685      if (List.exists (eta_subterm div) (p.ps@p.conv))
686       then Some "div occurs as subterm in ps or conv"
687       else None
688 ;;
689
690 let solve p =
691  prerr_endline (string_of_problem "main" p);
692  match check p with
693  | Some s -> `Unseparable s
694  | None ->
695  bomb := `Var(-1,-666);
696  Console.print_hline();
697  let p_finale = auto p p.initialSpecialK in
698  let freshno,sigma = p_finale.freshno, p_finale.sigma in
699  prerr_endline ("------- <DONE> ------ measure=. \n ");
700  List.iter (fun (x,inst) -> prerr_endline
701  (string_of_var p_finale.var_names x ^ " := " ^ string_of_term p_finale inst)) sigma;
702
703  prerr_endline "---------<OPT>----------";
704  let sigma = optimize_numerals p_finale in (* optimize numerals *)
705  List.iter (fun (x,inst) -> prerr_endline
706   (string_of_var p_finale.var_names x ^ " := " ^ string_of_term p_finale inst)) sigma;
707
708  prerr_endline "---------<PURE>---------";
709  let scott_of_nf t = ToScott.t_of_nf (t :> nf) in
710  let div = option_map scott_of_nf p.div in
711  let conv = List.map scott_of_nf p.conv in
712  let ps = List.map scott_of_nf p.ps in
713
714  let sigma' = List.map (fun (x,inst) -> x, scott_of_nf inst) sigma in
715  let e' = env_of_sigma freshno sigma' false in
716  let e'' = env_of_sigma freshno sigma' true in
717
718  prerr_endline "--------<REDUCE>---------";
719  (function
720    | Some div ->
721       print_endline (Pure.print div);
722       let t = Pure.mwhd (e',div,[]) in
723       prerr_endline ("*:: " ^ (Pure.print t));
724       assert (Pure.diverged t)
725    | None -> ()) div;
726  List.iter (fun n ->
727   verbose ("_::: " ^ (Pure.print n));
728   let t = Pure.mwhd (e'',n,[]) in
729   verbose ("_:: " ^ (Pure.print t));
730   assert (not (Pure.diverged t))
731  ) conv ;
732  List.iteri (fun i n ->
733   verbose ((string_of_int i) ^ "::: " ^ (Pure.print n));
734   let t = Pure.mwhd (e',n,[]) in
735   verbose ((string_of_int i) ^ ":: " ^ (Pure.print t));
736   assert (t = Scott.mk_n i)
737  ) ps ;
738  prerr_endline "-------- </DONE> --------";
739  `Separable p_finale.sigma
740 ;;
741
742 let problem_of (label, div, conv, ps, var_names) =
743  (* TODO: replace div with bottom in problem??? *)
744  let all_tms = (match div with None -> [] | Some div -> [(div :> i_n_var)]) @ ps @ conv in
745  if all_tms = [] then failwith "problem_of: empty problem";
746  let initialSpecialK = compute_special_k (Listx.from_list (all_tms :> nf list)) in
747  let freshno = List.length var_names in
748  let deltas =
749   let dummy = `Var (max_int / 2, -666) in
750    [ ref (Array.to_list (Array.init (List.length ps) (fun i -> i, dummy))) ] in
751  {freshno; div; conv; ps; sigma=[]; deltas; initialSpecialK; var_names; label}
752 ;;