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