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