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