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