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