]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/simple.ml
13400b7f8cb84cb94c36c65daae5bd3a3a0dcf42
[fireball-separation.git] / ocaml / simple.ml
1 let (++) f g x = f (g x);;\r
2 let id x = x;;\r
3 let rec fold_nat f x n = if n = 0 then x else f (fold_nat f x (n-1)) n ;;\r
4 \r
5 let print_hline = Console.print_hline;;\r
6 \r
7 open Pure\r
8 \r
9 type var = int;;\r
10 type t =\r
11  | V of var\r
12  | A of t * t\r
13  | L of (t * t list (*garbage*))\r
14  | C (* constant *)\r
15 ;;\r
16 \r
17 let delta = L(A(V 0, V 0),[]);;\r
18 \r
19 let rec is_stuck = function\r
20  | C -> true\r
21  | A(t,_) -> is_stuck t\r
22  | _ -> false\r
23 ;;\r
24 \r
25 let eta_eq' =\r
26  let rec aux l1 l2 t1 t2 =\r
27   let stuck1, stuck2 = is_stuck t1, is_stuck t2 in\r
28   match t1, t2 with\r
29   | _, _ when not stuck1 && stuck2 -> false\r
30   | _, _ when stuck1 -> true\r
31   | L t1, L t2 -> aux l1 l2 (fst t1) (fst t2)\r
32   | L t1, t2 -> aux l1 (l2+1) (fst t1) t2\r
33   | t1, L t2 -> aux (l1+1) l2 t1 (fst t2)\r
34   | V a, V b -> a + l1 = b + l2\r
35   | A(t1,t2), A(u1,u2) -> aux l1 l2 t1 u1 && aux l1 l2 t2 u2\r
36   | _, _ -> false\r
37  in aux ;;\r
38 let eta_eq = eta_eq' 0 0;;\r
39 \r
40 (* is arg1 eta-subterm of arg2 ? *)\r
41 let eta_subterm u =\r
42  let rec aux lev t = if t = C then false else (eta_eq' lev 0 u t || match t with\r
43  | L(t,g) -> List.exists (aux (lev+1)) (t::g)\r
44  | A(t1, t2) -> aux lev t1 || aux lev t2\r
45  | _ -> false) in\r
46  aux 0\r
47 ;;\r
48 \r
49 (* does NOT lift the argument *)\r
50 let mk_lams = fold_nat (fun x _ -> L(x,[])) ;;\r
51 \r
52 let string_of_t =\r
53   let string_of_bvar =\r
54    let bound_vars = ["x"; "y"; "z"; "w"; "q"] in\r
55    let bvarsno = List.length bound_vars in\r
56    fun nn -> if nn < bvarsno then List.nth bound_vars nn else "x" ^ (string_of_int (nn - bvarsno + 1)) in\r
57   let rec string_of_term_w_pars level = function\r
58     | V v -> if v >= level then "`" ^ string_of_int (v-level) else\r
59        string_of_bvar (level - v-1)\r
60     | C -> "C"\r
61     | A _\r
62     | L _ as t -> "(" ^ string_of_term_no_pars level t ^ ")"\r
63   and string_of_term_no_pars_app level = function\r
64     | A(t1,t2) -> string_of_term_no_pars_app level t1 ^ " " ^ string_of_term_w_pars level t2\r
65     | _ as t -> string_of_term_w_pars level t\r
66   and string_of_term_no_pars level = function\r
67     | L(t,g) -> "λ" ^ string_of_bvar level ^ ". " ^ string_of_term_no_pars (level+1) t\r
68        ^ (if g = [] then "" else String.concat ", " ("" :: List.map (string_of_term_w_pars (level+1)) g))\r
69     | _ as t -> string_of_term_no_pars_app level t\r
70   in string_of_term_no_pars 0\r
71 ;;\r
72 \r
73 type problem = {\r
74    orig_freshno: int\r
75  ; freshno : int\r
76  ; label : string\r
77  ; div : t\r
78  ; conv : t\r
79  ; sigma : (var * t) list (* substitutions *)\r
80 }\r
81 \r
82 let string_of_problem p =\r
83  let lines = [\r
84   "[DV] " ^ string_of_t p.div;\r
85   "[CV] " ^ string_of_t p.conv;\r
86  ] in\r
87  String.concat "\n" lines\r
88 ;;\r
89 \r
90 exception B;;\r
91 exception Done of (var * t) list (* substitution *);;\r
92 exception Unseparable of string;;\r
93 exception Backtrack of string;;\r
94 \r
95 let rec try_all label f = function\r
96  | x::xs -> (try f x with Backtrack _ -> try_all label f xs)\r
97  | [] -> raise (Backtrack label)\r
98 ;;\r
99 \r
100 let problem_fail p reason =\r
101  print_endline "!!!!!!!!!!!!!!! FAIL !!!!!!!!!!!!!!!";\r
102  print_endline (string_of_problem p);\r
103  failwith reason\r
104 ;;\r
105 \r
106 let freshvar ({freshno} as p) =\r
107  {p with freshno=freshno+1}, freshno+1\r
108 ;;\r
109 \r
110 (* CSC: rename? is an applied C an inert?\r
111    is_inert and get_inert work inconsistently *)\r
112 let rec is_inert =\r
113  function\r
114  | A(t,_) -> is_inert t\r
115  | V _ -> true\r
116  | C\r
117  | L _ -> false\r
118 ;;\r
119 \r
120 let rec is_constant =\r
121  function\r
122     C -> true\r
123   | V _ -> false\r
124   | A(t,_)\r
125   | L(t,_) -> is_constant t\r
126 ;;\r
127 \r
128 let rec get_inert = function\r
129  | V _ | C as t -> (t,0)\r
130  | A(t, _) -> let hd,args = get_inert t in hd,args+1\r
131  | _ -> assert false\r
132 ;;\r
133 \r
134 let args_of_inert =\r
135  let rec aux acc =\r
136   function\r
137    | V _ | C -> acc\r
138    | A(t, a) -> aux (a::acc) t\r
139    | _ -> assert false\r
140  in\r
141   aux []\r
142 ;;\r
143 \r
144 (* precomputes the number of leading lambdas in a term,\r
145    after replacing _v_ w/ a term starting with n lambdas *)\r
146 let rec no_leading_lambdas v n = function\r
147  | L(t,_) -> 1 + no_leading_lambdas (v+1) n t\r
148  | A _ as t -> let v', m = get_inert t in if V v = v' then max 0 (n - m) else 0\r
149  | V v' -> if v = v' then n else 0\r
150  | C -> 0\r
151 ;;\r
152 \r
153 let rec subst level delift sub =\r
154  function\r
155  | V v -> (if v = level + fst sub then lift level (snd sub) else V (if delift && v > level then v-1 else v)), []\r
156  | L x -> let t, g = subst_in_lam (level+1) delift sub x in L(t, g), []\r
157  | A (t1,t2) ->\r
158   let t1, g1 = subst level delift sub t1 in\r
159   let t2, g2 = subst level delift sub t2 in\r
160   let t3, g3 = mk_app t1 t2 in\r
161   t3, g1 @ g2 @ g3\r
162  | C -> C, []\r
163 and subst_in_lam level delift sub (t, g) =\r
164   let t', g' = subst level delift sub t in\r
165   let g'' = List.fold_left\r
166    (fun xs t ->\r
167      let x,y = subst level delift sub t in\r
168      (x :: y @ xs)) g' g in t', g''\r
169 and mk_app t1 t2 = if t1 = delta && t2 = delta then raise B\r
170  else match t1 with\r
171  | L x -> subst_in_lam 0 true (0, t2) x\r
172  | _ -> A (t1, t2), []\r
173 and lift n =\r
174  let rec aux lev =\r
175   function\r
176   | V m -> V (if m >= lev then m + n else m)\r
177   | L(t,g) -> L (aux (lev+1) t, List.map (aux (lev+1)) g)\r
178   | A (t1, t2) -> A (aux lev t1, aux lev t2)\r
179   | C -> C\r
180  in aux 0\r
181 ;;\r
182 let subst' = subst;;\r
183 let subst = subst' 0 false;;\r
184 \r
185 let rec mk_apps t = function\r
186  | u::us -> mk_apps (A(t,u)) us\r
187  | [] -> t\r
188 ;;\r
189 \r
190 let subst_in_problem ((v, t) as sub) p =\r
191 print_endline ("-- SUBST " ^ string_of_t (V v) ^ " |-> " ^ string_of_t t);\r
192  let sigma = sub :: p.sigma in\r
193  let div, g = try subst sub p.div with B -> raise (Done sigma) in\r
194  let divs = div :: g in\r
195  let conv, g = try subst sub p.conv with B -> raise (Backtrack "p.conv diverged") in\r
196  let conv = if g = [] then conv else mk_apps C (conv::g) in\r
197  divs, {p with div; conv; sigma}\r
198 ;;\r
199 \r
200 let get_subterms_with_head hd_var =\r
201  let rec aux lev inert_done g = function\r
202  | L(t,g') -> List.fold_left (aux (lev+1) false) g (t::g')\r
203  | C | V _ -> g\r
204  | A(t1,t2) as t ->\r
205    let hd_var', n_args' = get_inert t1 in\r
206    if not inert_done && hd_var' = V (hd_var + lev)\r
207     then lift ~-lev t :: aux lev false (aux lev true g t1) t2\r
208     else                 aux lev false (aux lev true g t1) t2\r
209  in aux 0 false []\r
210 ;;\r
211 \r
212 let purify =\r
213  let rec aux = function\r
214  | L(t,g) ->\r
215     let t = aux (lift (List.length g) t) in\r
216     let t = List.fold_left (fun t g -> Pure.A(Pure.L t, aux g)) t g in\r
217     Pure.L t\r
218  | A (t1,t2) -> Pure.A (aux t1, aux t2)\r
219  | V n -> Pure.V (n)\r
220  | C -> Pure.V (min_int/2)\r
221  in aux\r
222 ;;\r
223 \r
224 let check p sigma =\r
225  print_endline "Checking...";\r
226  let div = purify p.div in\r
227  let conv = purify p.conv in\r
228  let sigma = List.map (fun (v,t) -> v, purify t) sigma in\r
229  let freshno = List.fold_right (max ++ fst) sigma 0 in\r
230  let env = Pure.env_of_sigma freshno sigma in\r
231  (if not (Pure.diverged (Pure.mwhd (env,div,[])))\r
232   then failwith "D converged in Pure");\r
233  print_endline "- D diverged.";\r
234  (if Pure.diverged (Pure.mwhd (env,conv,[]))\r
235   then failwith "C diverged in Pure");\r
236  print_endline "- C converged.";\r
237  ()\r
238 ;;\r
239 \r
240 let sanity p =\r
241  print_endline (string_of_problem p); (* non cancellare *)\r
242  (* Trailing constant args can be removed because do not contribute to eta-diff *)\r
243  let rec remove_trailing_constant_args = function\r
244  | A(t1, t2) when is_constant t2 -> remove_trailing_constant_args t1\r
245  | _ as t -> t in\r
246  let p = {p with div=remove_trailing_constant_args p.div} in\r
247  p\r
248 ;;\r
249 \r
250 (* drops the arguments of t after the n-th *)\r
251 let inert_cut_at n t =\r
252  let rec aux t =\r
253   match t with\r
254   | V _ as t -> 0, t\r
255   | A(t1,_) as t ->\r
256     let k', t' = aux t1 in\r
257      if k' = n then n, t'\r
258       else k'+1, t\r
259   | _ -> assert false\r
260  in snd (aux t)\r
261 ;;\r
262 \r
263 (* return the index of the first argument with a difference\r
264    (the first argument is 0) *)\r
265 let find_eta_difference p t =\r
266  let divargs = args_of_inert p.div in\r
267  let conargs = args_of_inert t in\r
268  let rec range i j =\r
269   if j = -1 then [] else i :: range (i+1) (j-1) in\r
270  let rec aux k divargs conargs =\r
271   match divargs,conargs with\r
272      [],conargs -> range k (List.length conargs)\r
273    | _::_,[] -> [k]\r
274    | t1::divargs,t2::conargs ->\r
275       (if not (eta_eq t1 t2) then [k] else []) @ aux (k+1) divargs conargs\r
276  in\r
277   aux 0 divargs conargs\r
278 ;;\r
279 \r
280 let compute_max_lambdas_at hd_var j =\r
281  let rec aux hd = function\r
282  | A(t1,t2) ->\r
283     (if get_inert t1 = (V hd, j)\r
284       then max ( (*FIXME*)\r
285        if is_inert t2 && let hd', j' = get_inert t2 in hd' = V hd\r
286         then let hd', j' = get_inert t2 in j - j'\r
287         else no_leading_lambdas hd_var j t2)\r
288       else id) (max (aux hd t1) (aux hd t2))\r
289  | L(t,_) -> aux (hd+1) t\r
290  | V _ | C -> 0\r
291  in aux hd_var\r
292 ;;\r
293 \r
294 let print_cmd s1 s2 = print_endline (">> " ^ s1 ^ " " ^ s2);;\r
295 \r
296 (* returns Some i if i is the smallest integer s.t. p holds for the i-th\r
297    element of the list in input *)\r
298 let smallest_such_that p =\r
299  let rec aux i =\r
300   function\r
301      [] -> None\r
302    | hd::_ when (print_endline (string_of_t hd) ; p hd) -> Some i\r
303    | _::tl -> aux (i+1) tl\r
304  in\r
305   aux 0\r
306 ;;\r
307 \r
308 (* step on the head of div, on the k-th argument, with n fresh vars *)\r
309 let step k n p =\r
310  let hd, _ = get_inert p.div in\r
311  match hd with\r
312  | C | L _ | A _  -> assert false\r
313  | V var ->\r
314 print_cmd "STEP" ("on " ^ string_of_t (V var) ^ " (on " ^ string_of_int (k+1) ^ "th)");\r
315  let p, t = (* apply fresh vars *)\r
316   fold_nat (fun (p, t) _ ->\r
317     let p, v = freshvar p in\r
318     p, A(t, V (v + k + 1))\r
319   ) (p, V 0) n in\r
320  let t = (* apply unused bound variables V_{k-1}..V_1 *)\r
321   fold_nat (fun t m -> A(t, V (k-m+1))) t k in\r
322  let t = mk_lams t (k+1) in (* make leading lambdas *)\r
323  let subst = var, t in\r
324  let divs, p = subst_in_problem subst p in\r
325  divs, sanity p\r
326 ;;\r
327 \r
328 let finish p =\r
329  (* one-step version of eat *)\r
330  let compute_max_arity =\r
331    let rec aux n = function\r
332    | A(t1,t2) -> max (aux (n+1) t1) (aux 0 t2)\r
333    | L(t,g) -> List.fold_right (max ++ (aux 0)) (t::g) 0\r
334    | _ -> n\r
335  in aux 0 in\r
336 print_cmd "FINISH" "";\r
337  (* First, a step on the last argument of the divergent.\r
338     Because of the sanity check, it will never be a constant term. *)\r
339  let div_hd, div_nargs = get_inert p.div in\r
340  let div_hd = match div_hd with V n -> n | _ -> assert false in\r
341  let j = div_nargs - 1 in\r
342  let arity = compute_max_arity p.conv in\r
343  let n = 1 + arity + max\r
344   (compute_max_lambdas_at div_hd j p.div)\r
345   (compute_max_lambdas_at div_hd j p.conv) in\r
346  let _, p = step j n p in\r
347  (* Now, find first argument of div that is a variable never applied anywhere.\r
348  It must exist because of some invariant, since we just did a step,\r
349  and because of the arity of the divergent *)\r
350  let div_hd, div_nargs = get_inert p.div in\r
351  let div_hd = match div_hd with V n -> n | _ -> assert false in\r
352  let rec aux m = function\r
353  | A(t, V delta_var) ->\r
354    if delta_var <> div_hd && get_subterms_with_head delta_var p.conv = []\r
355    then m, delta_var\r
356    else aux (m-1) t\r
357  | A(t,_) -> aux (m-1) t\r
358  | _ -> assert false in\r
359  let m, delta_var = aux div_nargs p.div in\r
360  let _, p = subst_in_problem (delta_var, delta) p in\r
361  let _, p = subst_in_problem (div_hd, mk_lams delta (m-1)) p in\r
362  sanity p\r
363 ;;\r
364 \r
365 let auto p =\r
366  let rec aux p =\r
367  match p.div with\r
368  | L(div,g) -> (* case p.div is an abstraction *)\r
369     let f l t = fst (subst' 0 true (0, C) t) :: l in\r
370     (* the `fst' above is because we can ignore the\r
371     garbage generated by the subst, because substituting\r
372     C does not create redexes and thus no new garbage is activated *)\r
373     let tms = List.fold_left f [] (div::g) in\r
374     try_all "auto.L"\r
375      (fun div -> aux {p with div}) tms\r
376  | _ -> (\r
377    if is_constant p.div (* case p.div is rigid inert *)\r
378    then try_all "auto.C"\r
379     (fun div -> aux {p with div}) (args_of_inert p.div)\r
380    else (* case p.div is flexible inert *)\r
381     let hd, n_args = get_inert p.div in\r
382    match hd with\r
383    | C | L _ | A _  -> assert false\r
384    | V hd_var ->\r
385    let tms = get_subterms_with_head hd_var p.conv in\r
386    if List.exists (fun t -> snd (get_inert t) >= n_args) tms\r
387     then (\r
388      (* let tms = List.sort (fun t1 t2 -> - compare (snd (get_inert t1)) (snd (get_inert t2))) tms in *)\r
389      try_all "no similar terms" (fun t ->\r
390       let js = find_eta_difference p t in\r
391       (* print_endline (String.concat ", " (List.map string_of_int js)); *)\r
392       let js = List.rev js in\r
393       try_all "no eta difference"\r
394        (fun j ->\r
395          let k = 1 + max\r
396           (compute_max_lambdas_at hd_var j p.div)\r
397            (compute_max_lambdas_at hd_var j p.conv) in\r
398          let divs, p = step j k p in\r
399          try_all "p.div" (fun div -> aux (sanity {p with div})) divs\r
400          ) js) tms)\r
401     else\r
402       problem_fail (finish p) "Finish did not complete the problem"\r
403  ) in try\r
404   aux p\r
405  with Done sigma -> sigma\r
406 ;;\r
407 \r
408 let problem_of (label, div, convs, ps, var_names) =\r
409  print_hline ();\r
410  let rec aux lev = function\r
411  | `Lam(_, t, g) -> L (aux (lev+1) t, List.map (aux (lev+1)) g)\r
412  | `I (v, args) -> Listx.fold_left (fun x y -> fst (mk_app x (aux lev y))) (aux lev (`Var v)) args\r
413  | `Var(v,_) -> if v >= lev && List.nth var_names (v-lev) = "C" then C else V v\r
414  | `N _ | `Match _ -> assert false in\r
415  assert (List.length ps = 0);\r
416  let convs = List.rev convs in\r
417  let conv = List.fold_left (fun x y -> fst (mk_app x (aux 0 (y :> Num.nf)))) C convs in\r
418  let div = match div with\r
419  | Some div -> aux 0 (div :> Num.nf)\r
420  | None -> assert false in\r
421  let varno = List.length var_names in\r
422  {orig_freshno=varno; freshno=1+varno; div; conv; sigma=[]; label}\r
423 ;;\r
424 \r
425 let solve p =\r
426  let c = if String.length p.label > 0 then String.sub (p.label) 0 1 else "" in\r
427  let module M = struct exception Okay end in\r
428  try\r
429   if eta_subterm p.div p.conv\r
430   then raise (Unseparable "div is subterm of conv")\r
431   else\r
432    let p = sanity p (* initial sanity check *) in\r
433    check p (auto p);\r
434    raise M.Okay\r
435  with\r
436   | M.Okay -> if c = "?" then\r
437     failwith "The problem succeeded, but was supposed to be unseparable"\r
438   | e when c = "!" ->\r
439     failwith ("The problem was supposed to be separable, but: "^Printexc.to_string e)\r
440   | e ->\r
441     print_endline ("The problem failed, as expected ("^Printexc.to_string e^")")\r
442 ;;\r
443 \r
444 Problems.main (solve ++ problem_of);\r
445 \r
446 (* Example usage of interactive: *)\r
447 \r
448 (* let interactive div conv cmds =\r
449  let p = problem_of div conv in\r
450  try (\r
451  let p = List.fold_left (|>) p cmds in\r
452  let rec f p cmds =\r
453   let nth spl n = int_of_string (List.nth spl n) in\r
454   let read_cmd () =\r
455    let s = read_line () in\r
456    let spl = Str.split (Str.regexp " +") s in\r
457    s, let uno = List.hd spl in\r
458     try if uno = "eat" then eat\r
459     else if uno = "step" then step (nth spl 1) (nth spl 2)\r
460     else failwith "Wrong input."\r
461     with Failure s -> print_endline s; (fun x -> x) in\r
462   let str, cmd = read_cmd () in\r
463   let cmds = (" " ^ str ^ ";")::cmds in\r
464   try\r
465    let p = cmd p in f p cmds\r
466   with\r
467   | Done _ -> print_endline "Done! Commands history: "; List.iter print_endline (List.rev cmds)\r
468  in f p []\r
469  ) with Done _ -> ()\r
470 ;; *)\r
471 \r
472 (* interactive "x y"\r
473  "@ (x x) (y x) (y z)" [step 0 1; step 0 2; eat]\r
474 ;; *)\r