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