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