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