]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/metadataQuery.ml
ocaml 3.09 transition
[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 =
274      let us = UriManager.string_of_uri (LibraryObjects.eq_URI ()) in
275      UriManager.uri_of_string (us ^ "#xpointer(1/1)")
276    in
277    match main with
278    | None -> eq_URI, []
279    | Some (m, l) when UriManager.eq m eq_URI -> m, l
280    | Some (m, l) -> eq_URI, []
281  in
282  Printf.printf "\nSome (m, l): %s, [%s]\n\n"
283    (UriManager.string_of_uri m)
284    (String.concat "; " (List.map UriManager.string_of_uri l));
285  (*        if m == UriManager.uri_of_string HelmLibraryObjects.Logic.eq_XURI then ( *)
286  let set = signature_of_hypothesis context in
287  (*          Printf.printf "\nsignature_of_hypothesis: %s\n\n" (to_string set); *)
288  let set = Constr.UriManagerSet.union set sig_constants in
289  let set = close_with_types set metasenv context in
290  (*          Printf.printf "\ndopo close_with_types: %s\n\n" (to_string set); *)
291  let set = close_with_constructors set metasenv context in
292  (*          Printf.printf "\ndopo close_with_constructors: %s\n\n" (to_string set); *)
293  let set = List.fold_right Constr.UriManagerSet.remove (m::l) set in
294  let uris =
295    sigmatch ~dbd ~facts:false ~where:`Statement (main,set) in
296  let uris = List.filter nonvar (List.map snd uris) in
297  let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
298  uris
299    (*        ) *)
300    (*        else raise Goal_is_not_an_equation *)
301
302 let experimental_hint 
303   ~(dbd:HMysql.dbd) ?(facts=false) ?signature ((proof, goal) as status) =
304   let (_, metasenv, _, _) = proof in
305   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
306   let (uris, (main, sig_constants)) =
307     match signature with
308     | Some signature -> 
309         (sigmatch ~dbd ~facts signature, signature)
310     | None -> 
311         (cmatch' ~dbd ~facts ty, Constr.signature_of ty)
312   in 
313   let uris = List.filter nonvar (List.map snd uris) in
314   let uris = List.filter Hashtbl_equiv.not_a_duplicate uris in
315   let types_constants =
316     match main with
317     | None -> Constr.UriManagerSet.empty
318     | Some (main, types) ->
319         List.fold_right Constr.UriManagerSet.add (main :: types)
320           Constr.UriManagerSet.empty
321   in
322   let all_constants =
323     let hyp_and_sug =
324       Constr.UriManagerSet.union
325         (signature_of_hypothesis context) 
326         sig_constants
327     in
328     let main = 
329       match main with
330       | None -> Constr.UriManagerSet.empty
331       | Some (main,_) -> 
332           let ty, _ = 
333             CicTypeChecker.type_of_aux' 
334               metasenv context (CicUtil.term_of_uri main) CicUniv.empty_ugraph
335           in
336           Constr.constants_of ty
337     in
338     Constr.UriManagerSet.union main hyp_and_sug
339   in
340 (* Constr.UriManagerSet.iter debug_print hyp_constants; *)
341   let all_constants_closed = close_with_types all_constants metasenv context in
342   let other_constants = 
343     Constr.UriManagerSet.diff all_constants_closed types_constants
344   in
345   debug_print (lazy "all_constants_closed");
346   if debug then Constr.UriManagerSet.iter (fun s -> debug_print (lazy (UriManager.string_of_uri s))) all_constants_closed;
347   debug_print (lazy "other_constants");
348   if debug then Constr.UriManagerSet.iter (fun s -> debug_print (lazy (UriManager.string_of_uri s))) other_constants;
349   let uris = 
350     let pow = 2 ** (Constr.UriManagerSet.cardinal other_constants) in
351     if ((List.length uris < pow) or (pow <= 0))
352     then begin
353       debug_print (lazy "MetadataQuery: large sig, falling back to old method");
354       filter_uris_forward ~dbd (main, other_constants) uris
355     end else
356       filter_uris_backward ~dbd ~facts (main, other_constants) uris
357   in 
358   let rec aux = function
359     | [] -> []
360     | uri :: tl ->
361         (let status' =
362             try
363               let (subst,(proof, goal_list)) =
364                   (* debug_print (lazy ("STO APPLICANDO" ^ uri)); *)
365                   apply_tac_verbose 
366                     ~term:(CicUtil.term_of_uri uri)
367                   status
368               in
369               let goal_list =
370                 List.stable_sort (compare_goal_list proof) goal_list
371               in
372               Some (uri, (subst,(proof, goal_list)))
373             with ProofEngineTypes.Fail _ -> None
374           in
375           match status' with
376           | None -> aux tl
377           | Some status' -> status' :: aux tl)
378   in
379   List.stable_sort
380     (fun (_,(_, (_, goals1))) (_,(_, (_, goals2))) ->
381       Pervasives.compare (List.length goals1) (List.length goals2))
382     (aux uris)
383
384 let new_experimental_hint 
385   ~(dbd:HMysql.dbd) ?(facts=false) ?signature ~universe
386   ((proof, goal) as status)
387 =
388   let (_, metasenv, _, _) = proof in
389   let (_, context, ty) = CicUtil.lookup_meta goal metasenv in
390   let (uris, (main, sig_constants)) =
391     match signature with
392     | Some signature -> 
393         (sigmatch ~dbd ~facts signature, signature)
394     | None -> 
395         (cmatch' ~dbd ~facts ty, Constr.signature_of ty) in 
396   let universe =
397    List.fold_left
398     (fun res u -> Constr.UriManagerSet.add u res)
399     Constr.UriManagerSet.empty universe in
400   let uris =
401    List.fold_left
402     (fun res (_,u) -> Constr.UriManagerSet.add u res)
403     Constr.UriManagerSet.empty uris in
404   let uris = Constr.UriManagerSet.inter uris universe in
405   let uris = Constr.UriManagerSet.elements uris in
406   let rec aux = function
407     | [] -> []
408     | uri :: tl ->
409         (let status' =
410             try
411               let (subst,(proof, goal_list)) =
412                   (* debug_print (lazy ("STO APPLICANDO" ^ uri)); *)
413                   apply_tac_verbose 
414                     ~term:(CicUtil.term_of_uri uri)
415                   status
416               in
417               let goal_list =
418                 List.stable_sort (compare_goal_list proof) goal_list
419               in
420               Some (uri, (subst,(proof, goal_list)))
421             with ProofEngineTypes.Fail _ -> None
422           in
423           match status' with
424           | None -> aux tl
425           | Some status' -> status' :: aux tl)
426   in
427   List.stable_sort
428     (fun (_,(_, (_, goals1))) (_,(_, (_, goals2))) ->
429       Pervasives.compare (List.length goals1) (List.length goals2))
430     (aux uris)
431
432 let elim ~dbd uri =
433   let constraints =
434     [`Rel [`MainConclusion None];
435      `Sort (Cic.Prop,[`MainHypothesis (Some (MetadataTypes.Ge 1))]);
436      `Obj (uri,[`MainHypothesis (Some (MetadataTypes.Eq 0))]);
437      `Obj (uri,[`InHypothesis]);
438     ]
439   in
440   MetadataConstraints.at_least ~rating:`Hits ~dbd constraints
441
442
443 let fill_with_dummy_constants t =
444   let rec aux i types =
445     function
446         Cic.Lambda (n,s,t) -> 
447           let dummy_uri = 
448             UriManager.uri_of_string ("cic:/dummy_"^(string_of_int i)^".con") in
449             (aux (i+1) (s::types)
450                (CicSubstitution.subst (Cic.Const(dummy_uri,[])) t))
451       | t -> t,types
452   in 
453   let t,types = aux 0 [] t in
454   t, List.rev types
455       
456 let instance ~dbd t =
457   let t',types = fill_with_dummy_constants t in 
458   let metadata = MetadataExtractor.compute ~body:None ~ty:t' in
459 (*   List.iter 
460     (fun x -> 
461        debug_print 
462          (lazy (MetadataPp.pp_constr (MetadataTypes.constr_of_metadata x)))) 
463     metadata; *)
464   let no_concl = MetadataDb.count_distinct `Conclusion metadata in
465   let no_hyp = MetadataDb.count_distinct `Hypothesis metadata in
466   let no_full = MetadataDb.count_distinct `Statement metadata in
467   let is_dummy = function
468     | `Obj(s, _) -> (String.sub (UriManager.string_of_uri s) 0 10) <> "cic:/dummy" 
469           | _ -> true 
470   in
471   let rec look_for_dummy_main = function
472           | [] -> None
473     | `Obj(s,`MainConclusion (Some (MetadataTypes.Eq d)))::_ 
474       when (String.sub (UriManager.string_of_uri s) 0 10 = "cic:/dummy") -> 
475       let s = UriManager.string_of_uri s in
476       let len = String.length s in
477             let dummy_index = int_of_string (String.sub s 11 (len-15)) in
478       let dummy_type = List.nth types dummy_index in
479       Some (d,dummy_type)
480     | _::l -> look_for_dummy_main l 
481   in
482   match (look_for_dummy_main metadata) with
483     | None->
484 (*         debug_print (lazy "Caso None"); *)
485         (* no dummy in main position *)
486         let metadata = List.filter is_dummy metadata in
487         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
488         let concl_card = Some (MetadataConstraints.Eq no_concl) in
489         let full_card = Some (MetadataConstraints.Eq no_full) in
490         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
491           Constr.at_least ~dbd ?concl_card ?full_card ?diff constraints
492     | Some (depth, dummy_type) ->
493 (*         debug_print 
494           (lazy (sprintf "Caso Some %d %s" depth (CicPp.ppterm dummy_type))); *)
495         (* a dummy in main position *)
496         let metadata_for_dummy_type = 
497           MetadataExtractor.compute ~body:None ~ty:dummy_type in
498         (* Let us skip this for the moment 
499            let main_of_dummy_type = 
500            look_for_dummy_main metadata_for_dummy_type in *)
501         let metadata = List.filter is_dummy metadata in
502         let constraints = List.map MetadataTypes.constr_of_metadata metadata in
503         let metadata_for_dummy_type = 
504           List.filter is_dummy metadata_for_dummy_type in
505         let metadata_for_dummy_type, depth' = 
506           (* depth' = the depth of the A -> A -> Prop *)
507           List.fold_left (fun (acc,dep) c ->
508             match c with
509             | `Sort (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
510                 (`Sort (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
511             | `Obj  (s,`MainConclusion (Some (MetadataTypes.Eq i))) -> 
512                 (`Obj (s,`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
513             | `Rel  (`MainConclusion (Some (MetadataTypes.Eq i))) -> 
514                 (`Rel (`MainConclusion (Some (MetadataTypes.Ge i))))::acc, i
515             | _ -> (c::acc,dep)) ([],0) metadata_for_dummy_type
516         in
517         let constraints_for_dummy_type =
518            List.map MetadataTypes.constr_of_metadata metadata_for_dummy_type in
519         (* start with the dummy constant in main conlusion *)
520         let from = ["refObj as table0"] in
521         let where = 
522           [sprintf "table0.h_position = \"%s\"" MetadataTypes.mainconcl_pos;
523                  sprintf "table0.h_depth >= %d" depth] in
524         let (n,from,where) =
525           List.fold_left 
526             (MetadataConstraints.add_constraint ~start:2)
527             (2,from,where) constraints in
528         let concl_card = Some (MetadataConstraints.Eq no_concl) in
529         let full_card = Some (MetadataConstraints.Eq no_full) in
530         let diff = Some (MetadataConstraints.Eq (no_hyp - no_concl)) in
531         let (n,from,where) = 
532           MetadataConstraints.add_all_constr 
533             (n,from,where) concl_card full_card diff in
534               (* join with the constraints over the type of the constant *)
535         let where = 
536           (sprintf "table0.h_occurrence = table%d.source" n)::where in
537         let where = 
538           sprintf "table0.h_depth - table%d.h_depth = %d" 
539             n (depth - depth')::where
540         in
541         let (m,from,where) =
542           List.fold_left 
543             (MetadataConstraints.add_constraint ~start:n)
544             (n,from,where) constraints_for_dummy_type in
545         Constr.exec ~dbd (m,from,where)
546
547 (* fwd_simpl ****************************************************************)
548
549 let rec map_filter f n = function
550    | []       -> []
551    | hd :: tl -> 
552       match f n hd with
553          | None    -> map_filter f (succ n) tl
554          | Some hd -> hd :: map_filter f (succ n) tl
555
556 let get_uri t =
557    let aux = function
558       | Cic.Appl (hd :: tl) -> Some (CicUtil.uri_of_term hd, tl)
559       | hd                  -> Some (CicUtil.uri_of_term hd, []) 
560    in
561    try aux t with
562       | Invalid_argument "uri_of_term" -> None
563
564 let get_metadata t =
565    let f n t =
566       match get_uri t with
567          | None          -> None 
568          | Some (uri, _) -> Some (n, uri)
569    in
570    match get_uri t with
571       | None             -> None
572       | Some (uri, args) -> Some (uri, map_filter f 1 args) 
573
574 let debug_metadata = function
575    | None                 -> ()
576    | Some (outer, inners) -> 
577       let f (n, uri) = Printf.eprintf "%s: %i %s\n" "fwd" n (UriManager.string_of_uri uri) in
578       Printf.eprintf "\n%s: %s\n" "fwd" (UriManager.string_of_uri outer);
579       List.iter f inners; prerr_newline ()
580
581 let fwd_simpl ~dbd t =
582    let map inners row = 
583       match row.(0), row.(1), row.(2) with  
584          | Some source, Some inner, Some index -> 
585             source,
586              List.mem
587               (int_of_string index, (UriManager.uri_of_string inner)) inners
588          | _                                   -> "", false
589    in
590    let rec rank ranks (source, ok) = 
591       match ranks, ok with
592          | [], false                               -> [source, 0]
593          | [], true                                -> [source, 1]
594          | (uri, i) :: tl, false when uri = source -> (uri, 0) :: tl
595          | (uri, 0) :: tl, true when uri = source  -> (uri, 0) :: tl
596          | (uri, i) :: tl, true when uri = source  -> (uri, succ i) :: tl
597          | hd :: tl, _ -> hd :: rank tl (source, ok)
598    in
599    let compare (_, x) (_, y) = compare x y in
600    let filter n (uri, rank) =
601       if rank > 0 then Some (UriManager.uri_of_string uri) else None
602    in
603    let metadata = get_metadata t in debug_metadata metadata;
604    match metadata with
605       | None                 -> []
606       | Some (outer, inners) ->
607          let select = "source, h_inner, h_index" in
608          let from = "genLemma" in
609          let where =
610           Printf.sprintf "h_outer = \"%s\""
611            (HMysql.escape (UriManager.string_of_uri outer)) in
612          let query = Printf.sprintf "SELECT %s FROM %s WHERE %s" select from where in
613          let result = HMysql.exec dbd query in
614          let lemmas = HMysql.map ~f:(map inners) result in
615          let ranked = List.fold_left rank [] lemmas in
616          let ordered = List.rev (List.fast_sort compare ranked) in
617          map_filter filter 0 ordered
618
619 (* get_decomposables ********************************************************)
620
621 let decomposables ~dbd =
622    let map row = match row.(0) with
623       | None     -> None
624       | Some str ->
625          match CicUtil.term_of_uri (UriManager.uri_of_string str) with
626             | Cic.MutInd (uri, typeno, _) -> Some (uri, typeno)
627             | _                           -> 
628                raise (UriManager.IllFormedUri str)
629    in
630    let select, from = "source", "decomposables" in
631    let query = Printf.sprintf "SELECT %s FROM %s" select from in
632    let decomposables = HMysql.map ~f:map (HMysql.exec dbd query) in
633    map_filter (fun _ x -> x) 0 decomposables