]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/metadataQuery.ml
beginning of the tactics lapply and fwd
[helm.git] / helm / ocaml / tactics / metadataQuery.ml
1 (* Copyright (C) 2004, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 open Printf
27
28 module Constr = MetadataConstraints
29 module PET = ProofEngineTypes 
30
31 let debug_print = fun _ -> ()
32
33   (** maps a shell like pattern (which uses '*' and '?') to a sql pattern for
34   * the "like" operator (which uses '%' and '_'). Does not support escaping. *)
35 let sqlpat_of_shellglob =
36   let star_RE, qmark_RE, percent_RE, uscore_RE =
37     Pcre.regexp "\\*", Pcre.regexp "\\?", Pcre.regexp "%", Pcre.regexp "_"
38   in
39   fun shellglob ->
40     Pcre.replace ~rex:star_RE ~templ:"%"
41       (Pcre.replace ~rex:qmark_RE ~templ:"_"
42         (Pcre.replace ~rex:percent_RE ~templ:"\\%"
43           (Pcre.replace ~rex:uscore_RE ~templ:"\\_"
44             shellglob)))
45
46 let nonvar s =
47   let len = String.length s in
48   let suffix = String.sub s (len-4) 4 in
49   not (suffix  = ".var")
50
51 let locate ~(dbd:Mysql.dbd) ?(vars = false) pat =
52   let sql_pat = sqlpat_of_shellglob pat in
53   let query =
54         sprintf ("SELECT source FROM %s WHERE value LIKE \"%s\" UNION "^^
55                  "SELECT source FROM %s WHERE value LIKE \"%s\"")
56           (MetadataTypes.name_tbl ()) sql_pat
57            MetadataTypes.library_name_tbl sql_pat
58   in
59   let result = Mysql.exec dbd query in
60   List.filter nonvar
61     (Mysql.map result
62       (fun cols -> match cols.(0) with Some s -> s | _ -> assert false))
63
64 let match_term ~(dbd:Mysql.dbd) ty =
65 (*   debug_print (CicPp.ppterm ty); *)
66   let metadata = MetadataExtractor.compute ~body:None ~ty in
67   let constants_no =
68     MetadataConstraints.StringSet.cardinal (MetadataConstraints.constants_of ty)
69   in
70   let full_card, diff =
71     if CicUtil.is_meta_closed ty then
72       Some (MetadataConstraints.Eq constants_no), None
73     else
74       let diff_no =
75         let (hyp_constants, concl_constants) =
76           (* collect different constants in hypotheses and conclusions *)
77           List.fold_left
78             (fun ((hyp, concl) as acc) metadata ->
79                match (metadata: MetadataTypes.metadata) with
80                | `Sort _ | `Rel _ -> acc
81                | `Obj (uri, `InConclusion) | `Obj (uri, `MainConclusion _)
82                  when not (List.mem uri concl) -> (hyp, uri :: concl)
83                | `Obj (uri, `InHypothesis) | `Obj (uri, `MainHypothesis _)
84                  when not (List.mem uri hyp) -> (uri :: hyp, concl)
85                | `Obj _ -> acc)
86             ([], [])
87             metadata
88         in
89         List.length hyp_constants - List.length concl_constants
90       in
91       let (concl_metas, hyp_metas) = MetadataExtractor.compute_metas ty in
92       let diff =
93         if MetadataExtractor.IntSet.equal concl_metas hyp_metas then
94           Some (MetadataConstraints.Eq diff_no)
95         else if MetadataExtractor.IntSet.subset concl_metas hyp_metas then
96           Some (MetadataConstraints.Gt (diff_no - 1))
97         else if MetadataExtractor.IntSet.subset hyp_metas concl_metas then
98           Some (MetadataConstraints.Lt (diff_no + 1))
99         else
100           None
101       in
102       None, diff
103   in
104   let constraints = List.map MetadataTypes.constr_of_metadata metadata in
105     Constr.at_least ~dbd ?full_card ?diff constraints
106
107 let ( ** ) x y = int_of_float ((float_of_int x) ** (float_of_int y))
108
109 let signature_of_hypothesis context =
110   List.fold_left
111     (fun set hyp ->
112       match hyp with
113       | None -> set
114       | Some (_, Cic.Decl t)
115       | Some (_, Cic.Def (t, _)) ->
116           Constr.StringSet.union set (Constr.constants_of t))
117     Constr.StringSet.empty context
118
119 let intersect uris siguris =
120   let set1 = List.fold_right Constr.StringSet.add uris Constr.StringSet.empty in
121   let set2 =
122     List.fold_right Constr.StringSet.add siguris Constr.StringSet.empty
123   in
124   let inter = Constr.StringSet.inter set1 set2 in
125   List.filter (fun s -> Constr.StringSet.mem s inter) uris
126
127 let filter_uris_forward ~dbd (main, constants) uris =
128   let main_uris =
129     match main with
130     | None -> []
131     | Some (main, types) -> main :: types
132   in
133   let full_signature =
134     List.fold_right Constr.StringSet.add main_uris constants
135   in
136   List.filter (Constr.at_most ~dbd ~where:`Statement full_signature) uris
137
138 let filter_uris_backward ~dbd ~facts signature uris =
139   let siguris =
140     List.map snd 
141       (MetadataConstraints.sigmatch ~dbd ~facts ~where:`Statement signature)
142   in
143     intersect uris siguris 
144
145 let compare_goal_list proof goal1 goal2 =
146   let _,metasenv,_,_ = proof in
147   let (_, ey1, ty1) = CicUtil.lookup_meta goal1 metasenv in
148   let (_, ey2, ty2) =  CicUtil.lookup_meta goal2 metasenv in
149   let ty_sort1,_ = 
150     CicTypeChecker.type_of_aux' metasenv ey1 ty1 CicUniv.empty_ugraph 
151   in
152   let ty_sort2,_ = 
153     CicTypeChecker.type_of_aux' metasenv ey2 ty2 CicUniv.empty_ugraph 
154   in
155   let prop1 =
156     let b,_ = 
157       CicReduction.are_convertible 
158         ey1 (Cic.Sort Cic.Prop) ty_sort1 CicUniv.empty_ugraph 
159     in
160       if b then 0
161       else 1
162   in
163   let prop2 =
164     let b,_ = 
165       CicReduction.are_convertible 
166         ey2 (Cic.Sort Cic.Prop) ty_sort2 CicUniv.empty_ugraph 
167     in 
168       if b then 0
169       else 1
170   in
171   prop1 - prop2
172
173 let hint ~(dbd:Mysql.dbd) ?(facts=false) ?signature ((proof, goal) as status) =
174   let (_, metasenv, _, _) = proof in
175   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
176   let (uris, (main, sig_constants)) =
177     match signature with
178     | Some signature -> (Constr.sigmatch ~dbd ~facts signature, signature)
179     | None -> (Constr.cmatch' ~dbd ~facts ty, Constr.signature_of ty)
180   in
181   let uris = List.filter nonvar (List.map snd uris) in
182   let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
183   let types_constants =
184     match main with
185     | None -> Constr.StringSet.empty
186     | Some (main, types) ->
187         List.fold_right Constr.StringSet.add (main :: types)
188           Constr.StringSet.empty
189   in
190   let hyp_constants =
191     Constr.StringSet.diff (signature_of_hypothesis context) types_constants
192   in
193 (* Constr.StringSet.iter debug_print hyp_constants; *)
194   let other_constants = Constr.StringSet.union sig_constants hyp_constants in
195   let uris = 
196     let pow = 2 ** (Constr.StringSet.cardinal other_constants) in
197     if ((List.length uris < pow) or (pow <= 0))
198     then begin
199 (*       debug_print "MetadataQuery: large sig, falling back to old method"; *)
200       filter_uris_forward ~dbd (main, other_constants) uris
201     end else
202       filter_uris_backward ~dbd ~facts (main, other_constants) uris
203   in
204   let rec aux = function
205     | [] -> []
206     | uri :: tl ->
207         (let status' =
208             try
209               let (proof, goal_list) =
210 (*                debug_print ("STO APPLICANDO " ^ uri); *)
211                 PET.apply_tactic
212                   (PrimitiveTactics.apply_tac
213                     ~term:(CicUtil.term_of_uri uri))
214                   status
215               in
216               let goal_list =
217                 List.stable_sort (compare_goal_list proof) goal_list
218               in
219               Some (uri, (proof, goal_list))
220             with ProofEngineTypes.Fail _ -> None
221           in
222           match status' with
223           | None -> aux tl
224           | Some status' ->
225               status' :: aux tl)
226   in
227   List.stable_sort
228     (fun (_, (_, goals1)) (_, (_, goals2)) ->
229       Pervasives.compare (List.length goals1) (List.length goals2))
230     (aux uris)
231
232 (* experimental_hint is a version of hint for experimental 
233     purposes. It uses auto_tac_verbose instead of auto tac.
234     Auto_tac verbose also returns a substitution - for the moment 
235     as a function from cic to cic, to be changed into an association
236     list in the future -. This substitution is used to build a
237     hash table of the inspected goals with their associated proofs.
238     The cose is a cut and paste of the previous one: at the end 
239     of the experimentation we shall make a choice. *)
240
241 let close_with_types s metasenv context =
242   Constr.StringSet.fold 
243     (fun e bag -> 
244       let t = CicUtil.term_of_uri e in
245       let ty, _ = 
246         CicTypeChecker.type_of_aux' metasenv context t CicUniv.empty_ugraph  
247       in
248       Constr.StringSet.union bag (Constr.constants_of ty)) 
249     s s
250
251 let experimental_hint 
252   ~(dbd:Mysql.dbd) ?(facts=false) ?signature ((proof, goal) as status) =
253   let (_, metasenv, _, _) = proof in
254   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
255   let (uris, (main, sig_constants)) =
256     match signature with
257     | Some signature -> 
258         (Constr.sigmatch ~dbd ~facts signature, signature)
259     | None -> 
260         (Constr.cmatch' ~dbd ~facts ty, Constr.signature_of ty)
261   in 
262   let uris = List.filter nonvar (List.map snd uris) in
263   let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
264   let types_constants =
265     match main with
266     | None -> Constr.StringSet.empty
267     | Some (main, types) ->
268         List.fold_right Constr.StringSet.add (main :: types)
269           Constr.StringSet.empty
270   in
271   let all_constants =
272     let hyp_and_sug =
273       Constr.StringSet.union
274         (signature_of_hypothesis context) 
275         sig_constants
276     in
277     let main = 
278       match main with
279       | None -> Constr.StringSet.empty
280       | Some (main,_) -> 
281           let ty, _ = 
282             CicTypeChecker.type_of_aux' 
283               metasenv context (CicUtil.term_of_uri main) CicUniv.empty_ugraph
284           in
285           Constr.constants_of ty
286     in
287     Constr.StringSet.union main hyp_and_sug
288   in
289 (* Constr.StringSet.iter debug_print hyp_constants; *)
290   let all_constants_closed = close_with_types all_constants metasenv context in
291   let other_constants = 
292     Constr.StringSet.diff all_constants_closed types_constants
293   in
294   debug_print "all_constants_closed";
295   Constr.StringSet.iter debug_print all_constants_closed;
296   debug_print "other_constants";
297   Constr.StringSet.iter debug_print other_constants;
298   let uris = 
299     let pow = 2 ** (Constr.StringSet.cardinal other_constants) in
300     if ((List.length uris < pow) or (pow <= 0))
301     then begin
302       debug_print "MetadataQuery: large sig, falling back to old method";
303       filter_uris_forward ~dbd (main, other_constants) uris
304     end else
305       filter_uris_backward ~dbd ~facts (main, other_constants) uris
306   in 
307   let rec aux = function
308     | [] -> []
309     | uri :: tl ->
310         (let status' =
311             try
312               let (subst,(proof, goal_list)) =
313                   (* debug_print ("STO APPLICANDO" ^ uri); *)
314                   PrimitiveTactics.apply_tac_verbose 
315                     ~term:(CicUtil.term_of_uri uri)
316                   status
317               in
318               let goal_list =
319                 List.stable_sort (compare_goal_list proof) goal_list
320               in
321               Some (uri, (subst,(proof, goal_list)))
322             with ProofEngineTypes.Fail _ -> None
323           in
324           match status' with
325           | None -> aux tl
326           | Some status' -> status' :: aux tl)
327   in
328   List.stable_sort
329     (fun (_,(_, (_, goals1))) (_,(_, (_, goals2))) ->
330       Pervasives.compare (List.length goals1) (List.length goals2))
331     (aux uris)
332
333 let elim ~dbd uri =
334   let constraints =
335     [`Rel [`MainConclusion None];
336      `Sort (Cic.Prop,[`MainHypothesis (Some (MetadataTypes.Ge 1))]);
337      `Obj (uri,[`MainHypothesis (Some (MetadataTypes.Eq 0))]);
338      `Obj (uri,[`InHypothesis]);
339     ]
340   in
341   MetadataConstraints.at_least ~rating:`Hits ~dbd constraints
342
343
344 let fill_with_dummy_constants t =
345   let rec aux i types =
346     function
347         Cic.Lambda (n,s,t) -> 
348           let dummy_uri = 
349             UriManager.uri_of_string ("cic:/dummy_"^(string_of_int i)) in
350             (aux (i+1) (s::types)
351                (CicSubstitution.subst (Cic.Const(dummy_uri,[])) t))
352       | t -> t,types
353   in 
354   let t,types = aux 0 [] t in
355   t, List.rev types
356       
357 let instance ~dbd t =
358   let t',types = fill_with_dummy_constants t in 
359   let metadata = MetadataExtractor.compute ~body:None ~ty:t' in
360 (*   List.iter 
361     (fun x -> 
362        debug_print 
363          (MetadataPp.pp_constr (MetadataTypes.constr_of_metadata x))) 
364     metadata; *)
365   let no_concl = MetadataDb.count_distinct `Conclusion metadata in
366   let no_hyp = MetadataDb.count_distinct `Hypothesis metadata in
367   let no_full = MetadataDb.count_distinct `Statement metadata in
368   let is_dummy = function
369     | `Obj(s, _) -> (String.sub s 0 10) <> "cic:/dummy" 
370           | _ -> true 
371   in
372   let rec look_for_dummy_main = function
373           | [] -> None
374     | `Obj(s,`MainConclusion (Some (MetadataTypes.Eq d)))::_ 
375       when ((String.sub s 0 10) = "cic:/dummy") -> 
376       let len = String.length s in
377             let dummy_index = int_of_string (String.sub s 11 (len-11)) in
378       let dummy_type = List.nth types dummy_index in
379       Some (d,dummy_type)
380     | _::l -> look_for_dummy_main l 
381   in
382   match (look_for_dummy_main metadata) with
383     | None->
384 (*         debug_print "Caso None"; *)
385         (* no dummy in main position *)
386         let metadata = List.filter is_dummy metadata in
387         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
388         let concl_card = Some (MetadataConstraints.Eq no_concl) in
389         let full_card = Some (MetadataConstraints.Eq no_full) in
390         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
391           Constr.at_least ~dbd ?concl_card ?full_card ?diff constraints
392     | Some (depth, dummy_type) ->
393 (*         debug_print 
394           (sprintf "Caso Some %d %s" depth (CicPp.ppterm dummy_type)); *)
395         (* a dummy in main position *)
396         let metadata_for_dummy_type = 
397           MetadataExtractor.compute ~body:None ~ty:dummy_type in
398         (* Let us skip this for the moment 
399            let main_of_dummy_type = 
400            look_for_dummy_main metadata_for_dummy_type in *)
401         let metadata = List.filter is_dummy metadata in
402         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
403         let metadata_for_dummy_type = 
404           List.filter is_dummy metadata_for_dummy_type in
405         let metadata_for_dummy_type, depth' = 
406           (* depth' = the depth of the A -> A -> Prop *)
407           List.fold_left (fun (acc,dep) c ->
408             match c with
409             | `Sort (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
410                 (`Sort (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
411             | `Obj  (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
412                 (`Obj (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
413             | `Rel  (`MainConclusion (Some (MetadataTypes.Eq i))) -> 
414                 (`Rel (`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
415             | _ -> (c::acc,dep)) ([],0) metadata_for_dummy_type
416         in
417         let constraints_for_dummy_type =
418            List.map MetadataTypes.constr_of_metadata metadata_for_dummy_type in
419         (* start with the dummy constant in main conlusion *)
420         let from = ["refObj as table0"] in
421         let where = 
422           [sprintf "table0.h_position = \"%s\"" MetadataTypes.mainconcl_pos;
423                  sprintf "table0.h_depth >= %d" depth] in
424         let (n,from,where) =
425           List.fold_left 
426             (MetadataConstraints.add_constraint ~start:2)
427             (2,from,where) constraints in
428         let concl_card = Some (MetadataConstraints.Eq no_concl) in
429         let full_card = Some (MetadataConstraints.Eq no_full) in
430         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
431         let (n,from,where) = 
432           MetadataConstraints.add_all_constr 
433             (n,from,where) concl_card full_card diff in
434               (* join with the constraints over the type of the constant *)
435         let where = 
436           (sprintf "table0.h_occurrence = table%d.source" n)::where in
437         let where = 
438           sprintf "table0.h_depth - table%d.h_depth = %d" 
439             n (depth - depth')::where
440         in
441         let (m,from,where) =
442           List.fold_left 
443             (MetadataConstraints.add_constraint ~start:n)
444             (n,from,where) constraints_for_dummy_type in
445         Constr.exec ~dbd (m,from,where)
446
447 (* fwd_simpl ****************************************************************)
448
449 let rec map_filter f n = function
450    | []       -> []
451    | hd :: tl -> 
452       match f n hd with
453          | None    -> map_filter f (succ n) tl
454          | Some hd -> hd :: map_filter f (succ n) tl
455
456 let get_uri t =
457    let aux = function
458       | Cic.Appl (hd :: tl) -> Some (CicUtil.uri_of_term hd, tl)
459       | hd                  -> Some (CicUtil.uri_of_term hd, []) 
460    in
461    try aux t with
462       | Invalid_argument "uri_of_term" -> None
463
464 let get_metadata t =
465    let f n t =
466       match get_uri t with
467          | None          -> None 
468          | Some (uri, _) -> Some (n, uri)
469    in
470    match get_uri t with
471       | None             -> None
472       | Some (uri, args) -> Some (uri, map_filter f 1 args) 
473
474 let debug_metadata = function
475    | None                 -> ()
476    | Some (outer, inners) -> 
477       let f (n, uri) = Printf.eprintf "%s: %i %s\n" "fwd" n uri in
478       Printf.eprintf "\n%s: %s\n" "fwd" outer;
479       List.iter f inners; prerr_newline ()
480
481 let fwd_simpl ~dbd t =
482    let map inners row = 
483       match row.(0), row.(1), row.(2) with  
484          | Some source, Some inner, Some index -> 
485             source, List.mem (int_of_string index, inner) inners
486          | _                                   -> "", false
487    in
488    let rec rank ranks (source, ok) = 
489       match ranks, ok with
490          | [], false                               -> [source, 0]
491          | [], true                                -> [source, 1]
492          | (uri, i) :: tl, false when uri = source -> (uri, 0) :: tl
493          | (uri, 0) :: tl, true when uri = source  -> (uri, 0) :: tl
494          | (uri, i) :: tl, true when uri = source  -> (uri, succ i) :: tl
495          | hd :: tl, _ -> hd :: rank tl (source, ok)
496    in
497    let compare (_, x) (_, y) = compare x y in
498    let filter n (uri, rank) =
499       if rank > 0 then Some uri else None
500    in   
501    match get_metadata t with
502       | None                 -> []
503       | Some (outer, inners) ->
504          let select = "source, h_inner, h_index" in
505          let from = "genLemma" in
506          let where = Printf.sprintf "h_outer = \"%s\"" (Mysql.escape outer) in
507          let query = Printf.sprintf "SELECT %s FROM %s WHERE %s" select from where in
508          let result = Mysql.exec dbd query in
509          let lemmas = Mysql.map result ~f:(map inners) in
510          let ranked = List.fold_left rank [] lemmas in
511          let ordered = List.rev (List.fast_sort compare ranked) in
512          map_filter filter 0 ordered