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