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