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