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