]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/disambiguation/disambiguate.ml
New modules stack:
[helm.git] / helm / software / components / disambiguation / disambiguate.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 (* $Id$ *)
27
28 open Printf
29
30 open DisambiguateTypes
31 open UriManager
32
33 module Ast = CicNotationPt
34
35 (* the integer is an offset to be added to each location *)
36 exception NoWellTypedInterpretation of
37  int *
38  ((Stdpp.location list * string * string) list *
39   (DisambiguateTypes.domain_item * string) list *
40   (Stdpp.location * string) Lazy.t * bool) list
41 exception PathNotWellFormed
42
43   (** raised when an environment is not enough informative to decide *)
44 exception Try_again of string Lazy.t
45
46 type 'term aliases = bool * 'term DisambiguateTypes.environment
47 type 'a disambiguator_input = string * int * 'a
48
49 type domain = domain_tree list
50 and domain_tree = Node of Stdpp.location list * domain_item * domain
51
52 let rec string_of_domain =
53  function
54     [] -> ""
55   | Node (_,domain_item,l)::tl ->
56      DisambiguateTypes.string_of_domain_item domain_item ^
57       " [ " ^ string_of_domain l ^ " ] " ^ string_of_domain tl
58
59 let rec filter_map_domain f =
60  function
61     [] -> []
62   | Node (locs,domain_item,l)::tl ->
63      match f locs domain_item with
64         None -> filter_map_domain f l @ filter_map_domain f tl
65       | Some res -> res :: filter_map_domain f l @ filter_map_domain f tl
66
67 let rec map_domain f =
68  function
69     [] -> []
70   | Node (locs,domain_item,l)::tl ->
71      f locs domain_item :: map_domain f l @ map_domain f tl
72
73 let uniq_domain dom =
74  let rec aux seen =
75   function
76      [] -> seen,[]
77    | Node (locs,domain_item,l)::tl ->
78       if List.mem domain_item seen then
79        let seen,l = aux seen l in
80        let seen,tl = aux seen tl in
81         seen, l @ tl
82       else
83        let seen,l = aux (domain_item::seen) l in
84        let seen,tl = aux seen tl in
85         seen, Node (locs,domain_item,l)::tl
86  in
87   snd (aux [] dom)
88
89 let debug = false
90 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
91
92 (*
93   (** print benchmark information *)
94 let benchmark = true
95 let max_refinements = ref 0       (* benchmarking is not thread safe *)
96 let actual_refinements = ref 0
97 let domain_size = ref 0
98 let choices_avg = ref 0.
99 *)
100
101 let descr_of_domain_item = function
102  | Id s -> s
103  | Symbol (s, _) -> s
104  | Num i -> string_of_int i
105
106 type ('term,'metasenv,'subst,'graph) test_result =
107   | Ok of 'term * 'metasenv * 'subst * 'graph
108   | Ko of (Stdpp.location * string) Lazy.t
109   | Uncertain of (Stdpp.location * string) Lazy.t
110
111 let resolve (env: 'term codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
112   try
113     snd (Environment.find item env) env num args
114   with Not_found -> 
115     failwith ("Domain item not found: " ^ 
116       (DisambiguateTypes.string_of_domain_item item))
117
118   (* TODO move it to Cic *)
119 let find_in_context name context =
120   let rec aux acc = function
121     | [] -> raise Not_found
122     | Some hd :: tl when hd = name -> acc
123     | _ :: tl ->  aux (acc + 1) tl
124   in
125   aux 1 context
126
127 let string_of_name =
128  function
129   | Ast.Ident (n, None) -> Some n
130   | _ -> assert false
131 ;;
132
133 let rec domain_of_term ?(loc = HExtlib.dummy_floc) ~context = function
134   | Ast.AttributedTerm (`Loc loc, term) ->
135      domain_of_term ~loc ~context term
136   | Ast.AttributedTerm (_, term) ->
137       domain_of_term ~loc ~context term
138   | Ast.Symbol (symbol, instance) ->
139       [ Node ([loc], Symbol (symbol, instance), []) ]
140       (* to be kept in sync with Ast.Appl (Ast.Symbol ...) *)
141   | Ast.Appl (Ast.Symbol (symbol, instance) as hd :: args)
142   | Ast.Appl (Ast.AttributedTerm (_,Ast.Symbol (symbol, instance)) as hd :: args)
143      ->
144       let args_dom =
145         List.fold_right
146           (fun term acc -> domain_of_term ~loc ~context term @ acc)
147           args [] in
148       let loc =
149        match hd with
150           Ast.AttributedTerm (`Loc loc,_)  -> loc
151         | _ -> loc
152       in
153        [ Node ([loc], Symbol (symbol, instance), args_dom) ]
154   | Ast.Appl (Ast.Ident (name, subst) as hd :: args)
155   | Ast.Appl (Ast.AttributedTerm (_,Ast.Ident (name, subst)) as hd :: args) ->
156       let args_dom =
157         List.fold_right
158           (fun term acc -> domain_of_term ~loc ~context term @ acc)
159           args [] in
160       let loc =
161        match hd with
162           Ast.AttributedTerm (`Loc loc,_)  -> loc
163         | _ -> loc
164       in
165       (try
166         (* the next line can raise Not_found *)
167         ignore(find_in_context name context);
168         if subst <> None then
169           Ast.fail loc "Explicit substitutions not allowed here"
170         else
171           args_dom
172       with Not_found ->
173         (match subst with
174         | None -> [ Node ([loc], Id name, args_dom) ]
175         | Some subst ->
176             let terms =
177               List.fold_left
178                 (fun dom (_, term) ->
179                   let dom' = domain_of_term ~loc ~context term in
180                   dom @ dom')
181                 [] subst in
182             [ Node ([loc], Id name, terms @ args_dom) ]))
183   | Ast.Appl terms ->
184       List.fold_right
185         (fun term acc -> domain_of_term ~loc ~context term @ acc)
186         terms []
187   | Ast.Binder (kind, (var, typ), body) ->
188       let type_dom = domain_of_term_option ~loc ~context typ in
189       let body_dom =
190         domain_of_term ~loc
191           ~context:(string_of_name var :: context) body in
192       (match kind with
193       | `Exists -> [ Node ([loc], Symbol ("exists", 0), (type_dom @ body_dom)) ]
194       | _ -> type_dom @ body_dom)
195   | Ast.Case (term, indty_ident, outtype, branches) ->
196       let term_dom = domain_of_term ~loc ~context term in
197       let outtype_dom = domain_of_term_option ~loc ~context outtype in
198       let rec get_first_constructor = function
199         | [] -> []
200         | (Ast.Pattern (head, _, _), _) :: _ -> [ Node ([loc], Id head, []) ]
201         | _ :: tl -> get_first_constructor tl in
202       let do_branch =
203        function
204           Ast.Pattern (head, _, args), term ->
205            let (term_context, args_domain) =
206              List.fold_left
207                (fun (cont, dom) (name, typ) ->
208                  (string_of_name name :: cont,
209                   (match typ with
210                   | None -> dom
211                   | Some typ -> dom @ domain_of_term ~loc ~context:cont typ)))
212                (context, []) args
213            in
214             domain_of_term ~loc ~context:term_context term @ args_domain
215         | Ast.Wildcard, term ->
216             domain_of_term ~loc ~context term
217       in
218       let branches_dom =
219         List.fold_left (fun dom branch -> dom @ do_branch branch) [] branches in
220       (match indty_ident with
221        | None -> get_first_constructor branches
222        | Some (ident, _) -> [ Node ([loc], Id ident, []) ])
223       @ term_dom @ outtype_dom @ branches_dom
224   | Ast.Cast (term, ty) ->
225       let term_dom = domain_of_term ~loc ~context term in
226       let ty_dom = domain_of_term ~loc ~context ty in
227       term_dom @ ty_dom
228   | Ast.LetIn ((var, typ), body, where) ->
229       let body_dom = domain_of_term ~loc ~context body in
230       let type_dom = domain_of_term_option ~loc ~context typ in
231       let where_dom =
232         domain_of_term ~loc ~context:(string_of_name var :: context) where in
233       body_dom @ type_dom @ where_dom
234   | Ast.LetRec (kind, defs, where) ->
235       let add_defs context =
236         List.fold_left
237           (fun acc (_, (var, _), _, _) -> string_of_name var :: acc
238           ) context defs in
239       let where_dom = domain_of_term ~loc ~context:(add_defs context) where in
240       let defs_dom =
241         List.fold_left
242           (fun dom (params, (_, typ), body, _) ->
243             let context' =
244              add_defs
245               (List.fold_left
246                 (fun acc (var,_) -> string_of_name var :: acc)
247                 context params)
248             in
249             List.rev
250              (snd
251                (List.fold_left
252                 (fun (context,res) (var,ty) ->
253                   string_of_name var :: context,
254                   domain_of_term_option ~loc ~context ty @ res)
255                 (add_defs context,[]) params))
256             @ dom
257             @ domain_of_term_option ~loc ~context:context' typ
258             @ domain_of_term ~loc ~context:context' body
259           ) [] defs
260       in
261       defs_dom @ where_dom
262   | Ast.Ident (name, subst) ->
263       (try
264         (* the next line can raise Not_found *)
265         ignore(find_in_context name context);
266         if subst <> None then
267           Ast.fail loc "Explicit substitutions not allowed here"
268         else
269           []
270       with Not_found ->
271         (match subst with
272         | None -> [ Node ([loc], Id name, []) ]
273         | Some subst ->
274             let terms =
275               List.fold_left
276                 (fun dom (_, term) ->
277                   let dom' = domain_of_term ~loc ~context term in
278                   dom @ dom')
279                 [] subst in
280             [ Node ([loc], Id name, terms) ]))
281   | Ast.Uri _ -> []
282   | Ast.Implicit -> []
283   | Ast.Num (num, i) -> [ Node ([loc], Num i, []) ]
284   | Ast.Meta (index, local_context) ->
285       List.fold_left
286        (fun dom term -> dom @ domain_of_term_option ~loc ~context term)
287        [] local_context
288   | Ast.Sort _ -> []
289   | Ast.UserInput
290   | Ast.Literal _
291   | Ast.Layout _
292   | Ast.Magic _
293   | Ast.Variable _ -> assert false
294
295 and domain_of_term_option ~loc ~context = function
296   | None -> []
297   | Some t -> domain_of_term ~loc ~context t
298
299 let domain_of_term ~context term = 
300  uniq_domain (domain_of_term ~context term)
301
302 let domain_of_obj ~context ast =
303  assert (context = []);
304   match ast with
305    | Ast.Theorem (_,_,ty,bo) ->
306       domain_of_term [] ty
307       @ (match bo with
308           None -> []
309         | Some bo -> domain_of_term [] bo)
310    | Ast.Inductive (params,tyl) ->
311       let context, dom = 
312        List.fold_left
313         (fun (context, dom) (var, ty) ->
314           let context' = string_of_name var :: context in
315           match ty with
316              None -> context', dom
317            | Some ty -> context', dom @ domain_of_term context ty
318         ) ([], []) params in
319       let context_w_types =
320         List.rev_map (fun (var, _, _, _) -> Some var) tyl @ context in
321       dom
322       @ List.flatten (
323          List.map
324           (fun (_,_,ty,cl) ->
325             domain_of_term context ty
326             @ List.flatten (
327                List.map
328                 (fun (_,ty) -> domain_of_term context_w_types ty) cl))
329                 tyl)
330    | CicNotationPt.Record (params,var,ty,fields) ->
331       let context, dom = 
332        List.fold_left
333         (fun (context, dom) (var, ty) ->
334           let context' = string_of_name var :: context in
335           match ty with
336              None -> context', dom
337            | Some ty -> context', dom @ domain_of_term context ty
338         ) ([], []) params in
339       let context_w_types = Some var :: context in
340       dom
341       @ domain_of_term context ty
342       @ snd
343          (List.fold_left
344           (fun (context,res) (name,ty,_,_) ->
345             Some name::context, res @ domain_of_term context ty
346           ) (context_w_types,[]) fields)
347
348 let domain_of_obj ~context obj = 
349  uniq_domain (domain_of_obj ~context obj)
350
351 let domain_of_ast_term = domain_of_term;;
352
353   (* dom1 \ dom2 *)
354 let domain_diff dom1 dom2 =
355 (* let domain_diff = Domain.diff *)
356   let is_in_dom2 elt =
357     List.exists
358      (function
359        | Symbol (symb, 0) ->
360           (match elt with
361               Symbol (symb',_) when symb = symb' -> true
362             | _ -> false)
363        | Num i ->
364           (match elt with
365               Num _ -> true
366             | _ -> false)
367        | item -> elt = item
368      ) dom2
369   in
370    let rec aux =
371     function
372        [] -> []
373      | Node (_,elt,l)::tl when is_in_dom2 elt -> aux (l @ tl)
374      | Node (loc,elt,l)::tl -> Node (loc,elt,aux l)::(aux tl)
375    in
376     aux dom1
377
378 module type Disambiguator =
379 sig
380   val disambiguate_thing:
381     context:'context ->
382     metasenv:'metasenv ->
383     subst:'subst ->
384     use_coercions:bool ->
385     mk_implicit:(bool -> 'refined_term) ->
386     string_context_of_context:('context -> string option list) ->
387     initial_ugraph:'ugraph ->
388     hint: 
389       ('metasenv -> 'raw_thing -> 'raw_thing) * 
390       (('refined_thing,'metasenv,'subst,'ugraph) test_result ->
391          ('refined_thing,'metasenv,'subst,'ugraph) test_result) ->
392     aliases:'refined_term DisambiguateTypes.codomain_item 
393       DisambiguateTypes.Environment.t ->
394     universe:'refined_term DisambiguateTypes.codomain_item list
395       DisambiguateTypes.Environment.t option ->
396     lookup_in_library:(
397       DisambiguateTypes.interactive_user_uri_choice_type ->
398       DisambiguateTypes.input_or_locate_uri_type ->
399       DisambiguateTypes.Environment.key ->
400       'refined_term DisambiguateTypes.codomain_item list) ->
401     uri:'uri ->
402     pp_thing:('ast_thing -> string) ->
403     domain_of_thing:(context: string option list -> 'ast_thing -> domain) ->
404     interpretate_thing:(
405       context:'context ->
406       env:'refined_term DisambiguateTypes.codomain_item
407              DisambiguateTypes.Environment.t ->
408       uri:'uri ->
409       is_path:bool -> 
410       'ast_thing -> 
411       localization_tbl:'cichash -> 
412         'raw_thing) ->
413     refine_thing:(
414       'metasenv -> 'subst -> 'context -> 'uri -> use_coercions:bool ->
415       'raw_thing -> 'ugraph -> localization_tbl:'cichash -> 
416         ('refined_thing, 'metasenv,'subst,'ugraph) test_result) ->
417     localization_tbl:'cichash ->
418     string * int * 'ast_thing ->
419     ((DisambiguateTypes.Environment.key * 
420       'refined_term DisambiguateTypes.codomain_item) list * 
421      'metasenv * 'subst * 'refined_thing * 'ugraph)
422     list * bool
423 end
424
425 module Make (C: Callbacks) =
426   struct
427 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
428
429     let disambiguate_thing 
430       ~context ~metasenv ~subst ~use_coercions
431       ~mk_implicit ~string_context_of_context
432       ~initial_ugraph:base_univ ~hint
433       ~aliases ~universe ~lookup_in_library 
434       ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing 
435       ~localization_tbl
436       (thing_txt,thing_txt_prefix_len,thing)
437     =
438       debug_print (lazy "DISAMBIGUATE INPUT");
439       debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
440       let thing_dom =
441         domain_of_thing ~context:(string_context_of_context context) thing in
442       debug_print
443        (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"(string_of_domain thing_dom)));
444 (*
445       debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
446         (DisambiguatePp.pp_environment aliases)));
447       debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
448         (match universe with None -> "None" | Some _ -> "Some _")));
449 *)
450       let current_dom =
451         Environment.fold (fun item _ dom -> item :: dom) aliases [] in
452       let todo_dom = domain_diff thing_dom current_dom in
453       debug_print
454        (lazy (sprintf "DISAMBIGUATION DOMAIN AFTER DIFF: %s"(string_of_domain todo_dom)));
455       (* (2) lookup function for any item (Id/Symbol/Num) *)
456       let lookup_choices =
457         fun item ->
458           let choices =
459             match universe with
460             | None -> 
461                 lookup_in_library 
462                   C.interactive_user_uri_choice 
463                   C.input_or_locate_uri item
464             | Some e ->
465                 (try
466                   let item =
467                     match item with
468                     | Symbol (symb, _) -> Symbol (symb, 0)
469                     | item -> item
470                   in
471                   Environment.find item e
472                 with Not_found -> 
473                   lookup_in_library 
474                     C.interactive_user_uri_choice 
475                     C.input_or_locate_uri item)
476           in
477           choices
478       in
479 (*
480       (* <benchmark> *)
481       let _ =
482         if benchmark then begin
483           let per_item_choices =
484             List.map
485               (fun dom_item ->
486                 try
487                   let len = List.length (lookup_choices dom_item) in
488                   debug_print (lazy (sprintf "BENCHMARK %s: %d"
489                     (string_of_domain_item dom_item) len));
490                   len
491                 with No_choices _ -> 0)
492               thing_dom
493           in
494           max_refinements := List.fold_left ( * ) 1 per_item_choices;
495           actual_refinements := 0;
496           domain_size := List.length thing_dom;
497           choices_avg :=
498             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
499         end
500       in
501       (* </benchmark> *)
502 *)
503
504       (* (3) test an interpretation filling with meta uninterpreted identifiers
505        *)
506       let test_env aliases todo_dom ugraph = 
507         let rec aux env = function
508           | [] -> env
509           | Node (_, item, l) :: tl ->
510               let env =
511                 Environment.add item
512                  ("Implicit",
513                    (match item with
514                       | Id _ | Num _ ->
515                           (fun _ _ _ -> mk_implicit true)
516                       | Symbol _ -> (fun _ _ _ -> mk_implicit false)))
517                  env in
518               aux (aux env l) tl in
519         let filled_env = aux aliases todo_dom in
520         try
521           let cic_thing =
522             interpretate_thing ~context ~env:filled_env
523              ~uri ~is_path:false thing ~localization_tbl
524           in
525           let cic_thing = (fst hint) metasenv cic_thing in
526 let foo () =
527           let k =
528            refine_thing metasenv subst context uri
529             ~use_coercions cic_thing ugraph ~localization_tbl
530           in
531           let k = (snd hint) k in
532             k
533 in refine_profiler.HExtlib.profile foo ()
534         with
535         | Try_again msg -> Uncertain (lazy (Stdpp.dummy_loc,Lazy.force msg))
536         | Invalid_choice loc_msg -> Ko loc_msg
537       in
538       (* (4) build all possible interpretations *)
539       let (@@) (l1,l2,l3) (l1',l2',l3') = l1@l1', l2@l2', l3@l3' in
540       (* aux returns triples Ok/Uncertain/Ko *)
541       (* rem_dom is the concatenation of all the remainin domains *)
542       let rec aux aliases diff lookup_in_todo_dom todo_dom rem_dom =
543         debug_print (lazy ("ZZZ: " ^ string_of_domain todo_dom));
544         match todo_dom with
545         | [] ->
546             assert (lookup_in_todo_dom = None);
547             (match test_env aliases rem_dom base_univ with
548             | Ok (thing, metasenv,subst,new_univ) -> 
549                [ aliases, diff, metasenv, subst, thing, new_univ ], [], []
550             | Ko loc_msg -> [],[],[aliases,diff,loc_msg,true]
551             | Uncertain loc_msg ->
552                [],[aliases,diff,loc_msg],[])
553         | Node (locs,item,inner_dom) :: remaining_dom ->
554             debug_print (lazy (sprintf "CHOOSED ITEM: %s"
555              (string_of_domain_item item)));
556             let choices =
557              match lookup_in_todo_dom with
558                 None -> lookup_choices item
559               | Some choices -> choices in
560             match choices with
561                [] ->
562                 [], [],
563                  [aliases, diff, 
564                   (lazy (List.hd locs,
565                     "No choices for " ^ string_of_domain_item item)),
566                   true]
567 (*
568              | [codomain_item] ->
569                  (* just one choice. We perform a one-step look-up and
570                     if the next set of choices is also a singleton we
571                     skip this refinement step *)
572                  debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
573                  let new_env = Environment.add item codomain_item aliases in
574                  let new_diff = (item,codomain_item)::diff in
575                  let lookup_in_todo_dom,next_choice_is_single =
576                   match remaining_dom with
577                      [] -> None,false
578                    | (_,he)::_ ->
579                       let choices = lookup_choices he in
580                        Some choices,List.length choices = 1
581                  in
582                   if next_choice_is_single then
583                    aux new_env new_diff lookup_in_todo_dom remaining_dom
584                     base_univ
585                   else
586                     (match test_env new_env remaining_dom base_univ with
587                     | Ok (thing, metasenv),new_univ ->
588                         (match remaining_dom with
589                         | [] ->
590                            [ new_env, new_diff, metasenv, thing, new_univ ], []
591                         | _ ->
592                            aux new_env new_diff lookup_in_todo_dom
593                             remaining_dom new_univ)
594                     | Uncertain (loc,msg),new_univ ->
595                         (match remaining_dom with
596                         | [] -> [], [new_env,new_diff,loc,msg,true]
597                         | _ ->
598                            aux new_env new_diff lookup_in_todo_dom
599                             remaining_dom new_univ)
600                     | Ko (loc,msg),_ -> [], [new_env,new_diff,loc,msg,true])
601 *)
602              | _::_ ->
603                  let mark_not_significant failures =
604                    List.map
605                     (fun (env, diff, loc_msg, _b) ->
606                       env, diff, loc_msg, false)
607                     failures in
608                  let classify_errors ((ok_l,uncertain_l,error_l) as outcome) =
609                   if ok_l <> [] || uncertain_l <> [] then
610                    ok_l,uncertain_l,mark_not_significant error_l
611                   else
612                    outcome in
613                let rec filter = function 
614                 | [] -> [],[],[]
615                 | codomain_item :: tl ->
616                     debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
617                     let new_env = Environment.add item codomain_item aliases in
618                     let new_diff = (item,codomain_item)::diff in
619                     (match
620                       test_env new_env 
621                         (inner_dom@remaining_dom@rem_dom) base_univ
622                      with
623                     | Ok (thing, metasenv,subst,new_univ) ->
624                         let res = 
625                           (match inner_dom with
626                           | [] ->
627                              [new_env,new_diff,metasenv,subst,thing,new_univ],
628                              [], []
629                           | _ ->
630                              aux new_env new_diff None inner_dom
631                               (remaining_dom@rem_dom) 
632                           ) 
633                         in
634                          res @@ filter tl
635                     | Uncertain loc_msg ->
636                         let res =
637                           (match inner_dom with
638                           | [] -> [],[new_env,new_diff,loc_msg],[]
639                           | _ ->
640                              aux new_env new_diff None inner_dom
641                               (remaining_dom@rem_dom) 
642                           )
643                         in
644                          res @@ filter tl
645                     | Ko loc_msg ->
646                         let res = [],[],[new_env,new_diff,loc_msg,true] in
647                          res @@ filter tl)
648                in
649                 let ok_l,uncertain_l,error_l =
650                  classify_errors (filter choices)
651                 in
652                  let res_after_ok_l =
653                   List.fold_right
654                    (fun (env,diff,_,_,_,_) res ->
655                      aux env diff None remaining_dom rem_dom @@ res
656                    ) ok_l ([],[],error_l)
657                 in
658                  List.fold_right
659                   (fun (env,diff,_) res ->
660                     aux env diff None remaining_dom rem_dom @@ res
661                   ) uncertain_l res_after_ok_l
662       in
663       let aux' aliases diff lookup_in_todo_dom todo_dom =
664        match test_env aliases todo_dom base_univ with
665         | Ok _
666         | Uncertain _ ->
667            aux aliases diff lookup_in_todo_dom todo_dom [] 
668         | Ko (loc_msg) -> [],[],[aliases,diff,loc_msg,true] in
669         let res =
670          match aux' aliases [] None todo_dom with
671          | [],uncertain,errors ->
672             let errors =
673              List.map
674               (fun (env,diff,loc_msg) -> (env,diff,loc_msg,true)
675               ) uncertain @ errors
676             in
677             let errors =
678              List.map
679               (fun (env,diff,loc_msg,significant) ->
680                 let env' =
681                  filter_map_domain
682                    (fun locs domain_item ->
683                      try
684                       let description =
685                        fst (Environment.find domain_item env)
686                       in
687                        Some (locs,descr_of_domain_item domain_item,description)
688                      with
689                       Not_found -> None)
690                    thing_dom
691                 in
692                 let diff= List.map (fun a,b -> a,fst b) diff in
693                  env',diff,loc_msg,significant
694               ) errors
695             in
696              raise (NoWellTypedInterpretation (0,errors))
697          | [_,diff,metasenv,subst,t,ugraph],_,_ ->
698              debug_print (lazy "SINGLE INTERPRETATION");
699              [diff,metasenv,subst,t,ugraph], false
700          | l,_,_ ->
701              debug_print 
702                (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
703              let choices =
704                List.map
705                  (fun (env, _, _, _, _, _) ->
706                    map_domain
707                      (fun locs domain_item ->
708                        let description =
709                          fst (Environment.find domain_item env)
710                        in
711                        locs,descr_of_domain_item domain_item, description)
712                      thing_dom)
713                  l
714              in
715              let choosed = 
716                C.interactive_interpretation_choice 
717                  thing_txt thing_txt_prefix_len choices 
718              in
719              (List.map (fun n->let _,d,m,s,t,u= List.nth l n in d,m,s,t,u)
720                choosed),
721               true
722         in
723          res
724
725   end