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