]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/cic_disambiguation/disambiguate.ml
Disambiguation errors now carry more information (i.e. the patches to apply to
[helm.git] / helm / software / components / cic_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 (* the integer is an offset to be added to each location *)
34 exception NoWellTypedInterpretation of
35  int * ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list * Token.flocation option * string Lazy.t) list
36 exception PathNotWellFormed
37
38   (** raised when an environment is not enough informative to decide *)
39 exception Try_again of string Lazy.t
40
41 type aliases = bool * DisambiguateTypes.environment
42 type 'a disambiguator_input = string * int * 'a
43
44 let debug = false
45 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
46
47 (*
48   (** print benchmark information *)
49 let benchmark = true
50 let max_refinements = ref 0       (* benchmarking is not thread safe *)
51 let actual_refinements = ref 0
52 let domain_size = ref 0
53 let choices_avg = ref 0.
54 *)
55
56 let descr_of_domain_item = function
57  | Id s -> s
58  | Symbol (s, _) -> s
59  | Num i -> string_of_int i
60
61 type 'a test_result =
62   | Ok of 'a * Cic.metasenv
63   | Ko of Token.flocation option * string Lazy.t
64   | Uncertain of Token.flocation option * string Lazy.t
65
66 let refine_term metasenv context uri term ugraph ~localization_tbl =
67 (*   if benchmark then incr actual_refinements; *)
68   assert (uri=None);
69     debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term)));
70     try
71       let term', _, metasenv',ugraph1 = 
72         CicRefine.type_of_aux' metasenv context term ugraph ~localization_tbl in
73         (Ok (term', metasenv')),ugraph1
74     with
75      exn ->
76       let rec process_exn loc =
77        function
78           HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
79         | CicRefine.Uncertain msg ->
80             debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppterm term)) ;
81             Uncertain (loc,msg),ugraph
82         | CicRefine.RefineFailure msg ->
83             debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
84               (CicPp.ppterm term) (Lazy.force msg)));
85             Ko (loc,msg),ugraph
86        | exn -> raise exn
87       in
88        process_exn None exn
89
90 let refine_obj metasenv context uri obj ugraph ~localization_tbl =
91  assert (context = []);
92    debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppobj obj))) ;
93    try
94      let obj', metasenv,ugraph =
95       CicRefine.typecheck metasenv uri obj ~localization_tbl
96      in
97        (Ok (obj', metasenv)),ugraph
98    with
99      exn ->
100       let rec process_exn loc =
101        function
102           HExtlib.Localized (loc,exn) -> process_exn (Some loc) exn
103         | CicRefine.Uncertain msg ->
104             debug_print (lazy ("UNCERTAIN!!! [" ^ (Lazy.force msg) ^ "] " ^ CicPp.ppobj obj)) ;
105             Uncertain (loc,msg),ugraph
106         | CicRefine.RefineFailure msg ->
107             debug_print (lazy (sprintf "PRUNED!!!\nterm%s\nmessage:%s"
108               (CicPp.ppobj obj) (Lazy.force msg))) ;
109             Ko (loc,msg),ugraph
110        | exn -> raise exn
111       in
112        process_exn None exn
113
114 let resolve (env: codomain_item Environment.t) (item: domain_item) ?(num = "") ?(args = []) () =
115   try
116     snd (Environment.find item env) env num args
117   with Not_found -> 
118     failwith ("Domain item not found: " ^ 
119       (DisambiguateTypes.string_of_domain_item item))
120
121   (* TODO move it to Cic *)
122 let find_in_context name context =
123   let rec aux acc = function
124     | [] -> raise Not_found
125     | Cic.Name hd :: tl when hd = name -> acc
126     | _ :: tl ->  aux (acc + 1) tl
127   in
128   aux 1 context
129
130 let interpretate_term ~(context: Cic.name list) ~env ~uri ~is_path ast
131      ~localization_tbl
132 =
133   assert (uri = None);
134   let rec aux ~localize loc (context: Cic.name list) = function
135     | CicNotationPt.AttributedTerm (`Loc loc, term) ->
136         let res = aux ~localize loc context term in
137          if localize then Cic.CicHash.add localization_tbl res loc;
138          res
139     | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
140     | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
141         let cic_args = List.map (aux ~localize loc context) args in
142         resolve env (Symbol (symb, i)) ~args:cic_args ()
143     | CicNotationPt.Appl terms ->
144        Cic.Appl (List.map (aux ~localize loc context) terms)
145     | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
146         let cic_type = aux_option ~localize loc context (Some `Type) typ in
147         let cic_name = CicNotationUtil.cic_name_of_name var in
148         let cic_body = aux ~localize loc (cic_name :: context) body in
149         (match binder_kind with
150         | `Lambda -> Cic.Lambda (cic_name, cic_type, cic_body)
151         | `Pi
152         | `Forall -> Cic.Prod (cic_name, cic_type, cic_body)
153         | `Exists ->
154             resolve env (Symbol ("exists", 0))
155               ~args:[ cic_type; Cic.Lambda (cic_name, cic_type, cic_body) ] ())
156     | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
157         let cic_term = aux ~localize loc context term in
158         let cic_outtype = aux_option ~localize loc context None outtype in
159         let do_branch ((head, _, args), term) =
160           let rec do_branch' context = function
161             | [] -> aux ~localize loc context term
162             | (name, typ) :: tl ->
163                 let cic_name = CicNotationUtil.cic_name_of_name name in
164                 let cic_body = do_branch' (cic_name :: context) tl in
165                 let typ =
166                   match typ with
167                   | None -> Cic.Implicit (Some `Type)
168                   | Some typ -> aux ~localize loc context typ
169                 in
170                 Cic.Lambda (cic_name, typ, cic_body)
171           in
172           do_branch' context args
173         in
174         let (indtype_uri, indtype_no) =
175           match indty_ident with
176           | Some (indty_ident, _) ->
177              (match resolve env (Id indty_ident) () with
178               | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
179               | Cic.Implicit _ ->
180                  raise (Try_again (lazy "The type of the term to be matched
181                   is still unknown"))
182               | _ ->
183                 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
184           | None ->
185               let fst_constructor =
186                 match branches with
187                 | ((head, _, _), _) :: _ -> head
188                 | [] -> raise (Invalid_choice (lazy "The type of the term to be matched is an inductive type without constructors that cannot be determined"))
189               in
190               (match resolve env (Id fst_constructor) () with
191               | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
192                   (indtype_uri, indtype_no)
193               | Cic.Implicit _ ->
194                  raise (Try_again (lazy "The type of the term to be matched
195                   is still unknown"))
196               | _ ->
197                 raise (Invalid_choice (lazy "The type of the term to be matched is not (co)inductive!")))
198         in
199         Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
200           (List.map do_branch branches))
201     | CicNotationPt.Cast (t1, t2) ->
202         let cic_t1 = aux ~localize loc context t1 in
203         let cic_t2 = aux ~localize loc context t2 in
204         Cic.Cast (cic_t1, cic_t2)
205     | CicNotationPt.LetIn ((name, typ), def, body) ->
206         let cic_def = aux ~localize loc context def in
207         let cic_name = CicNotationUtil.cic_name_of_name name in
208         let cic_def =
209           match typ with
210           | None -> cic_def
211           | Some t -> Cic.Cast (cic_def, aux ~localize loc context t)
212         in
213         let cic_body = aux ~localize loc (cic_name :: context) body in
214         Cic.LetIn (cic_name, cic_def, cic_body)
215     | CicNotationPt.LetRec (kind, defs, body) ->
216         let context' =
217           List.fold_left
218             (fun acc (_, (name, _), _, _) ->
219               CicNotationUtil.cic_name_of_name name :: acc)
220             context defs
221         in
222         let cic_body =
223          let unlocalized_body = aux ~localize:false loc context' body in
224          match unlocalized_body with
225             Cic.Rel 1 -> `AvoidLetInNoAppl
226           | Cic.Appl (Cic.Rel 1::l) ->
227              (try
228                let l' =
229                 List.map
230                  (function t ->
231                    let t',subst,metasenv =
232                     CicMetaSubst.delift_rels [] [] 1 t
233                    in
234                     assert (subst=[]);
235                     assert (metasenv=[]);
236                     t') l
237                in
238                 (* We can avoid the LetIn. But maybe we need to recompute l'
239                    so that it is localized *)
240                 if localize then
241                  match body with
242                     CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
243                      let l' = List.map (aux ~localize loc context) l in
244                       `AvoidLetIn l'
245                   | _ -> assert false
246                 else
247                  `AvoidLetIn l'
248               with
249                CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
250                 if localize then
251                  `AddLetIn (aux ~localize loc context' body)
252                 else
253                  `AddLetIn unlocalized_body)
254           | _ ->
255              if localize then
256               `AddLetIn (aux ~localize loc context' body)
257              else
258               `AddLetIn unlocalized_body
259         in
260         let inductiveFuns =
261           List.map
262             (fun (params, (name, typ), body, decr_idx) ->
263               let add_binders kind t =
264                List.fold_right
265                 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
266               in
267               let cic_body =
268                aux ~localize loc context' (add_binders `Lambda body) in
269               let cic_type =
270                aux_option ~localize loc context (Some `Type)
271                 (HExtlib.map_option (add_binders `Pi) typ) in
272               let name =
273                 match CicNotationUtil.cic_name_of_name name with
274                 | Cic.Anonymous ->
275                     CicNotationPt.fail loc
276                       "Recursive functions cannot be anonymous"
277                 | Cic.Name name -> name
278               in
279               (name, decr_idx, cic_type, cic_body))
280             defs
281         in
282         let counter = ref ~-1 in
283         let build_term funs =
284           (* this is the body of the fold_right function below. Rationale: Fix
285            * and CoFix cases differs only in an additional index in the
286            * inductiveFun list, see Cic.term *)
287           match kind with
288           | `Inductive ->
289               (fun (var, _, _, _) cic ->
290                 incr counter;
291                 let fix = Cic.Fix (!counter,funs) in
292                  match cic with
293                     `Recipe (`AddLetIn cic) ->
294                       `Term (Cic.LetIn (Cic.Name var, fix, cic))
295                   | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
296                   | `Recipe `AvoidLetInNoAppl -> `Term fix
297                   | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
298           | `CoInductive ->
299               let funs =
300                 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
301               in
302               (fun (var, _, _, _) cic ->
303                 incr counter;
304                 let cofix = Cic.CoFix (!counter,funs) in
305                  match cic with
306                     `Recipe (`AddLetIn cic) ->
307                       `Term (Cic.LetIn (Cic.Name var, cofix, cic))
308                   | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
309                   | `Recipe `AvoidLetInNoAppl -> `Term cofix
310                   | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
311         in
312          (match
313            List.fold_right (build_term inductiveFuns) inductiveFuns
314             (`Recipe cic_body)
315           with
316              `Recipe _ -> assert false
317            | `Term t -> t)
318     | CicNotationPt.Ident _
319     | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
320     | CicNotationPt.Ident (name, subst)
321     | CicNotationPt.Uri (name, subst) as ast ->
322         let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
323         (try
324           if is_uri ast then raise Not_found;(* don't search the env for URIs *)
325           let index = find_in_context name context in
326           if subst <> None then
327             CicNotationPt.fail loc "Explicit substitutions not allowed here";
328           Cic.Rel index
329         with Not_found ->
330           let cic =
331             if is_uri ast then  (* we have the URI, build the term out of it *)
332               try
333                 CicUtil.term_of_uri (UriManager.uri_of_string name)
334               with UriManager.IllFormedUri _ ->
335                 CicNotationPt.fail loc "Ill formed URI"
336             else
337               resolve env (Id name) ()
338           in
339           let mk_subst uris =
340             let ids_to_uris =
341               List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
342             in
343             (match subst with
344             | Some subst ->
345                 List.map
346                   (fun (s, term) ->
347                     (try
348                       List.assoc s ids_to_uris, aux ~localize loc context term
349                      with Not_found ->
350                        raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
351                   subst
352             | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
353           in
354           (try 
355             match cic with
356             | Cic.Const (uri, []) ->
357                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
358                 let uris = CicUtil.params_of_obj o in
359                 Cic.Const (uri, mk_subst uris)
360             | Cic.Var (uri, []) ->
361                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
362                 let uris = CicUtil.params_of_obj o in
363                 Cic.Var (uri, mk_subst uris)
364             | Cic.MutInd (uri, i, []) ->
365                (try
366                  let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
367                  let uris = CicUtil.params_of_obj o in
368                  Cic.MutInd (uri, i, mk_subst uris)
369                 with
370                  CicEnvironment.Object_not_found _ ->
371                   (* if we are here it is probably the case that during the
372                      definition of a mutual inductive type we have met an
373                      occurrence of the type in one of its constructors.
374                      However, the inductive type is not yet in the environment
375                   *)
376                   (*here the explicit_named_substituion is assumed to be of length 0 *)
377                   Cic.MutInd (uri,i,[]))
378             | Cic.MutConstruct (uri, i, j, []) ->
379                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
380                 let uris = CicUtil.params_of_obj o in
381                 Cic.MutConstruct (uri, i, j, mk_subst uris)
382             | Cic.Meta _ | Cic.Implicit _ as t ->
383 (*
384                 debug_print (lazy (sprintf
385                   "Warning: %s must be instantiated with _[%s] but we do not enforce it"
386                   (CicPp.ppterm t)
387                   (String.concat "; "
388                     (List.map
389                       (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
390                       subst))));
391 *)
392                 t
393             | _ ->
394               raise (Invalid_choice (lazy "??? Can this happen?"))
395            with 
396              CicEnvironment.CircularDependency _ -> 
397                raise (Invalid_choice (lazy "Circular dependency in the environment"))))
398     | CicNotationPt.Implicit -> Cic.Implicit None
399     | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
400     | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
401     | CicNotationPt.Meta (index, subst) ->
402         let cic_subst =
403           List.map
404             (function
405                 None -> None
406               | Some term -> Some (aux ~localize loc context term))
407             subst
408         in
409         Cic.Meta (index, cic_subst)
410     | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
411     | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
412     | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
413     | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
414     | CicNotationPt.Symbol (symbol, instance) ->
415         resolve env (Symbol (symbol, instance)) ()
416     | _ -> assert false (* god bless Bologna *)
417   and aux_option ~localize loc (context: Cic.name list) annotation = function
418     | None -> Cic.Implicit annotation
419     | Some term -> aux ~localize loc context term
420   in
421    aux ~localize:true HExtlib.dummy_floc context ast
422
423 let interpretate_path ~context path =
424  let localization_tbl = Cic.CicHash.create 23 in
425   (* here we are throwing away useful localization informations!!! *)
426   fst (
427    interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
428     path ~localization_tbl, localization_tbl)
429
430 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
431  assert (context = []);
432  assert (is_path = false);
433  let interpretate_term = interpretate_term ~localization_tbl in
434  match obj with
435   | CicNotationPt.Inductive (params,tyl) ->
436      let uri = match uri with Some uri -> uri | None -> assert false in
437      let context,params =
438       let context,res =
439        List.fold_left
440         (fun (context,res) (name,t) ->
441           let t =
442            match t with
443               None -> CicNotationPt.Implicit
444             | Some t -> t in
445           let name = CicNotationUtil.cic_name_of_name name in
446            name::context,(name, interpretate_term context env None false t)::res
447         ) ([],[]) params
448       in
449        context,List.rev res in
450      let add_params =
451       List.fold_right (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
452      let name_to_uris =
453       snd (
454        List.fold_left
455         (*here the explicit_named_substituion is assumed to be of length 0 *)
456         (fun (i,res) (name,_,_,_) ->
457           i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
458         ) (0,[]) tyl) in
459      let con_env = DisambiguateTypes.env_of_list name_to_uris env in
460      let tyl =
461       List.map
462        (fun (name,b,ty,cl) ->
463          let ty' = add_params (interpretate_term context env None false ty) in
464          let cl' =
465           List.map
466            (fun (name,ty) ->
467              let ty' =
468               add_params (interpretate_term context con_env None false ty)
469              in
470               name,ty'
471            ) cl
472          in
473           name,b,ty',cl'
474        ) tyl
475      in
476       Cic.InductiveDefinition (tyl,[],List.length params,[])
477   | CicNotationPt.Record (params,name,ty,fields) ->
478      let uri = match uri with Some uri -> uri | None -> assert false in
479      let context,params =
480       let context,res =
481        List.fold_left
482         (fun (context,res) (name,t) ->
483           let t =
484            match t with
485               None -> CicNotationPt.Implicit
486             | Some t -> t in
487           let name = CicNotationUtil.cic_name_of_name name in
488            name::context,(name, interpretate_term context env None false t)::res
489         ) ([],[]) params
490       in
491        context,List.rev res in
492      let add_params =
493       List.fold_right
494        (fun (name,ty) t -> Cic.Prod (name,ty,t)) params in
495      let ty' = add_params (interpretate_term context env None false ty) in
496      let fields' =
497       snd (
498        List.fold_left
499         (fun (context,res) (name,ty,_coercion,arity) ->
500           let context' = Cic.Name name :: context in
501            context',(name,interpretate_term context env None false ty)::res
502         ) (context,[]) fields) in
503      let concl =
504       (*here the explicit_named_substituion is assumed to be of length 0 *)
505       let mutind = Cic.MutInd (uri,0,[]) in
506       if params = [] then mutind
507       else
508        Cic.Appl
509         (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
510      let con =
511       List.fold_left
512        (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
513        concl fields' in
514      let con' = add_params con in
515      let tyl = [name,true,ty',["mk_" ^ name,con']] in
516      let field_names = List.map (fun (x,_,y,z) -> x,y,z) fields in
517       Cic.InductiveDefinition
518        (tyl,[],List.length params,[`Class (`Record field_names)])
519   | CicNotationPt.Theorem (flavour, name, ty, bo) ->
520      let attrs = [`Flavour flavour] in
521      let ty' = interpretate_term [] env None false ty in
522      (match bo,flavour with
523         None,`Axiom ->
524          Cic.Constant (name,None,ty',[],attrs)
525       | Some bo,`Axiom -> assert false
526       | None,_ ->
527          Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
528       | Some bo,_ ->
529          let bo' = Some (interpretate_term [] env None false bo) in
530           Cic.Constant (name,bo',ty',[],attrs))
531           
532
533   (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
534 let rev_uniq =
535   let module SortedItem =
536     struct
537       type t = DisambiguateTypes.domain_item
538       let compare = Pervasives.compare
539     end
540   in
541   let module Map = Map.Make (SortedItem) in
542   fun l ->
543     let rev_l = List.rev l in
544     let (members, uniq_rev_l) =
545       List.fold_left
546         (fun (members, rev_l) (loc,elt) ->
547           try 
548             let locs = Map.find elt members in
549             if List.mem loc locs then
550               members, rev_l
551             else
552               Map.add elt (loc::locs) members, rev_l
553           with
554           | Not_found -> Map.add elt [loc] members, elt :: rev_l)
555         (Map.empty, []) rev_l
556     in
557     List.rev_map 
558       (fun e -> try Map.find e members,e with Not_found -> assert false)
559       uniq_rev_l
560
561 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
562  * Domain item more in deep in the list will be processed first.
563  *)
564 let rec domain_rev_of_term ?(loc = HExtlib.dummy_floc) context = function
565   | CicNotationPt.AttributedTerm (`Loc loc, term) ->
566      domain_rev_of_term ~loc context term
567   | CicNotationPt.AttributedTerm (_, term) ->
568       domain_rev_of_term ~loc context term
569   | CicNotationPt.Appl terms ->
570       List.fold_left
571        (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
572   | CicNotationPt.Binder (kind, (var, typ), body) ->
573       let kind_dom =
574         match kind with
575         | `Exists -> [ loc, Symbol ("exists", 0) ]
576         | _ -> []
577       in
578       let type_dom = domain_rev_of_term_option ~loc context typ in
579       let body_dom =
580         domain_rev_of_term ~loc
581           (CicNotationUtil.cic_name_of_name var :: context) body
582       in
583       body_dom @ type_dom @ kind_dom
584   | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
585       let term_dom = domain_rev_of_term ~loc context term in
586       let outtype_dom = domain_rev_of_term_option loc context outtype in
587       let get_first_constructor = function
588         | [] -> []
589         | ((head, _, _), _) :: _ -> [ loc, Id head ]
590       in
591       let do_branch ((head, _, args), term) =
592         let (term_context, args_domain) =
593           List.fold_left
594             (fun (cont, dom) (name, typ) ->
595               (CicNotationUtil.cic_name_of_name name :: cont,
596                (match typ with
597                | None -> dom
598                | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
599             (context, []) args
600         in
601         args_domain @ domain_rev_of_term ~loc term_context term
602       in
603       let branches_dom =
604         List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
605       in
606       branches_dom @ outtype_dom @ term_dom @
607       (match indty_ident with
608        | None -> get_first_constructor branches
609        | Some (ident, _) -> [ loc, Id ident ])
610   | CicNotationPt.Cast (term, ty) ->
611       let term_dom = domain_rev_of_term ~loc context term in
612       let ty_dom = domain_rev_of_term ~loc context ty in
613       ty_dom @ term_dom
614   | CicNotationPt.LetIn ((var, typ), body, where) ->
615       let body_dom = domain_rev_of_term ~loc context body in
616       let type_dom = domain_rev_of_term_option loc context typ in
617       let where_dom =
618         domain_rev_of_term ~loc
619           (CicNotationUtil.cic_name_of_name var :: context) where
620       in
621       where_dom @ type_dom @ body_dom
622   | CicNotationPt.LetRec (kind, defs, where) ->
623       let add_defs context =
624         List.fold_left
625           (fun acc (_, (var, _), _, _) ->
626             CicNotationUtil.cic_name_of_name var :: acc
627           ) context defs in
628       let where_dom = domain_rev_of_term ~loc (add_defs context) where in
629       let defs_dom =
630         List.fold_left
631           (fun dom (params, (_, typ), body, _) ->
632             let context' =
633              add_defs
634               (List.fold_left
635                 (fun acc (var,_) -> CicNotationUtil.cic_name_of_name var :: acc)
636                 context params)
637             in
638             domain_rev_of_term ~loc context' body @
639             domain_rev_of_term_option ~loc context typ @
640             List.rev
641              (snd
642                (List.fold_left
643                 (fun (context,res) (var,ty) ->
644                   CicNotationUtil.cic_name_of_name var :: context,
645                   res @ domain_rev_of_term_option ~loc context ty)
646                 (add_defs context,[]) params))
647           ) [] defs
648       in
649       where_dom @ defs_dom
650   | CicNotationPt.Ident (name, subst) ->
651       (try
652         (* the next line can raise Not_found *)
653         ignore(find_in_context name context);
654         if subst <> None then
655           CicNotationPt.fail loc "Explicit substitutions not allowed here"
656         else
657           []
658       with Not_found ->
659         (match subst with
660         | None -> [loc, Id name]
661         | Some subst ->
662             List.fold_left
663               (fun dom (_, term) ->
664                 let dom' = domain_rev_of_term ~loc context term in
665                 dom' @ dom)
666               [loc, Id name] subst))
667   | CicNotationPt.Uri _ -> []
668   | CicNotationPt.Implicit -> []
669   | CicNotationPt.Num (num, i) -> [loc, Num i ]
670   | CicNotationPt.Meta (index, local_context) ->
671       List.fold_left
672        (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
673         local_context
674   | CicNotationPt.Sort _ -> []
675   | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
676   | CicNotationPt.UserInput
677   | CicNotationPt.Literal _
678   | CicNotationPt.Layout _
679   | CicNotationPt.Magic _
680   | CicNotationPt.Variable _ -> assert false
681
682 and domain_rev_of_term_option ~loc context = function
683   | None -> []
684   | Some t -> domain_rev_of_term ~loc context t
685
686 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
687
688 let domain_of_obj ~context ast =
689  assert (context = []);
690  let domain_rev =
691   match ast with
692    | CicNotationPt.Theorem (_,_,ty,bo) ->
693       (match bo with
694           None -> []
695         | Some bo -> domain_rev_of_term [] bo) @
696       domain_rev_of_term [] ty
697    | CicNotationPt.Inductive (params,tyl) ->
698       let dom =
699        List.flatten (
700         List.rev_map
701          (fun (_,_,ty,cl) ->
702            List.flatten (
703             List.rev_map
704              (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
705             domain_rev_of_term [] ty) tyl) in
706       let dom = 
707        List.fold_left
708         (fun dom (_,ty) ->
709           match ty with
710              None -> dom
711            | Some ty -> domain_rev_of_term [] ty @ dom
712         ) dom params
713       in
714        List.filter
715         (fun (_,name) ->
716           not (  List.exists (fun (name',_) ->
717                   match CicNotationUtil.cic_name_of_name name' with
718                      Cic.Anonymous -> false
719                    | Cic.Name name' -> name = Id name') params
720               || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
721         ) dom
722    | CicNotationPt.Record (params,_,ty,fields) ->
723       let dom =
724        List.flatten
725         (List.rev_map (fun (_,ty,_,_) -> domain_rev_of_term [] ty) fields) in
726       let dom =
727        List.fold_left
728         (fun dom (_,ty) ->
729           match ty with
730              None -> dom
731            | Some ty -> domain_rev_of_term [] ty @ dom
732         ) (dom @ domain_rev_of_term [] ty) params
733       in
734        List.filter
735         (fun (_,name) ->
736           not (  List.exists (fun (name',_) ->
737                   match CicNotationUtil.cic_name_of_name name' with
738                      Cic.Anonymous -> false
739                    | Cic.Name name' -> name = Id name') params
740               || List.exists (fun (name',_,_,_) -> name = Id name') fields)
741         ) dom
742  in
743   rev_uniq domain_rev
744
745   (* dom1 \ dom2 *)
746 let domain_diff dom1 dom2 =
747 (* let domain_diff = Domain.diff *)
748   let is_in_dom2 elt =
749     List.exists
750      (function
751        | Symbol (symb, 0) ->
752           (match elt with
753               Symbol (symb',_) when symb = symb' -> true
754             | _ -> false)
755        | Num i ->
756           (match elt with
757               Num _ -> true
758             | _ -> false)
759        | item -> elt = item
760      ) dom2
761   in
762   List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
763
764 module type Disambiguator =
765 sig
766   val disambiguate_term :
767     ?fresh_instances:bool ->
768     dbd:HMysql.dbd ->
769     context:Cic.context ->
770     metasenv:Cic.metasenv ->
771     ?initial_ugraph:CicUniv.universe_graph -> 
772     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
773     universe:DisambiguateTypes.multiple_environment option ->
774     CicNotationPt.term disambiguator_input ->
775     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
776      Cic.metasenv *                  (* new metasenv *)
777      Cic.term*
778      CicUniv.universe_graph) list *  (* disambiguated term *)
779     bool
780
781   val disambiguate_obj :
782     ?fresh_instances:bool ->
783     dbd:HMysql.dbd ->
784     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
785     universe:DisambiguateTypes.multiple_environment option ->
786     uri:UriManager.uri option ->     (* required only for inductive types *)
787     CicNotationPt.obj disambiguator_input ->
788     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
789      Cic.metasenv *                  (* new metasenv *)
790      Cic.obj *
791      CicUniv.universe_graph) list *  (* disambiguated obj *)
792     bool
793 end
794
795 module Make (C: Callbacks) =
796   struct
797     let choices_of_id dbd id =
798       let uris = Whelp.locate ~dbd id in
799       let uris =
800        match uris with
801         | [] ->
802            (match 
803              (C.input_or_locate_uri 
804                ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ()) 
805            with
806            | None -> []
807            | Some uri -> [uri])
808         | [uri] -> [uri]
809         | _ ->
810             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
811              ~ok:"Try selected." ~enable_button_for_non_vars:true
812              ~title:"Ambiguous input." ~id
813              ~msg: ("Ambiguous input \"" ^ id ^
814                 "\". Please, choose one or more interpretations:")
815              uris
816       in
817       List.map
818         (fun uri ->
819           (UriManager.string_of_uri uri,
820            let term =
821              try
822                CicUtil.term_of_uri uri
823              with exn ->
824                debug_print (lazy (UriManager.string_of_uri uri));
825                debug_print (lazy (Printexc.to_string exn));
826                assert false
827             in
828            fun _ _ _ -> term))
829         uris
830
831 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
832
833     let disambiguate_thing ~dbd ~context ~metasenv
834       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
835       ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing 
836       (thing_txt,thing_txt_prefix_len,thing)
837     =
838       debug_print (lazy "DISAMBIGUATE INPUT");
839       let disambiguate_context =  (* cic context -> disambiguate context *)
840         List.map
841           (function None -> Cic.Anonymous | Some (name, _) -> name)
842           context
843       in
844       debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
845       let thing_dom = domain_of_thing ~context:disambiguate_context thing in
846       debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
847         (string_of_domain (List.map snd thing_dom))));
848 (*
849       debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
850         (DisambiguatePp.pp_environment aliases)));
851       debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
852         (match universe with None -> "None" | Some _ -> "Some _")));
853 *)
854       let current_dom =
855         Environment.fold (fun item _ dom -> item :: dom) aliases []
856       in
857       let todo_dom = domain_diff thing_dom current_dom in
858       (* (2) lookup function for any item (Id/Symbol/Num) *)
859       let lookup_choices =
860         fun item ->
861           let choices =
862             let lookup_in_library () =
863               match item with
864               | Id id -> choices_of_id dbd id
865               | Symbol (symb, _) ->
866                   List.map DisambiguateChoices.mk_choice
867                     (TermAcicContent.lookup_interpretations symb)
868               | Num instance ->
869                   DisambiguateChoices.lookup_num_choices ()
870             in
871             match universe with
872             | None -> lookup_in_library ()
873             | Some e ->
874                 (try
875                   let item =
876                     match item with
877                     | Symbol (symb, _) -> Symbol (symb, 0)
878                     | item -> item
879                   in
880                   Environment.find item e
881                 with Not_found -> lookup_in_library ())
882           in
883           choices
884       in
885 (*
886       (* <benchmark> *)
887       let _ =
888         if benchmark then begin
889           let per_item_choices =
890             List.map
891               (fun dom_item ->
892                 try
893                   let len = List.length (lookup_choices dom_item) in
894                   debug_print (lazy (sprintf "BENCHMARK %s: %d"
895                     (string_of_domain_item dom_item) len));
896                   len
897                 with No_choices _ -> 0)
898               thing_dom
899           in
900           max_refinements := List.fold_left ( * ) 1 per_item_choices;
901           actual_refinements := 0;
902           domain_size := List.length thing_dom;
903           choices_avg :=
904             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
905         end
906       in
907       (* </benchmark> *)
908 *)
909
910       (* (3) test an interpretation filling with meta uninterpreted identifiers
911        *)
912       let test_env aliases todo_dom ugraph = 
913         let filled_env =
914           List.fold_left
915             (fun env (_,item) ->
916                Environment.add item
917                ("Implicit",
918                  (match item with
919                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
920                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
921             aliases todo_dom 
922         in
923         try
924           let localization_tbl = Cic.CicHash.create 503 in
925           let cic_thing =
926             interpretate_thing ~context:disambiguate_context ~env:filled_env
927              ~uri ~is_path:false thing ~localization_tbl
928           in
929 let foo () =
930           let k,ugraph1 =
931            refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
932           in
933             (k , ugraph1 )
934 in refine_profiler.HExtlib.profile foo ()
935         with
936         | Try_again msg -> Uncertain (None,msg), ugraph
937         | Invalid_choice msg -> Ko (None,msg), ugraph
938       in
939       (* (4) build all possible interpretations *)
940       let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
941       let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
942         match todo_dom with
943         | [] ->
944             assert (lookup_in_todo_dom = None);
945             (match test_env aliases [] base_univ with
946             | Ok (thing, metasenv),new_univ -> 
947                [ aliases, diff, metasenv, thing, new_univ ], []
948             | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[diff,loc,msg])
949         | (locs,item) :: remaining_dom ->
950             debug_print (lazy (sprintf "CHOOSED ITEM: %s"
951              (string_of_domain_item item)));
952             let choices =
953              match lookup_in_todo_dom with
954                 None -> lookup_choices item
955               | Some choices -> choices in
956             match choices with
957                [] ->
958                 [], [diff,
959                      Some (List.hd locs),
960                      lazy ("No choices for " ^ string_of_domain_item item)]
961              | [codomain_item] ->
962                  (* just one choice. We perform a one-step look-up and
963                     if the next set of choices is also a singleton we
964                     skip this refinement step *)
965                  debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
966                  let new_env = Environment.add item codomain_item aliases in
967                  let new_diff = (item,codomain_item)::diff in
968                  let lookup_in_todo_dom,next_choice_is_single =
969                   match remaining_dom with
970                      [] -> None,false
971                    | (_,he)::_ ->
972                       let choices = lookup_choices he in
973                        Some choices,List.length choices = 1
974                  in
975                   if next_choice_is_single then
976                    aux new_env new_diff lookup_in_todo_dom remaining_dom
977                     base_univ
978                   else
979                     (match test_env new_env remaining_dom base_univ with
980                     | Ok (thing, metasenv),new_univ ->
981                         (match remaining_dom with
982                         | [] ->
983                            [ new_env, new_diff, metasenv, thing, new_univ ], []
984                         | _ ->
985                            aux new_env new_diff lookup_in_todo_dom
986                             remaining_dom new_univ)
987                     | Uncertain (loc,msg),new_univ ->
988                         (match remaining_dom with
989                         | [] -> [], [diff,loc,msg]
990                         | _ ->
991                            aux new_env new_diff lookup_in_todo_dom
992                             remaining_dom new_univ)
993                     | Ko (loc,msg),_ -> [], [diff,loc,msg])
994              | _::_ ->
995                let rec filter univ = function 
996                 | [] -> [],[]
997                 | codomain_item :: tl ->
998                     debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
999                     let new_env = Environment.add item codomain_item aliases in
1000                     let new_diff = (item,codomain_item)::diff in
1001                     (match test_env new_env remaining_dom univ with
1002                     | Ok (thing, metasenv),new_univ ->
1003                         (match remaining_dom with
1004                         | [] -> [new_env,new_diff,metasenv,thing,new_univ], []
1005                         | _ -> aux new_env new_diff None remaining_dom new_univ
1006                         ) @@ 
1007                           filter univ tl
1008                     | Uncertain (loc,msg),new_univ ->
1009                         (match remaining_dom with
1010                         | [] -> [],[diff,loc,msg]
1011                         | _ -> aux new_env new_diff None remaining_dom new_univ
1012                         ) @@ 
1013                           filter univ tl
1014                     | Ko (loc,msg),_ -> ([],[diff,loc,msg]) @@ filter univ tl)
1015                in
1016                 filter base_univ choices
1017       in
1018       let base_univ = initial_ugraph in
1019       try
1020         let res =
1021          match aux aliases [] None todo_dom base_univ with
1022          | [],errors -> raise (NoWellTypedInterpretation (0,errors))
1023          | [_,diff,metasenv,t,ugraph],_ ->
1024              debug_print (lazy "SINGLE INTERPRETATION");
1025              [diff,metasenv,t,ugraph], false
1026          | l,_ ->
1027              debug_print 
1028                (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
1029              let choices =
1030                List.map
1031                  (fun (env, _, _, _, _) ->
1032                    List.map
1033                      (fun (locs,domain_item) ->
1034                        let description =
1035                          fst (Environment.find domain_item env)
1036                        in
1037                        locs,descr_of_domain_item domain_item, description)
1038                      thing_dom)
1039                  l
1040              in
1041              let choosed = 
1042                C.interactive_interpretation_choice 
1043                  thing_txt thing_txt_prefix_len choices 
1044              in
1045              (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1046               true
1047         in
1048          res
1049      with
1050       CicEnvironment.CircularDependency s -> 
1051         failwith "Disambiguate: circular dependency"
1052
1053     let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1054       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe 
1055       (text,prefix_len,term)
1056     =
1057       let term =
1058         if fresh_instances then CicNotationUtil.freshen_term term else term
1059       in
1060       disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1061         ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1062         ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1063         ~refine_thing:refine_term (text,prefix_len,term)
1064
1065     let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1066      (text,prefix_len,obj)
1067     =
1068       let obj =
1069         if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1070       in
1071       disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1072         ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1073         ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1074         (text,prefix_len,obj)
1075   end
1076