]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/lambda4.ml
6b59ed9fc065fdc95678bd0103de356102ff28ee
[fireball-separation.git] / ocaml / lambda4.ml
1 open Util
2 open Util.Vars
3 open Pure
4 open Num
5
6 let bomb = ref(`Var ~-1);;
7
8 type var = int;;
9
10 type problem =
11  { freshno: int
12  ; div: i_var option (* None = bomb *)
13  ; conv: i_n_var list (* the inerts that must converge *)
14  ; ps: i_n_var list (* the n-th inert must become n *)
15  ; sigma: (var * nf) list (* the computed substitution *)
16  ; deltas: (int * nf) list ref list (* collection of all branches *)
17  (* ; steps: int (* the bound on the number of steps *) *)
18  ; arities: int list
19  ; special_k: int
20  }
21
22 let string_of_nf {freshno} t =
23  let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
24  print ~l (t :> nf)
25 ;;
26
27 (* let heads = Util.sort_uniq (List.map hd_of_i_var p.ps) in
28 for all head
29   List.map (fun (_, bs) -> List.map (fun (x,_) -> List.nth p.ps x) !bs) p.deltas *)
30
31 (* let ($) f x = f x;; *)
32
33
34 let subterms tms freshno =
35  let apply_var =
36   let no = ref freshno in
37   function t -> incr no; mk_app t (`Var !no) in
38  let applicative hd args = snd (
39     List.fold_left (fun (hd, acc) t -> let hd = mk_app hd t in hd, hd::acc) (hd, []) args) in
40  let rec aux t = match t with
41  | `Var _ -> []
42  | `I(v,ts) ->
43     (* applicative (`Var v) (Listx.to_list ts) @  *)
44      Util.concat_map aux (Listx.to_list ts) @ List.map apply_var (Listx.to_list ts)
45  | `Lam(_,t) -> aux (lift ~-1 t)
46  | `Match(u,bs_lift,bs,args) ->
47     aux (u :> nf) @
48      (* applicative (`Match(u,bs_lift,bs,[])) args @ *)
49       Util.concat_map aux args @ List.map apply_var args
50       (* @ Util.concat_map (aux ++ (lift bs_lift) ++ snd) !bs *)
51  | `N _ -> []
52  in let tms' = (* Util.sort_uniq ~compare:eta_compare*) (Util.concat_map aux tms) in
53  tms @ tms'
54  (* List.map (fun (t, v) -> match t with `N _ -> t | _ -> mk_app t v) (List.combine tms (List.mapi (fun i _ -> `Var(freshno+i)) tms)) *)
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 problem_measure p =
64  (* let l = Array.to_list (Array.init (p.freshno + 1) string_of_var) in *)
65  let open Listx in
66  (* aux |t1;t2| e' numero di step per portare la diff in testa
67     INVARIANTE: t1 <eta> t2
68  *)
69  let rec aux t1 t2 =
70   match t1, t2 with
71   | `I(v1,nfs1), `I(v2,nfs2) ->
72     if v1 <> v2
73      then 0 else 1 + find_first_diff (to_list nfs1, to_list nfs2)
74   | `Match (t1,bs_lift,bs,args), `Match (t2,bs_lift',bs',args') ->
75      if bs != bs' then 0 (* TODO *)
76       else if eta_eq (t1 :> nf) (t2 :> nf) then 1 + find_first_diff (args, args') else aux (t1 :> nf) (t2 :> nf) (* TODO *)
77   | `Match _, _
78   | _, `Match _ -> 0 (* FIXME!!! *)
79   | `Lam(_,t1), `Lam(_,t2) -> aux t1 t2
80   | _ -> 0
81  and find_first_diff = function
82   | [], [] -> assert false
83   | [], t::_
84   | t::_, [] -> 1
85   | t1::ts1, t2::ts2 ->
86     if eta_eq (t1 :> nf) (t2 :> nf) then 1 + find_first_diff (ts1, ts2) else aux t1 t2
87     (* no. di step da fare per separare t1 e t2 *)
88  in let diff t1 t2 = (
89   let res = if eta_eq t1 t2 then 0 else aux t1 t2 in
90   (* if res <> 0 then prerr_endline ("diff (" ^ print ~l t1 ^ ") (" ^ print ~l t2 ^ ") = " ^ string_of_int res); *)
91   res
92   )
93  (* aux calcola la somma delle differenze tra i termini in una lista (quadratico) *)
94  in let rec sum = function
95   | [] -> 0
96   | x::xs -> List.fold_right ((+) ++ (diff (x :> nf))) (xs :> nf list) (sum xs)
97  in let subterms = subterms ((all_terms p) :> nf list) p.freshno
98  (* let subterms = sort_uniq ~compare:eta_compare subterms in *)
99  in let a = sum subterms
100  in let b = List.fold_right (fun bs -> (+) (sum (List.map ((List.nth p.ps) ++ fst) !bs))) p.deltas 0
101  in let _ = prerr_endline ("Computed measure: " ^ string_of_int a ^ "," ^ string_of_int b)
102  in a + b
103 ;;
104
105 (* AC MEASURE *)
106 module ACMeasure = struct
107 type var = int;;
108
109 type state = {
110  freshno : int;
111  arities : int list;
112  p : problem;
113 }
114
115 let string_of_state s =
116  "STATE\n - arities: " ^
117  String.concat " " (List.mapi (fun v n -> "`"^string_of_var v ^ "=" ^ string_of_int n) s.p.arities)
118 ;;
119
120 let rec get_var_of_match bs p =
121  let rec aux = function
122  | (v,`Lam(_,`Match(_,_,bs',_)))::sigma -> if bs = bs' then v else aux sigma
123  | _::sigma -> aux sigma
124  | [] -> assert false
125  in aux p.sigma
126 ;;
127
128 let mk_freshvar s =
129  let freshno = s.freshno + 1 in
130  {s with freshno}, freshno
131 ;;
132
133 let rec mk_apps vmap (h : nf) (args : var list) =
134  let aux l = Listx.from_list (List.map (fun x -> `Var x) l) in
135  match h,args with
136   | _, [] -> vmap, h
137   | `I(n,args'), _ -> vmap, `I(n, Listx.append (aux args) args')
138   | `Var n, _ -> vmap, `I(n, aux args)
139   | `Lam(_,nf), a::args -> mk_apps (a::vmap) (lift ~-1 nf) args
140   | `Match(t,lift,bs,args'), _ -> vmap, `Match(t,lift,bs,List.append args' (Listx.to_list (aux args)))
141   | _ -> assert false
142 ;;
143
144 let mk_freshvars s n = Array.fold_right (fun () (s,acc) -> let s, v = mk_freshvar s in s, v::acc ) (Array.make n ()) (s, [])
145 ;;
146
147 let get_arity_of_var p v t =
148  (* prerr_endline (string_of_nf p t); *)
149  let rec aux level = function
150  | `Var _ | `N _-> 0
151  | `I(v', tms) as t ->
152     max
153      (if v + level = v' then (
154       (* prerr_endline("found applied " ^ string_of_var v ^" in "^print (lift (-level) t)); *)
155       Listx.length tms) else 0)
156      (aux_listx level tms)
157  | `Lam(_,t) -> aux (level + 1) t
158  | `Match(t, liftno, bs, args) -> max (aux level (t :> nf)) (aux_list level args)
159  and aux_listx level listx = Listx.fold_left (fun x t -> max x (aux level t)) 0 listx
160  and aux_list level lst = List.fold_left (fun x t -> max x (aux level t)) 0 lst
161  in aux 0 t
162 ;;
163
164 (* let mk_apps t args = List.fold_left mk_app t args;; *)
165
166 let first_arg = function
167  | Listx.Nil x
168  | Listx.Cons(x,_) -> x
169 ;;
170
171 let find_first_args var =
172  let rec aux level : nf -> nf list = function
173  | `Var _ | `N _ -> []
174  | `I(v, args) -> (if var + level = v then [first_arg args] else []) @ (Util.concat_map (aux level) (Listx.to_list args))
175  | `Lam(_,t) -> aux (level+1) t
176  | `Match(t, liftno, bs, args) -> aux level (t :> nf) @ (Util.concat_map (aux level) (args))
177  in aux 0
178 ;;
179
180 let remove_lambdas k t =
181  let rec aux = function
182  | `Lam(_,t) -> aux t
183  | _ as t -> t
184  in lift (-k) (aux t)
185 ;;
186
187 let get_arity_of_continuation p v =
188  if !bomb = `Var v then 0 else (
189   let bs = List.find (fun bs -> List.exists (fun (_,t) -> t = `Var v) !bs) p.deltas in
190   let orig = get_var_of_match bs p in
191   List.nth p.arities orig
192  )
193 ;;
194
195 let fix_arities p v freshvars =
196  let all_terms = (all_terms p :> nf list) in
197  let args = Util.concat_map (find_first_args v) all_terms in
198  let k = List.length freshvars in
199  let args = List.map (remove_lambdas k) args in
200  prerr_endline ("delifted lambdas in which to look for "^ string_of_var v);
201  (* List.iter (fun t -> prerr_endline(strilogng_of_nf p t)) args; *)
202  (* assert (List.length args > 0); *)
203  List.iter (fun v -> prerr_endline ("var to fix: fresh " ^ string_of_var v)) freshvars;
204  let find_arities_args v = let i = List.fold_left (fun x t -> max x (get_arity_of_var p v t)) 0 args in prerr_endline ("found arity in args of " ^ string_of_var (List.nth (List.rev freshvars) (v+1)) ^ ": " ^ string_of_int i); i in
205  (* let find_arities_all v = List.fold_left (fun x t -> max x (get_arity_of_var p v t)) 0 all_terms in *)
206  let arities = List.mapi (fun var () ->
207   if var < List.length p.arities
208    then List.nth p.arities var
209    else if List.mem var freshvars
210     then 1 + find_arities_args (Util.index_of var (List.rev freshvars) - 1)
211     (* else find_arities_all var *)
212     else (get_arity_of_continuation p var) - 1
213  ) (Array.to_list (Array.make (p.freshno+1) ())) in
214  assert (List.length arities = (p.freshno + 1));
215  (* prerr_endline ("arities added : " ^ string_of_int (List.length freshvars)); *)
216  (* List.iter (fun (v,n) -> prerr_endline(string_of_int v ^ "=" ^ string_of_int n)) arities; *)
217  {p with arities}
218 ;;
219
220 let measure =
221  let rec aux (s:state) vmap =
222  let p = s.p in
223  let realvar vmap v =
224   (* prerr_endline ("waant " ^ string_of_int v ^ "; we have "^ string_of_int (List.length vmap)); *)
225   if v < 0 then List.nth vmap (-1-v) else v in
226  function
227  | `Var _ | `N _-> 0
228  | `I(v, tms) -> assert (List.length s.arities = (s.freshno + 1)); 1 +
229    let v = realvar vmap v in
230    (* prerr_endline ("lookup for arity of " ^ string_of_int v ^ "with freshno =" ^ string_of_int s.freshno ^ " and length = " ^ string_of_int (List.length s.arities)); *)
231    let arity = List.nth s.arities v in
232    1 + if arity = 0 then 0 else (
233     let first, rest = (match tms with
234     | Listx.Nil x -> x, []
235     | Listx.Cons(a,b) -> a, Listx.to_list b) in
236     (
237      let s, vars = mk_freshvars s (1+s.p.special_k) in
238      let vmap, t = mk_apps vmap first (vars) in
239      let arities = List.mapi (fun v () ->
240       if v < List.length s.arities
241        then List.nth s.arities v
242        else get_arity_of_var p (realvar vmap v) t
243      ) (Array.to_list (Array.make (s.freshno + 1) ())) in
244      (* let arities = (List.map (fun v -> v, get_arity_of_var p (realvar vmap' v) t) vars) in *)
245      (* let arities = arities @ s.arities in *)
246      let s = {s with arities} in
247      aux s vmap t
248     ) + (
249      let s, fresh = mk_freshvar s in
250      let arities = s.arities @ [arity - 1] in
251      let s = {s with arities} in
252      if rest = [] then aux s vmap (`Var fresh) else
253       aux s vmap (`I (fresh, Listx.from_list rest))
254     )
255    )
256   | `Match(t, _, bs, rest) ->
257      let tmp = aux s vmap (t :> nf) in
258      let s, fresh = mk_freshvar s in
259      let arity = List.nth s.arities (get_var_of_match bs s.p) in
260      let arities = s.arities @ [arity - 1] in
261      let s = {s with arities} in
262      tmp + if rest = [] then aux s vmap (`Var(fresh)) else
263       aux s vmap (`I(fresh, Listx.from_list rest))
264   | `Lam _ -> assert false
265  in fun s -> aux s []
266 ;;
267
268
269 (* let measure p =
270  let rec m = function
271  | `N _ | `Var  _ -> 0
272  | `I(_,args) ->
273    let args = Listx.to_list args in
274    List.fold_left (fun acc t -> acc + m t) (1 + Listx.length args) args
275  | `Lam(_,t) -> m t
276  | `Match(t, lft, bs, rest) ->
277    (* let var = get_var_of_match bs p in *)
278    let args = rest in m (t :> nf) + List.fold_left (fun acc t -> acc + m t) (aux args) args
279
280 and aux = function
281  | [] -> 0
282  | x::xs -> m x + if aux xs = 0 then 0 else 1 + aux xs
283 in m
284 ;;*)
285
286 let measure_many s tms = List.fold_left (fun x t -> x + (measure s t)) 0 tms;;
287
288 let map_max f l = List.fold_left (fun x t -> max x (f t)) 0 l;;
289
290 let measure_of_problem p =
291  let tms = (all_terms p :> nf list) in
292  let freshno = p.freshno in
293  let arities = p.arities in
294  let s = {arities; freshno; p} in
295  prerr_endline (string_of_state s);
296  let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
297  List.iter (fun t -> prerr_endline (string_of_int (measure s t) ^ " ::" ^ print ~l t)) tms;
298  let m = measure_many s tms in
299  (* prerr_endline (string_of_int m); *)
300  m
301 ;;
302 end;;
303
304 let measure_of_problem = ACMeasure.measure_of_problem;;
305 let problem_measure = measure_of_problem;;
306 (* AC MEASURE *)
307
308 let print_problem label ({freshno; div; conv; ps; deltas} as p) =
309  (* assert (p.steps > List.length p.sigma); *)
310  let measure = try
311   problem_measure p
312  with
313  | _ -> -1 in
314  Console.print_hline ();
315  prerr_endline ("\n||||| Displaying problem: " ^ label ^ " |||||");
316  let nl = "\n| " in
317  let deltas = String.concat nl (List.map (fun r -> String.concat " <> " (List.map (fun (i,_) -> string_of_int i) !r)) deltas) in
318  let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
319     nl ^
320     (* (string_of_int (steps - List.length p.sigma)) ^ " steps left;" ^ *)
321     "measure="^string_of_int measure ^" freshno = " ^ string_of_int freshno
322  ^ nl ^ "\b> DISCRIMINATING SETS (deltas)"
323  ^ nl ^ deltas ^ (if deltas = "" then "" else nl)
324  ^ "\b> DIVERGENT" ^ nl
325  ^ "*: " ^ (match div with None -> "*" | Some div -> print ~l (div :> nf)) ^ "\n| "
326  ^ "\b> CONVERGENT" ^ nl
327  ^ String.concat "\n| " (List.map (fun t -> "_: " ^ (if t = `N (-1) then "_" else print ~l (t :> nf))) conv) ^
328  (if conv = [] then "" else "\n| ")
329  ^ "\b> NUMERIC" ^ nl
330  ^ String.concat "\n| " (List.mapi (fun i t -> string_of_int i ^ ": " ^ print ~l (t :> nf)) ps)
331  ^ nl
332 ;;
333
334
335 let failwithProblem p reason =
336  print_endline (print_problem "FAIL" p);
337  failwith reason
338 ;;
339
340 let make_fresh_var p =
341  let freshno = p.freshno + 1 in
342  {p with freshno}, `Var freshno
343 ;;
344
345 let make_fresh_vars p m =
346  Array.fold_left
347   (* fold_left vs. fold_right hides/shows the bug in problem q7 *)
348   (fun (p, vars) _ -> let p, var = make_fresh_var p in p, var::vars)
349   (p, [])
350   (Array.make m ())
351 ;;
352
353 let simple_expand_match ps =
354   let rec aux level = function
355   | #i_num_var as t -> aux_i_num_var level t
356   | `Lam(b,t) -> `Lam(b, aux (level+1) t)
357   and aux_i_num_var level = function
358   | `Match(u,bs_lift,bs,args) as torig ->
359     let u = aux_i_num_var level u in
360     bs := List.map (fun (n, x) -> n, aux 0 x) !bs;
361     (try
362        (match u with
363          | #i_n_var as u ->
364             let i = index_of (lift (-level) u) (ps :> nf list) (* can raise Not_found *)
365             in let t = mk_match (`N i) bs_lift bs args in
366             if t <> torig then
367             aux level (t :> nf)
368            else raise Not_found
369          | _ -> raise Not_found)
370       with Not_found ->
371        `Match(cast_to_i_num_var u,bs_lift,bs,List.map (aux level) args))
372   | `I(k,args) -> `I(k,Listx.map (aux level) args)
373   | `N _ | `Var _ as t -> t
374 in aux_i_num_var 0;;
375
376 let fixpoint f =
377  let rec aux x = let x' = f x in if x <> x' then aux x' else x in aux
378 ;;
379
380 let rec super_simplify_ps ps =
381  fixpoint (List.map (cast_to_i_num_var ++ (simple_expand_match ps)))
382 ;;
383
384 let super_simplify ({div; ps; conv} as p) =
385   let ps = super_simplify_ps p.ps (p.ps :> i_num_var list) in
386   let conv = super_simplify_ps ps (p.conv :> i_num_var list) in
387   let div = option_map (fun div ->
388    let divs = super_simplify_ps p.ps ([div] :> i_num_var list) in
389     List.hd divs) div in
390   {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}
391
392 exception ExpandedToLambda;;
393
394 let subst_in_problem x inst ({freshno; div; conv; ps; sigma} as p) =
395  let len_ps = List.length ps in
396 (*(let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
397 prerr_endline ("# INST0: " ^ string_of_var x ^ " := " ^ print ~l inst));*)
398  let rec aux ((freshno,acc_ps,acc_new_ps) as acc) =
399   function
400   | [] -> acc
401   | t::todo_ps ->
402 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
403      let t = subst false x inst (t :> nf) in
404 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
405      let freshno,new_t,acc_new_ps =
406       expand_match (freshno,acc_ps@`Var(max_int/3)::todo_ps,acc_new_ps) t
407      in
408       aux (freshno,acc_ps@[new_t],acc_new_ps) todo_ps
409
410   (* cut&paste from aux above *)
411   and aux' ps ((freshno,acc_conv,acc_new_ps) as acc) =
412    function
413    | [] -> acc
414    | t::todo_conv ->
415 (*prerr_endline ("EXPAND t:" ^ print (t :> nf));*)
416       (* try *)
417        let t = subst false x inst (t :> nf) in
418 (*prerr_endline ("SUBSTITUTED t:" ^ print (t :> nf));*)
419        let freshno,new_t,acc_new_ps =
420         expand_match (freshno,ps,acc_new_ps) t
421        in
422         aux' ps (freshno,acc_conv@[new_t],acc_new_ps) todo_conv
423       (* with ExpandedToLambda -> aux' ps (freshno,acc_conv@[`N(-1)],acc_new_ps) todo_conv *)
424
425   (* cut&paste from aux' above *)
426   and aux'' ps (freshno,acc_new_ps) =
427    function
428    | None -> freshno, None, acc_new_ps
429    | Some t ->
430       let t = subst false x inst (t :> nf) in
431       let freshno,new_t,acc_new_ps =
432        expand_match (freshno,ps,acc_new_ps) t
433       in
434        freshno,Some new_t,acc_new_ps
435
436   and expand_match ((freshno,acc_ps,acc_new_ps) as acc) t =
437    match t with
438    | `Match(u',bs_lift,bs,args) ->
439         let freshno,u,acc_new_ps = expand_match acc (u' :> nf) in
440         let acc_new_ps,i =
441          match u with
442          | `N i -> acc_new_ps,i
443          | _ ->
444             let ps = List.map (fun t -> cast_to_i_num_var (subst false x inst (t:> nf))) (acc_ps@acc_new_ps) in
445             let super_simplified_ps = super_simplify_ps ps ps in
446 (*prerr_endline ("CERCO u:" ^ print (fst u :> nf));
447 List.iter (fun x -> prerr_endline ("IN: " ^ print (fst x :> nf))) ps;
448 List.iter (fun x -> prerr_endline ("IN2: " ^ print (fst x :> nf))) super_simplified_ps;*)
449             match index_of_opt ~eq:eta_eq super_simplified_ps u with
450                Some i -> acc_new_ps, i
451              | None -> acc_new_ps@[u], len_ps + List.length acc_new_ps
452         in
453          let freshno=
454           if List.exists (fun (j,_) -> i=j) !bs then
455            freshno
456           else
457            let freshno,v = freshno+1, `Var (freshno+1) in (* make_fresh_var freshno in *)
458            bs := !bs @ [i, v] ;
459            freshno in
460 (*prerr_endlie ("t DA RIDURRE:" ^ print (`Match(`N i,arity,bs_lift,bs,args) :> nf) ^ " more_args=" ^ string_of_int more_args);*)
461          let t = mk_match (`N i) bs_lift bs args in
462 (*prerr_endline ("NUOVO t:" ^ print (fst t :> nf) ^ " more_args=" ^ string_of_int (snd t));*)
463           expand_match (freshno,acc_ps,acc_new_ps) t
464    | `Lam _ -> raise ExpandedToLambda
465    | #i_n_var as x ->
466       let x = simple_expand_match (acc_ps@acc_new_ps) x in
467       freshno,cast_to_i_num_var x,acc_new_ps in
468
469  let freshno,old_ps,new_ps = aux (freshno,[],[]) (ps :> i_num_var list) in
470  let freshno,conv,new_ps = aux' old_ps (freshno,[],new_ps) (conv :> i_num_var list) in
471  let freshno,div,new_ps = aux'' old_ps (freshno,new_ps) (div :> i_num_var option) in
472  let div = option_map cast_to_i_var div in
473  let ps = List.map cast_to_i_n_var (old_ps @ new_ps) in
474  let conv = List.map cast_to_i_n_var conv in
475 (let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
476 prerr_endline ("# INST: " ^ string_of_var x ^ " := " ^ print ~l inst));
477  let p = {p with freshno; div; conv; ps} in
478  ( (* check if double substituting a variable *)
479   if List.exists (fun (x',_) -> x = x') sigma
480    then failwithProblem p "Variable replaced twice"
481  );
482  let p = {p with sigma = sigma@[x,inst]} in
483  let p = super_simplify p in
484  print_endline (print_problem "instantiate" p);
485  p
486 ;;
487
488 exception Dangerous
489
490 let arity_of arities k =
491  let _,pos,y = List.find (fun (v,_,_) -> v=k) arities in
492  let arity = match y with `Var _ -> 0 | `I(_,args) -> Listx.length args | _ -> assert false in
493  arity + if pos = -1 then - 1 else 0
494 ;;
495
496 let rec dangerous arities showstoppers =
497  function
498     `N _
499   | `Var _
500   | `Lam _ -> ()
501   | `Match(t,liftno,bs,args) ->
502       (* CSC: XXX partial dependency on the encoding *)
503       (match t with
504           `N _ -> List.iter (dangerous arities showstoppers) args
505         | `Match _ as t -> dangerous arities showstoppers t ; List.iter (dangerous arities showstoppers) args
506         | `Var x -> dangerous_inert arities showstoppers x args 2 (* 2 coming from Scott's encoding *)
507         | `I(x,args') -> dangerous_inert arities showstoppers x (Listx.to_list args' @ args) 2 (* 2 coming from Scott's encoding *)
508       )
509   | `I(k,args) -> dangerous_inert arities showstoppers k (Listx.to_list args) 0
510
511 and dangerous_inert arities showstoppers k args more_args =
512  List.iter (dangerous arities showstoppers) args ;
513  if List.mem k showstoppers then raise Dangerous else
514  try
515   let arity = arity_of arities k in
516   if List.length args + more_args > arity then raise Dangerous else ()
517  with
518   Not_found -> ()
519
520 (* cut & paste from above *)
521 let rec dangerous_conv arities showstoppers =
522  function
523     `N _
524   | `Var _
525   | `Lam _ -> []
526   | `Match(t,liftno,bs,args) ->
527       (* CSC: XXX partial dependency on the encoding *)
528       (match t with
529           `N _ -> concat_map (dangerous_conv arities showstoppers) args
530         | `Match _ as t -> dangerous_conv arities showstoppers t @ concat_map (dangerous_conv arities showstoppers) args
531         | `Var x -> dangerous_inert_conv arities showstoppers x args 2 (* 2 coming from Scott's encoding *)
532         | `I(x,args') -> dangerous_inert_conv arities showstoppers x (Listx.to_list args' @ args) 2 (* 2 coming from Scott's encoding *)
533       )
534   | `I(k,args) -> dangerous_inert_conv arities showstoppers k (Listx.to_list args) 0
535
536 and dangerous_inert_conv arities showstoppers k args more_args =
537  concat_map (dangerous_conv arities showstoppers) args @
538  if List.mem k showstoppers then k :: concat_map free_vars args else
539  try
540   let arity = arity_of arities k in
541   prerr_endline ("dangerous_inert_conv: ar=" ^ string_of_int arity ^ " k="^string_of_var k ^ " listlenargs=" ^ (string_of_int (List.length args)) );
542   if List.length args + more_args > arity then k :: concat_map free_vars args else []
543  with
544   Not_found -> []
545
546 (* inefficient algorithm *)
547 let rec edible arities div ps conv showstoppers =
548  let rec aux showstoppers =
549   function
550      [] -> showstoppers
551    | x::xs when List.exists (fun y -> hd_of x = Some y) showstoppers ->
552       (* se la testa di x e' uno show-stopper *)
553       let new_showstoppers = sort_uniq (showstoppers @ free_vars (x :> nf)) in
554       (* aggiungi tutte le variabili libere di x *)
555       if List.length showstoppers <> List.length new_showstoppers then
556        aux new_showstoppers ps
557       else
558        aux showstoppers xs
559    | x::xs ->
560       match hd_of x with
561          None -> aux showstoppers xs
562        | Some h ->
563           try
564            dangerous arities showstoppers (x : i_n_var :> nf) ;
565            aux showstoppers xs
566           with
567            Dangerous ->
568             aux (sort_uniq (h::showstoppers)) ps
569   in
570     let showstoppers = sort_uniq (aux showstoppers ps) in
571     let dangerous_conv =
572      List.map (dangerous_conv arities showstoppers) (conv :> nf list) in
573
574     prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
575     List.iter (fun l -> prerr_endline (String.concat " " (List.map string_of_var l))) dangerous_conv;
576     let showstoppers' = showstoppers @ List.concat dangerous_conv in
577     let showstoppers' = sort_uniq (match div with
578      | None -> showstoppers'
579      | Some div ->
580        if List.exists ((=) (hd_of_i_var div)) showstoppers'
581        then showstoppers' @ free_vars (div :> nf) else showstoppers') in
582     if showstoppers <> showstoppers' then edible arities div ps conv showstoppers' else showstoppers', dangerous_conv
583 ;;
584
585 let precompute_edible_data {ps; div} xs =
586  (match div with None -> [] | Some div -> [hd_of_i_var div, -1, (div :> i_n_var)]) @
587   List.map (fun hd ->
588    let i, tm = Util.findi (fun y -> hd_of y = Some hd) ps in
589     hd, i, tm
590    ) xs
591 ;;
592
593 let critical_showstoppers p =
594   let p = super_simplify p in
595   let hd_of_div = match p.div with None -> [] | Some t -> [hd_of_i_var t] in
596   let showstoppers_step =
597   concat_map (fun bs ->
598     let heads = List.map (fun (i,_) -> List.nth p.ps i) !bs in
599     let heads = List.sort compare (hd_of_div @ filter_map hd_of heads) in
600     snd (split_duplicates heads)
601     ) p.deltas @
602      if List.exists (fun t -> [hd_of t] = List.map (fun x -> Some x) hd_of_div) p.conv
603      then hd_of_div else [] in
604   let showstoppers_step = sort_uniq showstoppers_step in
605   let showstoppers_eat =
606    let heads_and_arities =
607     List.sort (fun (k,_) (h,_) -> compare k h)
608      (filter_map (function `Var k -> Some (k,0) | `I(k,args) -> Some (k,Listx.length args) | _ -> None ) p.ps) in
609    let rec multiple_arities =
610     function
611        []
612      | [_] -> []
613      | (x,i)::(y,j)::tl when x = y && i <> j ->
614          x::multiple_arities tl
615      | _::tl -> multiple_arities tl in
616    multiple_arities heads_and_arities in
617
618   let showstoppers_eat = sort_uniq showstoppers_eat in
619   let showstoppers_eat = List.filter
620     (fun x -> not (List.mem x showstoppers_step))
621     showstoppers_eat in
622   List.iter (fun v -> prerr_endline ("DANGEROUS STEP: " ^ string_of_var v)) showstoppers_step;
623   List.iter (fun v -> prerr_endline ("DANGEROUS EAT: " ^ string_of_var v)) showstoppers_eat;
624   p, showstoppers_step, showstoppers_eat
625   ;;
626
627 let eat p =
628   let ({ps} as p), showstoppers_step, showstoppers_eat = critical_showstoppers p in
629   let showstoppers = showstoppers_step @ showstoppers_eat in
630   let heads = List.sort compare (filter_map hd_of ps) in
631   let arities = precompute_edible_data p (uniq heads) in
632   let showstoppers, showstoppers_conv =
633    edible arities p.div ps p.conv showstoppers in
634   let l = List.filter (fun (x,_,_) -> not (List.mem x showstoppers)) arities in
635   let p =
636   List.fold_left (fun p (x,pos,(xx : i_n_var)) -> if pos = -1 then p else
637    let n = match xx with `I(_,args) -> Listx.length args | _ -> 0 in
638    let v = `N(pos) in
639    let inst = make_lams v n in
640 (let l = Array.to_list (Array.init (p.freshno + 1) string_of_var) in
641 prerr_endline ("# INST_IN_EAT: " ^ string_of_var x ^ " := " ^ print ~l inst));
642    { p with sigma = p.sigma @ [x,inst] }
643    ) p l in
644   (* to avoid applied numbers in safe positions that
645      trigger assert failures subst_in_problem x inst p*)
646  let ps =
647   List.map (fun t ->
648    try
649     let _,j,_ = List.find (fun (h,_,_) -> hd_of t = Some h) l in
650     `N j
651    with Not_found -> t
652   ) ps in
653  let p = match p.div with
654   | None -> p
655   | Some div ->
656    if List.mem (hd_of_i_var div) showstoppers
657    then p
658    else
659     let n = match div with `I(_,args) -> Listx.length args | `Var _ -> 0 in
660     let p, bomb' = make_fresh_var p in
661     (if !bomb <> `Var (-1) then
662      failwithProblem p
663       ("Bomb was duplicated! It was " ^ string_of_nf p !bomb ^
664        ", tried to change it to " ^ string_of_nf p bomb'));
665     bomb := bomb';
666     prerr_endline ("Just created bomb var: " ^ string_of_nf p !bomb);
667     let x = hd_of_i_var div in
668     let inst = make_lams !bomb n in
669     prerr_endline ("# INST (div): " ^ string_of_var x ^ " := " ^ string_of_nf p inst);
670     let p = {p with div=None} in
671     (* subst_in_problem (hd_of_i_var div) inst p in *)
672      {p with sigma=p.sigma@[x,inst]} in
673      let dangerous_conv = showstoppers_conv in
674 let _ = prerr_endline ("dangerous_conv lenght:" ^ string_of_int (List.length dangerous_conv));
675 List.iter (fun l -> prerr_endline (String.concat " " (List.map string_of_var l))) dangerous_conv; in
676  let conv =
677    List.map (function s,t ->
678     try
679      if s <> [] then t else (
680      (match t with | `Var _ -> raise Not_found | _ -> ());
681      let _ = List.find (fun h -> hd_of t = Some h) showstoppers in
682       t)
683     with Not_found -> match hd_of t with
684      | None -> assert (t = `N ~-1); t
685      | Some h ->
686       prerr_endline ("FREEZING " ^ string_of_var h);
687       `N ~-1 (* convergent dummy*)
688    ) (List.combine showstoppers_conv p.conv) in
689  List.iter
690   (fun bs ->
691     bs :=
692      List.map
693       (fun (n,t as res) ->
694         match List.nth ps n with
695            `N m -> m,t
696          | _ -> res
697       ) !bs
698   ) p.deltas ;
699  let old_conv = p.conv in
700  let p = { p with ps; conv } in
701  if l <> [] || old_conv <> conv
702   then print_endline (print_problem "eat" p);
703  if List.for_all (function `N _ -> true | _ -> false) ps && p.div = None then
704   `Finished p
705  else
706   `Continue p
707
708 let instantiate p x n =
709  (if `Var x = !bomb
710    then failwithProblem p ("BOMB (" ^ string_of_nf p !bomb ^ ") cannot be instantiated!"));
711  prerr_endline ("stepping on " ^ string_of_var x);
712  (if List.nth p.arities x <= 0 then failwith "stepped on a varible of arity <= 0");
713  let p,vars = make_fresh_vars p n in
714  let p,zero' = make_fresh_var p in
715  let zero = Listx.Nil zero' in
716  let args = if n = 0 then zero else Listx.append zero (Listx.from_list vars) in
717  let bs = ref [] in
718  let inst = `Lam(false,`Match(`I(0,Listx.map (lift 1) args),1,bs,[])) in
719  let p = {p with deltas=bs::p.deltas} in
720  let p = ACMeasure.fix_arities p x (List.map (function `Var x -> x | _ -> assert false) (Listx.to_list args)) in
721  let p = subst_in_problem x inst p in
722  p
723 ;;
724
725 let auto_instantiate (n,p) =
726   let p, showstoppers_step, showstoppers_eat = critical_showstoppers p in
727  let x =
728   match showstoppers_step, showstoppers_eat with
729     | [], y::_ ->
730       prerr_endline ("INSTANTIATING CRITICAL TO EAT " ^ string_of_var y); y
731     | [], [] ->
732      let heads = List.sort compare (filter_map (fun t -> match t with `Var _ -> None | x -> hd_of x) ((match p.div with Some t -> [(t :> i_n_var)] | _ -> []) @ p.ps)) in
733      (match heads with
734          [] -> assert false
735        | x::_ ->
736           prerr_endline ("INSTANTIATING TO EAT " ^ string_of_var x);
737           x)
738   | x::_, _ ->
739       prerr_endline ("INSTANTIATING " ^ string_of_var x);
740       x in
741 (* Strategy that decreases the special_k to 0 first (round robin)
742 1:11m42 2:14m5 3:11m16s 4:14m46s 5:12m7s 6:6m31s *)
743 let x =
744  try
745   match hd_of (List.find (fun t -> compute_special_k (Listx.Nil (t :> nf)) > 0) (all_terms p)) with
746       None -> assert false
747     | Some x ->
748        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var x);
749        x
750  with
751   Not_found -> x
752 in
753 (* Instantiate in decreasing order of compute_special_k
754 1:15m14s 2:13m14s 3:4m55s 4:4m43s 5:4m34s 6:6m28s 7:3m31s
755 let x =
756  try
757   (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
758       None -> assert false
759     | Some x ->
760        prerr_endline ("INSTANTIATING AND HOPING " ^ string_of_var x);
761        x)
762  with
763   Not_found -> x
764 in*)
765  let special_k =
766      compute_special_k (Listx.from_list (all_terms p :> nf list) )in
767  if special_k < n then
768   prerr_endline ("@@@@ NEW INSTANTIATE PHASE (" ^ string_of_int special_k ^ ") @@@@");
769  let p = instantiate p x special_k in
770  special_k,p
771
772
773 let rec auto_eat (n,({ps} as p)) =
774  prerr_endline "{{{{{{{{ Computing measure before auto_instantiate }}}}}}";
775  let p = ACMeasure.fix_arities p (-1) [] in
776  let m = problem_measure p in
777  let (n,p') = auto_instantiate (n,p) in
778  match eat p' with
779    `Finished p -> p
780  | `Continue p ->
781      prerr_endline "{{{{{{{{ Computing measure inafter auto_instantiate }}}}}}";
782      let p = ACMeasure.fix_arities p (-1) [] in
783      let delta = m - problem_measure p in
784      if delta <= 0 then (
785       (* failwithProblem p *)
786       prerr_endline
787       ("Measure did not decrease (delta=" ^ string_of_int delta ^ ")"))
788      else prerr_endline ("$ Measure decreased by " ^ string_of_int delta);
789      (* let p' = {p' with steps=(p'.steps - 1)} in *)
790      (* (if p'.steps < 0 then prerr_endline ">>>>>>>>>> STEPS ARE OVER <<<<<<<<<"
791      (*failwithProblem p' "steps are over. sorry."*) ); *)
792      auto_eat (n,p)
793 ;;
794
795 let auto p n =
796  prerr_endline ("@@@@ FIRST INSTANTIATE PHASE (" ^ string_of_int n ^ ") @@@@");
797  match eat p with
798    `Finished p -> p
799  | `Continue p -> auto_eat (n,p)
800 ;;
801
802 (*
803 0 = snd
804
805       x y = y 0    a y = k  k z = z 0  c y = k   y u = u h1 h2 0          h2 a = h3
806 1 x a c    1 a 0 c  1 k c    1 c 0      1 k        1 k                     1 k
807 2 x a y    2 a 0 y  2 k y    2 y 0      2 y 0      2 h2 0                  2 h3
808 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)
809 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
810 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
811 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
812
813                                 l2 _ = l3
814 b u = u l1 l2 0                 e _ _ _ _ = f                         l3 n = n j 0
815 1 k                             1 k                                  1 k
816 2 h3                            2 h3                                 2 h3
817 3 l2 0 (\u. u h1 (\w. h3) 0)    3 l3 (\u. u h1 (\w. h3) 0)           3 j h1 (\w. h3) 0 0
818 4 l2 0 c                        4 l3 c                               4 c j 0
819 5 e l1 l2 0 0                   5 f                                  5 f
820 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
821 *)
822
823 (*
824                 x n = n 0 ?
825 x a (b (a c))   a 0 = 1 ? (b (a c))   8
826 x a (b d')      a 0 = 1 ? (b d')      7
827 x b (a c)       b 0 = 1 ? (a c)       4
828 x b (a c')      b 0 = 1 ? (a c')      5
829
830 c = 2
831 c' = 3
832 a 2 = 4  (* a c *)
833 a 3 = 5  (* a c' *)
834 d' = 6
835 b 6 = 7  (* b d' *)
836 b 4 = 8  (* b (a c) *)
837 b 0 = 1
838 a 0 = 1
839 *)
840
841 (************** Tests ************************)
842
843 let optimize_numerals p =
844   let replace_in_sigma perm =
845     let rec aux = function
846     | `N n -> `N (List.nth perm n)
847     | `I _ -> assert false
848     | `Var _ as t -> t
849     | `Lam(v,t) -> `Lam(v, aux t)
850     | `Match(_,_,bs,_) as t -> (bs := List.map (fun (n,t) -> (List.nth perm n, t)) !bs); t
851     in List.map (fun (n,t) -> (n,aux t))
852   in
853   let deltas' = List.mapi (fun n d -> (n, List.map fst !d)) p.deltas in
854   let maxs = Array.to_list (Array.init (List.length deltas') (fun _ -> 0)) in
855   let max = List.fold_left max 0 (concat_map snd deltas') in
856   let perm,_ = List.fold_left (fun (perm, maxs) (curr_n:int) ->
857       let containing = filter_map (fun (i, bs) -> if List.mem curr_n bs then Some i else None) deltas' in
858       (* (prerr_endline (string_of_int curr_n ^ " occurs in: " ^ (String.concat " " (List.map string_of_int containing)))); *)
859       let neww = List.fold_left Pervasives.max 0 (List.mapi (fun n max -> if List.mem n containing then max else 0) maxs) in
860       let maxs = List.mapi (fun i m -> if List.mem i containing then neww+1 else m) maxs in
861       (neww::perm, maxs)
862     ) ([],maxs) (Array.to_list (Array.init (max+1) (fun x -> x))) in
863   replace_in_sigma (List.rev perm) p.sigma
864 ;;
865
866 let env_of_sigma freshno sigma should_explode =
867  let rec aux n =
868   if n > freshno then
869    []
870   else
871    let e = aux (n+1) in
872    (try
873     e,Pure.lift (-n-1) (snd (List.find (fun (i,_) -> i = n) sigma)),[]
874    with
875     Not_found ->
876      if should_explode && `Var n = !bomb
877       then ([], (let f t = Pure.A(t,t) in f (Pure.L (f (Pure.V 0)))), [])
878       else ([],Pure.V n,[]))::e
879  in aux 0
880 ;;
881
882 prerr_endline "########## main ##########";;
883
884 (* Commands:
885     v ==> v := \a. a k1 .. kn \^m.0
886     + ==> v := \^k. numero  for every v such that ...
887     * ==> tries v as long as possible and then +v as long as possible
888 *)
889 let main problems =
890  let rec aux ({ps} as p) n l =
891   if List.for_all (function `N _ -> true | _ -> false) ps && p.div = None then begin
892    p
893   end else
894    let _ = print_endline (print_problem "main" p) in
895    let x,l =
896     match l with
897      | cmd::l -> cmd,l
898      | [] -> read_line (),[] in
899    let cmd =
900     if x = "+" then
901      `DoneWith
902     else if x = "*" then
903      `Auto
904     else
905      `Step x in
906    match cmd with
907     | `DoneWith -> assert false (*aux (eat p) n l*) (* CSC: TODO *)
908     | `Step x ->
909         let x = var_of_string x in
910         aux (instantiate p x n) n l
911     | `Auto -> aux (auto p n) n l
912  in
913   List.iter
914    (fun (p,n,cmds) ->
915     Console.print_hline();
916     bomb := `Var (-1);
917     let p_finale = aux p n cmds in
918     let freshno,sigma = p_finale.freshno, p_finale.sigma in
919     prerr_endline ("------- <DONE> ------\n "
920     (* ^ (string_of_int (p.steps - (List.length p_finale.sigma))) ^ " steps of "^ (string_of_int p.steps) ^"." *)
921     );
922     (* print_endline (print_problem "Original problem" p); *)
923     prerr_endline "---------------------";
924     let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
925     prerr_endline (" BOMB == " ^ print ~l !bomb);
926     prerr_endline "---------------------";
927     List.iter (fun (x,inst) -> prerr_endline (string_of_var x ^ " := " ^ print ~l inst)) sigma;
928 (*
929      prerr_endline "----------------------";
930      let ps =
931       List.fold_left (fun ps (x,inst) ->
932        (* CSC: XXXX Is the subst always sorted correctly? Otherwise, implement a recursive subst *)
933        (* In this non-recursive version, the intermediate states may containt Matchs *)
934        List.map (fun t -> let t = subst false x inst (t :> nf) in cast_to_i_num_var t) ps)
935        (p.ps :> i_num_var list) sigma in
936      print_endline (print_problem {p with ps= List.map (function t -> cast_to_i_n_var t) ps; freshno});
937      List.iteri (fun i (n,more_args) -> assert (more_args = 0 && n = `N i)) ps ;
938 *)
939     prerr_endline "---------<OPT>----------";
940     let sigma = optimize_numerals p_finale in (* optimize numerals *)
941     let l = Array.to_list (Array.init (freshno + 1) string_of_var) in
942     List.iter (fun (x,inst) -> prerr_endline (string_of_var x ^ " := " ^ print ~l inst)) sigma;
943     prerr_endline "---------<PURE>---------";
944     let div = option_map (fun div -> ToScott.t_of_nf (div :> nf)) p.div in
945     let conv = List.map (fun t -> ToScott.t_of_nf (t :> nf)) p.conv in
946     let ps = List.map (fun t -> ToScott.t_of_nf (t :> nf)) p.ps in
947     let sigma = List.map (fun (x,inst) -> x, ToScott.t_of_nf inst) sigma in
948     (*let ps_ok = List.fold_left (fun ps (x,inst) ->
949       List.map (Pure.subst false x inst) ps) ps sigma in*)
950     let e = env_of_sigma freshno sigma true in
951     let e' = env_of_sigma freshno sigma false in
952
953 (*
954      prerr_endline "---------<PPP>---------";
955 let rec print_e e =
956  "[" ^ String.concat ";" (List.map (fun (e,t,[]) -> print_e e ^ ":" ^ Pure.print t) e) ^ "]"
957 in
958      prerr_endline (print_e e);
959      List.iter (fun (t,t_ok) ->
960       prerr_endline ("T0= " ^ Pure.print t ^ "\nTM= " ^ Pure.print (Pure.unwind (e,t,[])) ^ "\nOM= " ^ Pure.print t_ok);
961       (*assert (Pure.unwind (e,t,[]) = t_ok)*)
962      ) (List.combine ps ps_ok);
963 *)
964      prerr_endline "--------<REDUCE>---------";
965      (function Some div ->
966       print_endline (Pure.print div);
967       let t = Pure.mwhd (e',div,[]) in
968       prerr_endline ("*:: " ^ (Pure.print t));
969       prerr_endline (print !bomb);
970       assert (t = ToScott.t_of_nf (!bomb:>nf))
971      | None -> ()) div;
972      List.iter (fun n ->
973        prerr_endline ("_::: " ^ (Pure.print n));
974        let t = Pure.mwhd (e,n,[]) in
975        prerr_endline ("_:: " ^ (Pure.print t))
976      ) conv ;
977      List.iteri (fun i n ->
978        prerr_endline ((string_of_int i) ^ "::: " ^ (Pure.print n));
979        let t = Pure.mwhd (e,n,[]) in
980        prerr_endline ((string_of_int i) ^ ":: " ^ (Pure.print t));
981        assert (t = Scott.mk_n i)
982      ) ps ;
983      prerr_endline "-------- </DONE> --------"
984    ) problems
985
986 (********************** problems *******************)
987
988 let zero = `Var 0;;
989
990 let append_zero =
991  function
992   | `I _
993   | `Var _ as i ->  cast_to_i_n_var (mk_app i zero)
994   | _ -> assert false
995 ;;
996
997
998 type t = problem * int * string list;;
999
1000 let magic_conv ~div ~conv ~nums cmds =
1001  let all_tms = (match div with None -> [] | Some div -> [div]) @ nums @ conv in
1002   let all_tms, var_names = parse' all_tms in
1003   let div, (tms, conv) = match div with
1004     | None -> None, list_cut (List.length nums, all_tms)
1005     | Some _ -> Some (List.hd all_tms), list_cut (List.length nums, List.tl all_tms) in
1006
1007  if match div with None -> false | Some div -> List.exists (eta_subterm div) (tms@conv)
1008  then (
1009   prerr_endline "--- TEST SKIPPED ---";
1010   {freshno=0; div=None; conv=[]; ps=[]; sigma=[]; deltas=[]; arities=[]; special_k=(-1);}, 0, []
1011  ) else
1012   let tms = sort_uniq ~compare:eta_compare tms in
1013   let special_k = compute_special_k (Listx.from_list all_tms) in (* compute initial special K *)
1014   (* casts *)
1015   let div = option_map cast_to_i_var div in
1016   let conv = List.map cast_to_i_n_var conv in
1017   let tms = List.map cast_to_i_n_var tms in
1018
1019   let ps = List.map append_zero tms in (* crea lista applicando zeri o dummies *)
1020   let freshno = List.length var_names in
1021   let sigma = [] in
1022   let deltas =
1023    let dummy = `Var (max_int / 2) in
1024    [ ref (Array.to_list (Array.init (List.length ps) (fun i -> i, dummy))) ] in
1025   let p = {freshno; div; conv; ps; sigma; deltas; special_k; arities=[]} in
1026   let arities =
1027   List.mapi (fun i () -> ACMeasure.map_max (ACMeasure.get_arity_of_var p i) ((all_terms p) :> nf list)) (Array.to_list (Array.make (freshno+1) ())) in
1028   let p = {p with arities} in
1029   p, special_k, cmds
1030 ;;
1031
1032 let magic strings cmds = magic_conv None [] strings cmds;;