]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/metadataQuery.ml
new signature of auto_tac, with a new optional argument "full", to invoke the
[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 exception Goal_is_not_an_equation
32
33 let debug = false
34 let debug_print s = if debug then prerr_endline (Lazy.force s)
35
36   (** maps a shell like pattern (which uses '*' and '?') to a sql pattern for
37   * the "like" operator (which uses '%' and '_'). Does not support escaping. *)
38 let sqlpat_of_shellglob =
39   let star_RE, qmark_RE, percent_RE, uscore_RE =
40     Pcre.regexp "\\*", Pcre.regexp "\\?", Pcre.regexp "%", Pcre.regexp "_"
41   in
42   fun shellglob ->
43     Pcre.replace ~rex:star_RE ~templ:"%"
44       (Pcre.replace ~rex:qmark_RE ~templ:"_"
45         (Pcre.replace ~rex:percent_RE ~templ:"\\%"
46           (Pcre.replace ~rex:uscore_RE ~templ:"\\_"
47             shellglob)))
48
49 let nonvar uri = not (UriManager.uri_is_var uri)
50
51 let locate ~(dbd:HMysql.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 = HMysql.exec dbd query in
60   List.filter nonvar
61     (HMysql.map result
62       (fun cols -> match cols.(0) with Some s -> UriManager.uri_of_string s | _ -> assert false))
63
64 let match_term ~(dbd:HMysql.dbd) ty =
65 (*   debug_print (lazy (CicPp.ppterm ty)); *)
66   let metadata = MetadataExtractor.compute ~body:None ~ty in
67   let constants_no =
68     MetadataConstraints.UriManagerSet.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.UriManagerSet.union set (Constr.constants_of t))
117     Constr.UriManagerSet.empty context
118
119 let intersect uris siguris =
120   let set1 = List.fold_right Constr.UriManagerSet.add uris Constr.UriManagerSet.empty in
121   let set2 =
122     List.fold_right Constr.UriManagerSet.add siguris Constr.UriManagerSet.empty
123   in
124   let inter = Constr.UriManagerSet.inter set1 set2 in
125   List.filter (fun s -> Constr.UriManagerSet.mem s inter) uris
126
127 (* Profiling code
128 let at_most =
129  let profiler = CicUtil.profile "at_most" in
130  fun ~dbd ~where uri -> profiler.profile (Constr.at_most ~dbd ~where) uri
131
132 let sigmatch =
133  let profiler = CicUtil.profile "sigmatch" in
134  fun ~dbd ~facts ~where signature ->
135   profiler.profile (MetadataConstraints.sigmatch ~dbd ~facts ~where) signature
136 *) let at_most = Constr.at_most  let sigmatch = MetadataConstraints.sigmatch
137
138 let filter_uris_forward ~dbd (main, constants) uris =
139   let main_uris =
140     match main with
141     | None -> []
142     | Some (main, types) -> main :: types
143   in
144   let full_signature =
145     List.fold_right Constr.UriManagerSet.add main_uris constants
146   in
147   List.filter (at_most ~dbd ~where:`Statement full_signature) uris
148
149 let filter_uris_backward ~dbd ~facts signature uris =
150   let siguris =
151     List.map snd 
152       (sigmatch ~dbd ~facts ~where:`Statement signature)
153   in
154     intersect uris siguris 
155
156 let compare_goal_list proof goal1 goal2 =
157   let _,metasenv,_,_ = proof in
158   let (_, ey1, ty1) = CicUtil.lookup_meta goal1 metasenv in
159   let (_, ey2, ty2) =  CicUtil.lookup_meta goal2 metasenv in
160   let ty_sort1,_ = 
161     CicTypeChecker.type_of_aux' metasenv ey1 ty1 CicUniv.empty_ugraph 
162   in
163   let ty_sort2,_ = 
164     CicTypeChecker.type_of_aux' metasenv ey2 ty2 CicUniv.empty_ugraph 
165   in
166   let prop1 =
167     let b,_ = 
168       CicReduction.are_convertible 
169         ey1 (Cic.Sort Cic.Prop) ty_sort1 CicUniv.empty_ugraph 
170     in
171       if b then 0
172       else 1
173   in
174   let prop2 =
175     let b,_ = 
176       CicReduction.are_convertible 
177         ey2 (Cic.Sort Cic.Prop) ty_sort2 CicUniv.empty_ugraph 
178     in 
179       if b then 0
180       else 1
181   in
182   prop1 - prop2
183
184 (* experimental_hint is a version of hint for experimental 
185     purposes. It uses auto_tac_verbose instead of auto tac.
186     Auto_tac verbose also returns a substitution - for the moment 
187     as a function from cic to cic, to be changed into an association
188     list in the future -. This substitution is used to build a
189     hash table of the inspected goals with their associated proofs.
190     The cose is a cut and paste of the previous one: at the end 
191     of the experimentation we shall make a choice. *)
192
193 let close_with_types s metasenv context =
194   Constr.UriManagerSet.fold 
195     (fun e bag -> 
196       let t = CicUtil.term_of_uri e in
197       let ty, _ = 
198         CicTypeChecker.type_of_aux' metasenv context t CicUniv.empty_ugraph  
199       in
200       Constr.UriManagerSet.union bag (Constr.constants_of ty)) 
201     s s
202
203 let close_with_constructors s metasenv context =
204   Constr.UriManagerSet.fold 
205     (fun e bag -> 
206       let t = CicUtil.term_of_uri e in
207       match t with
208           Cic.MutInd (uri,_,_)  
209         | Cic.MutConstruct (uri,_,_,_) ->  
210             (match fst (CicEnvironment.get_obj CicUniv.empty_ugraph uri) with
211                  Cic.InductiveDefinition(tl,_,_,_) ->
212                    snd
213                      (List.fold_left
214                         (fun (i,s) (_,_,_,cl) ->
215                            let _,s =
216                              List.fold_left 
217                                (fun (j,s) _ -> 
218                                   let curi = UriManager.uri_of_uriref uri i (Some j) in
219                                     j+1,Constr.UriManagerSet.add curi s) (1,s) cl in
220                              (i+1,s)) (0,bag) tl)
221                | _ -> assert false)
222         | _ -> bag)
223     s s
224
225 (* Profiling code
226 let apply_tac_verbose =
227  let profiler = CicUtil.profile "apply_tac_verbose" in
228   fun ~term status -> profiler.profile (PrimitiveTactics.apply_tac_verbose ~term) status
229
230 let sigmatch =
231  let profiler = CicUtil.profile "sigmatch" in
232  fun ~dbd ~facts ?(where=`Conclusion) signature -> profiler.profile (Constr.sigmatch ~dbd ~facts ~where) signature
233
234 let cmatch' =
235  let profiler = CicUtil.profile "cmatch'" in
236  fun ~dbd ~facts signature -> profiler.profile (Constr.cmatch' ~dbd ~facts) signature
237 *) let apply_tac_verbose = PrimitiveTactics.apply_tac_verbose let cmatch' = Constr.cmatch'
238
239 let signature_of_goal ~(dbd:HMysql.dbd) ((proof, goal) as status) =
240  let (_, metasenv, _, _) = proof in
241  let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
242  let main, sig_constants = Constr.signature_of ty in
243  let set = signature_of_hypothesis context in
244  let set =
245   match main with
246      None -> set
247    | Some (main,l) ->
248       List.fold_right Constr.UriManagerSet.add (main::l) set in
249  let set = Constr.UriManagerSet.union set sig_constants in
250  let all_constants_closed = close_with_types set metasenv context in
251  let uris =
252   sigmatch ~dbd ~facts:false ~where:`Statement (None,all_constants_closed) in
253  let uris = List.filter nonvar (List.map snd uris) in
254  let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
255   uris
256
257 let equations_for_goal ~(dbd:HMysql.dbd) ((proof, goal) as status) =
258   let to_string set =
259     "{ " ^
260       (String.concat ", "
261          (Constr.UriManagerSet.fold
262             (fun u l -> (UriManager.string_of_uri u)::l) set []))
263     ^ " }"
264   in
265  let (_, metasenv, _, _) = proof in
266  let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
267  let main, sig_constants = Constr.signature_of ty in
268 (*  Printf.printf "\nsig_constants: %s\n\n" (to_string sig_constants); *)
269 (*  match main with *)
270 (*      None -> raise Goal_is_not_an_equation *)
271 (*    | Some (m,l) -> *)
272  let m, l =
273    let eq_URI = UriManager.uri_of_string HelmLibraryObjects.Logic.eq_XURI in
274    match main with
275    | None -> eq_URI, []
276    | Some (m, l) when UriManager.eq m eq_URI -> m, l
277    | Some (m, l) -> eq_URI, []
278  in
279  Printf.printf "\nSome (m, l): %s, [%s]\n\n"
280    (UriManager.string_of_uri m)
281    (String.concat "; " (List.map UriManager.string_of_uri l));
282  (*        if m == UriManager.uri_of_string HelmLibraryObjects.Logic.eq_XURI then ( *)
283  let set = signature_of_hypothesis context in
284  (*          Printf.printf "\nsignature_of_hypothesis: %s\n\n" (to_string set); *)
285  let set = Constr.UriManagerSet.union set sig_constants in
286  let set = close_with_types set metasenv context in
287  (*          Printf.printf "\ndopo close_with_types: %s\n\n" (to_string set); *)
288  let set = close_with_constructors set metasenv context in
289  (*          Printf.printf "\ndopo close_with_constructors: %s\n\n" (to_string set); *)
290  let set = List.fold_right Constr.UriManagerSet.remove (m::l) set in
291  let uris =
292    sigmatch ~dbd ~facts:false ~where:`Statement (main,set) in
293  let uris = List.filter nonvar (List.map snd uris) in
294  let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
295  uris
296    (*        ) *)
297    (*        else raise Goal_is_not_an_equation *)
298
299 let experimental_hint 
300   ~(dbd:HMysql.dbd) ?(facts=false) ?signature ((proof, goal) as status) =
301   let (_, metasenv, _, _) = proof in
302   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
303   let (uris, (main, sig_constants)) =
304     match signature with
305     | Some signature -> 
306         (sigmatch ~dbd ~facts signature, signature)
307     | None -> 
308         (cmatch' ~dbd ~facts ty, Constr.signature_of ty)
309   in 
310   let uris = List.filter nonvar (List.map snd uris) in
311   let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
312   let types_constants =
313     match main with
314     | None -> Constr.UriManagerSet.empty
315     | Some (main, types) ->
316         List.fold_right Constr.UriManagerSet.add (main :: types)
317           Constr.UriManagerSet.empty
318   in
319   let all_constants =
320     let hyp_and_sug =
321       Constr.UriManagerSet.union
322         (signature_of_hypothesis context) 
323         sig_constants
324     in
325     let main = 
326       match main with
327       | None -> Constr.UriManagerSet.empty
328       | Some (main,_) -> 
329           let ty, _ = 
330             CicTypeChecker.type_of_aux' 
331               metasenv context (CicUtil.term_of_uri main) CicUniv.empty_ugraph
332           in
333           Constr.constants_of ty
334     in
335     Constr.UriManagerSet.union main hyp_and_sug
336   in
337 (* Constr.UriManagerSet.iter debug_print hyp_constants; *)
338   let all_constants_closed = close_with_types all_constants metasenv context in
339   let other_constants = 
340     Constr.UriManagerSet.diff all_constants_closed types_constants
341   in
342   debug_print (lazy "all_constants_closed");
343   if debug then Constr.UriManagerSet.iter (fun s -> debug_print (lazy (UriManager.string_of_uri s))) all_constants_closed;
344   debug_print (lazy "other_constants");
345   if debug then Constr.UriManagerSet.iter (fun s -> debug_print (lazy (UriManager.string_of_uri s))) other_constants;
346   let uris = 
347     let pow = 2 ** (Constr.UriManagerSet.cardinal other_constants) in
348     if ((List.length uris < pow) or (pow <= 0))
349     then begin
350       debug_print (lazy "MetadataQuery: large sig, falling back to old method");
351       filter_uris_forward ~dbd (main, other_constants) uris
352     end else
353       filter_uris_backward ~dbd ~facts (main, other_constants) uris
354   in 
355   let rec aux = function
356     | [] -> []
357     | uri :: tl ->
358         (let status' =
359             try
360               let (subst,(proof, goal_list)) =
361                   (* debug_print (lazy ("STO APPLICANDO" ^ uri)); *)
362                   apply_tac_verbose 
363                     ~term:(CicUtil.term_of_uri uri)
364                   status
365               in
366               let goal_list =
367                 List.stable_sort (compare_goal_list proof) goal_list
368               in
369               Some (uri, (subst,(proof, goal_list)))
370             with ProofEngineTypes.Fail _ -> None
371           in
372           match status' with
373           | None -> aux tl
374           | Some status' -> status' :: aux tl)
375   in
376   List.stable_sort
377     (fun (_,(_, (_, goals1))) (_,(_, (_, goals2))) ->
378       Pervasives.compare (List.length goals1) (List.length goals2))
379     (aux uris)
380
381 let new_experimental_hint 
382   ~(dbd:HMysql.dbd) ?(facts=false) ?signature ~universe
383   ((proof, goal) as status)
384 =
385   let (_, metasenv, _, _) = proof in
386   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
387   let (uris, (main, sig_constants)) =
388     match signature with
389     | Some signature -> 
390         (sigmatch ~dbd ~facts signature, signature)
391     | None -> 
392         (cmatch' ~dbd ~facts ty, Constr.signature_of ty) in 
393   let universe =
394    List.fold_left
395     (fun res u -> Constr.UriManagerSet.add u res)
396     Constr.UriManagerSet.empty universe in
397   let uris =
398    List.fold_left
399     (fun res (_,u) -> Constr.UriManagerSet.add u res)
400     Constr.UriManagerSet.empty uris in
401   let uris = Constr.UriManagerSet.inter uris universe in
402   let uris = Constr.UriManagerSet.elements uris in
403   let rec aux = function
404     | [] -> []
405     | uri :: tl ->
406         (let status' =
407             try
408               let (subst,(proof, goal_list)) =
409                   (* debug_print (lazy ("STO APPLICANDO" ^ uri)); *)
410                   apply_tac_verbose 
411                     ~term:(CicUtil.term_of_uri uri)
412                   status
413               in
414               let goal_list =
415                 List.stable_sort (compare_goal_list proof) goal_list
416               in
417               Some (uri, (subst,(proof, goal_list)))
418             with ProofEngineTypes.Fail _ -> None
419           in
420           match status' with
421           | None -> aux tl
422           | Some status' -> status' :: aux tl)
423   in
424   List.stable_sort
425     (fun (_,(_, (_, goals1))) (_,(_, (_, goals2))) ->
426       Pervasives.compare (List.length goals1) (List.length goals2))
427     (aux uris)
428
429 let elim ~dbd uri =
430   let constraints =
431     [`Rel [`MainConclusion None];
432      `Sort (Cic.Prop,[`MainHypothesis (Some (MetadataTypes.Ge 1))]);
433      `Obj (uri,[`MainHypothesis (Some (MetadataTypes.Eq 0))]);
434      `Obj (uri,[`InHypothesis]);
435     ]
436   in
437   MetadataConstraints.at_least ~rating:`Hits ~dbd constraints
438
439
440 let fill_with_dummy_constants t =
441   let rec aux i types =
442     function
443         Cic.Lambda (n,s,t) -> 
444           let dummy_uri = 
445             UriManager.uri_of_string ("cic:/dummy_"^(string_of_int i)^".con") in
446             (aux (i+1) (s::types)
447                (CicSubstitution.subst (Cic.Const(dummy_uri,[])) t))
448       | t -> t,types
449   in 
450   let t,types = aux 0 [] t in
451   t, List.rev types
452       
453 let instance ~dbd t =
454   let t',types = fill_with_dummy_constants t in 
455   let metadata = MetadataExtractor.compute ~body:None ~ty:t' in
456 (*   List.iter 
457     (fun x -> 
458        debug_print 
459          (lazy (MetadataPp.pp_constr (MetadataTypes.constr_of_metadata x)))) 
460     metadata; *)
461   let no_concl = MetadataDb.count_distinct `Conclusion metadata in
462   let no_hyp = MetadataDb.count_distinct `Hypothesis metadata in
463   let no_full = MetadataDb.count_distinct `Statement metadata in
464   let is_dummy = function
465     | `Obj(s, _) -> (String.sub (UriManager.string_of_uri s) 0 10) <> "cic:/dummy" 
466           | _ -> true 
467   in
468   let rec look_for_dummy_main = function
469           | [] -> None
470     | `Obj(s,`MainConclusion (Some (MetadataTypes.Eq d)))::_ 
471       when (String.sub (UriManager.string_of_uri s) 0 10 = "cic:/dummy") -> 
472       let s = UriManager.string_of_uri s in
473       let len = String.length s in
474             let dummy_index = int_of_string (String.sub s 11 (len-15)) in
475       let dummy_type = List.nth types dummy_index in
476       Some (d,dummy_type)
477     | _::l -> look_for_dummy_main l 
478   in
479   match (look_for_dummy_main metadata) with
480     | None->
481 (*         debug_print (lazy "Caso None"); *)
482         (* no dummy in main position *)
483         let metadata = List.filter is_dummy metadata in
484         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
485         let concl_card = Some (MetadataConstraints.Eq no_concl) in
486         let full_card = Some (MetadataConstraints.Eq no_full) in
487         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
488           Constr.at_least ~dbd ?concl_card ?full_card ?diff constraints
489     | Some (depth, dummy_type) ->
490 (*         debug_print 
491           (lazy (sprintf "Caso Some %d %s" depth (CicPp.ppterm dummy_type))); *)
492         (* a dummy in main position *)
493         let metadata_for_dummy_type = 
494           MetadataExtractor.compute ~body:None ~ty:dummy_type in
495         (* Let us skip this for the moment 
496            let main_of_dummy_type = 
497            look_for_dummy_main metadata_for_dummy_type in *)
498         let metadata = List.filter is_dummy metadata in
499         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
500         let metadata_for_dummy_type = 
501           List.filter is_dummy metadata_for_dummy_type in
502         let metadata_for_dummy_type, depth' = 
503           (* depth' = the depth of the A -> A -> Prop *)
504           List.fold_left (fun (acc,dep) c ->
505             match c with
506             | `Sort (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
507                 (`Sort (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
508             | `Obj  (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
509                 (`Obj (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
510             | `Rel  (`MainConclusion (Some (MetadataTypes.Eq i))) -> 
511                 (`Rel (`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
512             | _ -> (c::acc,dep)) ([],0) metadata_for_dummy_type
513         in
514         let constraints_for_dummy_type =
515            List.map MetadataTypes.constr_of_metadata metadata_for_dummy_type in
516         (* start with the dummy constant in main conlusion *)
517         let from = ["refObj as table0"] in
518         let where = 
519           [sprintf "table0.h_position = \"%s\"" MetadataTypes.mainconcl_pos;
520                  sprintf "table0.h_depth >= %d" depth] in
521         let (n,from,where) =
522           List.fold_left 
523             (MetadataConstraints.add_constraint ~start:2)
524             (2,from,where) constraints in
525         let concl_card = Some (MetadataConstraints.Eq no_concl) in
526         let full_card = Some (MetadataConstraints.Eq no_full) in
527         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
528         let (n,from,where) = 
529           MetadataConstraints.add_all_constr 
530             (n,from,where) concl_card full_card diff in
531               (* join with the constraints over the type of the constant *)
532         let where = 
533           (sprintf "table0.h_occurrence = table%d.source" n)::where in
534         let where = 
535           sprintf "table0.h_depth - table%d.h_depth = %d" 
536             n (depth - depth')::where
537         in
538         let (m,from,where) =
539           List.fold_left 
540             (MetadataConstraints.add_constraint ~start:n)
541             (n,from,where) constraints_for_dummy_type in
542         Constr.exec ~dbd (m,from,where)
543
544 (* fwd_simpl ****************************************************************)
545
546 let rec map_filter f n = function
547    | []       -> []
548    | hd :: tl -> 
549       match f n hd with
550          | None    -> map_filter f (succ n) tl
551          | Some hd -> hd :: map_filter f (succ n) tl
552
553 let get_uri t =
554    let aux = function
555       | Cic.Appl (hd :: tl) -> Some (CicUtil.uri_of_term hd, tl)
556       | hd                  -> Some (CicUtil.uri_of_term hd, []) 
557    in
558    try aux t with
559       | Invalid_argument "uri_of_term" -> None
560
561 let get_metadata t =
562    let f n t =
563       match get_uri t with
564          | None          -> None 
565          | Some (uri, _) -> Some (n, uri)
566    in
567    match get_uri t with
568       | None             -> None
569       | Some (uri, args) -> Some (uri, map_filter f 1 args) 
570
571 let debug_metadata = function
572    | None                 -> ()
573    | Some (outer, inners) -> 
574       let f (n, uri) = Printf.eprintf "%s: %i %s\n" "fwd" n (UriManager.string_of_uri uri) in
575       Printf.eprintf "\n%s: %s\n" "fwd" (UriManager.string_of_uri outer);
576       List.iter f inners; prerr_newline ()
577
578 let fwd_simpl ~dbd t =
579    let map inners row = 
580       match row.(0), row.(1), row.(2) with  
581          | Some source, Some inner, Some index -> 
582             source,
583              List.mem
584               (int_of_string index, (UriManager.uri_of_string inner)) inners
585          | _                                   -> "", false
586    in
587    let rec rank ranks (source, ok) = 
588       match ranks, ok with
589          | [], false                               -> [source, 0]
590          | [], true                                -> [source, 1]
591          | (uri, i) :: tl, false when uri = source -> (uri, 0) :: tl
592          | (uri, 0) :: tl, true when uri = source  -> (uri, 0) :: tl
593          | (uri, i) :: tl, true when uri = source  -> (uri, succ i) :: tl
594          | hd :: tl, _ -> hd :: rank tl (source, ok)
595    in
596    let compare (_, x) (_, y) = compare x y in
597    let filter n (uri, rank) =
598       if rank > 0 then Some (UriManager.uri_of_string uri) else None
599    in
600    let metadata = get_metadata t in debug_metadata metadata;
601    match metadata with
602       | None                 -> []
603       | Some (outer, inners) ->
604          let select = "source, h_inner, h_index" in
605          let from = "genLemma" in
606          let where =
607           Printf.sprintf "h_outer = \"%s\""
608            (HMysql.escape (UriManager.string_of_uri outer)) in
609          let query = Printf.sprintf "SELECT %s FROM %s WHERE %s" select from where in
610          let result = HMysql.exec dbd query in
611          let lemmas = HMysql.map ~f:(map inners) result in
612          let ranked = List.fold_left rank [] lemmas in
613          let ordered = List.rev (List.fast_sort compare ranked) in
614          map_filter filter 0 ordered
615
616 (* get_decomposables ********************************************************)
617
618 let decomposables ~dbd =
619    let map row = match row.(0) with
620       | None     -> None
621       | Some str ->
622          match CicUtil.term_of_uri (UriManager.uri_of_string str) with
623             | Cic.MutInd (uri, typeno, _) -> Some (uri, typeno)
624             | _                           -> 
625                raise (UriManager.IllFormedUri str)
626    in
627    let select, from = "source", "decomposables" in
628    let query = Printf.sprintf "SELECT %s FROM %s" select from in
629    let decomposables = HMysql.map ~f:map (HMysql.exec dbd query) in
630    map_filter (fun _ x -> x) 0 decomposables