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