]> matita.cs.unibo.it Git - helm.git/blob - components/cic_disambiguation/disambiguate.ml
645ad57accf85ec211859a23f6954fb1ca494c57
[helm.git] / 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 * (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 ((name, typ), body, decr_idx) ->
263               let cic_body = aux ~localize loc context' body in
264               let cic_type =
265                aux_option ~localize loc context (Some `Type) typ in
266               let name =
267                 match CicNotationUtil.cic_name_of_name name with
268                 | Cic.Anonymous ->
269                     CicNotationPt.fail loc
270                       "Recursive functions cannot be anonymous"
271                 | Cic.Name name -> name
272               in
273               (name, decr_idx, cic_type, cic_body))
274             defs
275         in
276         let counter = ref ~-1 in
277         let build_term funs =
278           (* this is the body of the fold_right function below. Rationale: Fix
279            * and CoFix cases differs only in an additional index in the
280            * inductiveFun list, see Cic.term *)
281           match kind with
282           | `Inductive ->
283               (fun (var, _, _, _) cic ->
284                 incr counter;
285                 let fix = Cic.Fix (!counter,funs) in
286                  match cic with
287                     `Recipe (`AddLetIn cic) ->
288                       `Term (Cic.LetIn (Cic.Name var, fix, cic))
289                   | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (fix::l))
290                   | `Recipe `AvoidLetInNoAppl -> `Term fix
291                   | `Term t -> `Term (Cic.LetIn (Cic.Name var, fix, t)))
292           | `CoInductive ->
293               let funs =
294                 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
295               in
296               (fun (var, _, _, _) cic ->
297                 incr counter;
298                 let cofix = Cic.CoFix (!counter,funs) in
299                  match cic with
300                     `Recipe (`AddLetIn cic) ->
301                       `Term (Cic.LetIn (Cic.Name var, cofix, cic))
302                   | `Recipe (`AvoidLetIn l) -> `Term (Cic.Appl (cofix::l))
303                   | `Recipe `AvoidLetInNoAppl -> `Term cofix
304                   | `Term t -> `Term (Cic.LetIn (Cic.Name var, cofix, t)))
305         in
306          (match
307            List.fold_right (build_term inductiveFuns) inductiveFuns
308             (`Recipe cic_body)
309           with
310              `Recipe _ -> assert false
311            | `Term t -> t)
312     | CicNotationPt.Ident _
313     | CicNotationPt.Uri _ when is_path -> raise PathNotWellFormed
314     | CicNotationPt.Ident (name, subst)
315     | CicNotationPt.Uri (name, subst) as ast ->
316         let is_uri = function CicNotationPt.Uri _ -> true | _ -> false in
317         (try
318           if is_uri ast then raise Not_found;(* don't search the env for URIs *)
319           let index = find_in_context name context in
320           if subst <> None then
321             CicNotationPt.fail loc "Explicit substitutions not allowed here";
322           Cic.Rel index
323         with Not_found ->
324           let cic =
325             if is_uri ast then  (* we have the URI, build the term out of it *)
326               try
327                 CicUtil.term_of_uri (UriManager.uri_of_string name)
328               with UriManager.IllFormedUri _ ->
329                 CicNotationPt.fail loc "Ill formed URI"
330             else
331               resolve env (Id name) ()
332           in
333           let mk_subst uris =
334             let ids_to_uris =
335               List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
336             in
337             (match subst with
338             | Some subst ->
339                 List.map
340                   (fun (s, term) ->
341                     (try
342                       List.assoc s ids_to_uris, aux ~localize loc context term
343                      with Not_found ->
344                        raise (Invalid_choice (lazy "The provided explicit named substitution is trying to instantiate a named variable the object is not abstracted on"))))
345                   subst
346             | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
347           in
348           (try 
349             match cic with
350             | Cic.Const (uri, []) ->
351                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
352                 let uris = CicUtil.params_of_obj o in
353                 Cic.Const (uri, mk_subst uris)
354             | Cic.Var (uri, []) ->
355                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
356                 let uris = CicUtil.params_of_obj o in
357                 Cic.Var (uri, mk_subst uris)
358             | Cic.MutInd (uri, i, []) ->
359                (try
360                  let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
361                  let uris = CicUtil.params_of_obj o in
362                  Cic.MutInd (uri, i, mk_subst uris)
363                 with
364                  CicEnvironment.Object_not_found _ ->
365                   (* if we are here it is probably the case that during the
366                      definition of a mutual inductive type we have met an
367                      occurrence of the type in one of its constructors.
368                      However, the inductive type is not yet in the environment
369                   *)
370                   (*here the explicit_named_substituion is assumed to be of length 0 *)
371                   Cic.MutInd (uri,i,[]))
372             | Cic.MutConstruct (uri, i, j, []) ->
373                 let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
374                 let uris = CicUtil.params_of_obj o in
375                 Cic.MutConstruct (uri, i, j, mk_subst uris)
376             | Cic.Meta _ | Cic.Implicit _ as t ->
377 (*
378                 debug_print (lazy (sprintf
379                   "Warning: %s must be instantiated with _[%s] but we do not enforce it"
380                   (CicPp.ppterm t)
381                   (String.concat "; "
382                     (List.map
383                       (fun (s, term) -> s ^ " := " ^ CicNotationPtPp.pp_term term)
384                       subst))));
385 *)
386                 t
387             | _ ->
388               raise (Invalid_choice (lazy "??? Can this happen?"))
389            with 
390              CicEnvironment.CircularDependency _ -> 
391                raise (Invalid_choice (lazy "Circular dependency in the environment"))))
392     | CicNotationPt.Implicit -> Cic.Implicit None
393     | CicNotationPt.UserInput -> Cic.Implicit (Some `Hole)
394     | CicNotationPt.Num (num, i) -> resolve env (Num i) ~num ()
395     | CicNotationPt.Meta (index, subst) ->
396         let cic_subst =
397           List.map
398             (function
399                 None -> None
400               | Some term -> Some (aux ~localize loc context term))
401             subst
402         in
403         Cic.Meta (index, cic_subst)
404     | CicNotationPt.Sort `Prop -> Cic.Sort Cic.Prop
405     | CicNotationPt.Sort `Set -> Cic.Sort Cic.Set
406     | CicNotationPt.Sort (`Type u) -> Cic.Sort (Cic.Type u)
407     | CicNotationPt.Sort `CProp -> Cic.Sort Cic.CProp
408     | CicNotationPt.Symbol (symbol, instance) ->
409         resolve env (Symbol (symbol, instance)) ()
410     | _ -> assert false (* god bless Bologna *)
411   and aux_option ~localize loc (context: Cic.name list) annotation = function
412     | None -> Cic.Implicit annotation
413     | Some term -> aux ~localize loc context term
414   in
415    aux ~localize:true HExtlib.dummy_floc context ast
416
417 let interpretate_path ~context path =
418  let localization_tbl = Cic.CicHash.create 23 in
419   (* here we are throwing away useful localization informations!!! *)
420   fst (
421    interpretate_term ~context ~env:Environment.empty ~uri:None ~is_path:true
422     path ~localization_tbl, localization_tbl)
423
424 let interpretate_obj ~context ~env ~uri ~is_path obj ~localization_tbl =
425  assert (context = []);
426  assert (is_path = false);
427  let interpretate_term = interpretate_term ~localization_tbl in
428  match obj with
429   | CicNotationPt.Inductive (params,tyl) ->
430      let uri = match uri with Some uri -> uri | None -> assert false in
431      let context,params =
432       let context,res =
433        List.fold_left
434         (fun (context,res) (name,t) ->
435           Cic.Name name :: context,
436           (name, interpretate_term context env None false t)::res
437         ) ([],[]) params
438       in
439        context,List.rev res in
440      let add_params =
441       List.fold_right
442        (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
443      let name_to_uris =
444       snd (
445        List.fold_left
446         (*here the explicit_named_substituion is assumed to be of length 0 *)
447         (fun (i,res) (name,_,_,_) ->
448           i + 1,(name,name,Cic.MutInd (uri,i,[]))::res
449         ) (0,[]) tyl) in
450      let con_env = DisambiguateTypes.env_of_list name_to_uris env in
451      let tyl =
452       List.map
453        (fun (name,b,ty,cl) ->
454          let ty' = add_params (interpretate_term context env None false ty) in
455          let cl' =
456           List.map
457            (fun (name,ty) ->
458              let ty' =
459               add_params (interpretate_term context con_env None false ty)
460              in
461               name,ty'
462            ) cl
463          in
464           name,b,ty',cl'
465        ) tyl
466      in
467       Cic.InductiveDefinition (tyl,[],List.length params,[])
468   | CicNotationPt.Record (params,name,ty,fields) ->
469      let uri = match uri with Some uri -> uri | None -> assert false in
470      let context,params =
471       let context,res =
472        List.fold_left
473         (fun (context,res) (name,t) ->
474           (Cic.Name name :: context),
475           (name, interpretate_term context env None false t)::res
476         ) ([],[]) params
477       in
478        context,List.rev res in
479      let add_params =
480       List.fold_right
481        (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
482      let ty' = add_params (interpretate_term context env None false ty) in
483      let fields' =
484       snd (
485        List.fold_left
486         (fun (context,res) (name,ty,_coercion) ->
487           let context' = Cic.Name name :: context in
488            context',(name,interpretate_term context env None false ty)::res
489         ) (context,[]) fields) in
490      let concl =
491       (*here the explicit_named_substituion is assumed to be of length 0 *)
492       let mutind = Cic.MutInd (uri,0,[]) in
493       if params = [] then mutind
494       else
495        Cic.Appl
496         (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
497      let con =
498       List.fold_left
499        (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
500        concl fields' in
501      let con' = add_params con in
502      let tyl = [name,true,ty',["mk_" ^ name,con']] in
503      let field_names = List.map (fun (x,_,y) -> x,y) fields in
504       Cic.InductiveDefinition
505        (tyl,[],List.length params,[`Class (`Record field_names)])
506   | CicNotationPt.Theorem (flavour, name, ty, bo) ->
507      let attrs = [`Flavour flavour] in
508      let ty' = interpretate_term [] env None false ty in
509      (match bo,flavour with
510         None,`Axiom ->
511          Cic.Constant (name,None,ty',[],attrs)
512       | Some bo,`Axiom -> assert false
513       | None,_ ->
514          Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
515       | Some bo,_ ->
516          let bo' = Some (interpretate_term [] env None false bo) in
517           Cic.Constant (name,bo',ty',[],attrs))
518           
519
520   (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
521 let rev_uniq =
522   let module SortedItem =
523     struct
524       type t = DisambiguateTypes.domain_item
525       let compare = Pervasives.compare
526     end
527   in
528   let module Map = Map.Make (SortedItem) in
529   fun l ->
530     let rev_l = List.rev l in
531     let (members, uniq_rev_l) =
532       List.fold_left
533         (fun (members, rev_l) (loc,elt) ->
534           try 
535             let locs = Map.find elt members in
536             if List.mem loc locs then
537               members, rev_l
538             else
539               Map.add elt (loc::locs) members, rev_l
540           with
541           | Not_found -> Map.add elt [loc] members, elt :: rev_l)
542         (Map.empty, []) rev_l
543     in
544     List.rev_map 
545       (fun e -> try Map.find e members,e with Not_found -> assert false)
546       uniq_rev_l
547
548 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
549  * Domain item more in deep in the list will be processed first.
550  *)
551 let rec domain_rev_of_term ?(loc = HExtlib.dummy_floc) context = function
552   | CicNotationPt.AttributedTerm (`Loc loc, term) ->
553      domain_rev_of_term ~loc context term
554   | CicNotationPt.AttributedTerm (_, term) ->
555       domain_rev_of_term ~loc context term
556   | CicNotationPt.Appl terms ->
557       List.fold_left
558        (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
559   | CicNotationPt.Binder (kind, (var, typ), body) ->
560       let kind_dom =
561         match kind with
562         | `Exists -> [ loc, Symbol ("exists", 0) ]
563         | _ -> []
564       in
565       let type_dom = domain_rev_of_term_option loc context typ in
566       let body_dom =
567         domain_rev_of_term ~loc
568           (CicNotationUtil.cic_name_of_name var :: context) body
569       in
570       body_dom @ type_dom @ kind_dom
571   | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
572       let term_dom = domain_rev_of_term ~loc context term in
573       let outtype_dom = domain_rev_of_term_option loc context outtype in
574       let get_first_constructor = function
575         | [] -> []
576         | ((head, _, _), _) :: _ -> [ loc, Id head ]
577       in
578       let do_branch ((head, _, args), term) =
579         let (term_context, args_domain) =
580           List.fold_left
581             (fun (cont, dom) (name, typ) ->
582               (CicNotationUtil.cic_name_of_name name :: cont,
583                (match typ with
584                | None -> dom
585                | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
586             (context, []) args
587         in
588         args_domain @ domain_rev_of_term ~loc term_context term
589       in
590       let branches_dom =
591         List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
592       in
593       branches_dom @ outtype_dom @ term_dom @
594       (match indty_ident with
595        | None -> get_first_constructor branches
596        | Some (ident, _) -> [ loc, Id ident ])
597   | CicNotationPt.Cast (term, ty) ->
598       let term_dom = domain_rev_of_term ~loc context term in
599       let ty_dom = domain_rev_of_term ~loc context ty in
600       ty_dom @ term_dom
601   | CicNotationPt.LetIn ((var, typ), body, where) ->
602       let body_dom = domain_rev_of_term ~loc context body in
603       let type_dom = domain_rev_of_term_option loc context typ in
604       let where_dom =
605         domain_rev_of_term ~loc
606           (CicNotationUtil.cic_name_of_name var :: context) where
607       in
608       where_dom @ type_dom @ body_dom
609   | CicNotationPt.LetRec (kind, defs, where) ->
610       let context' =
611         List.fold_left
612           (fun acc ((var, typ), _, _) ->
613             CicNotationUtil.cic_name_of_name var :: acc)
614           context defs
615       in
616       let where_dom = domain_rev_of_term ~loc context' where in
617       let defs_dom =
618         List.fold_left
619           (fun dom ((_, typ), body, _) ->
620             domain_rev_of_term ~loc context' body @
621             domain_rev_of_term_option loc context typ)
622           [] defs
623       in
624       where_dom @ defs_dom
625   | CicNotationPt.Ident (name, subst) ->
626       (try
627         (* the next line can raise Not_found *)
628         ignore(find_in_context name context);
629         if subst <> None then
630           CicNotationPt.fail loc "Explicit substitutions not allowed here"
631         else
632           []
633       with Not_found ->
634         (match subst with
635         | None -> [loc, Id name]
636         | Some subst ->
637             List.fold_left
638               (fun dom (_, term) ->
639                 let dom' = domain_rev_of_term ~loc context term in
640                 dom' @ dom)
641               [loc, Id name] subst))
642   | CicNotationPt.Uri _ -> []
643   | CicNotationPt.Implicit -> []
644   | CicNotationPt.Num (num, i) -> [loc, Num i ]
645   | CicNotationPt.Meta (index, local_context) ->
646       List.fold_left
647        (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
648         local_context
649   | CicNotationPt.Sort _ -> []
650   | CicNotationPt.Symbol (symbol, instance) -> [loc, Symbol (symbol, instance) ]
651   | CicNotationPt.UserInput
652   | CicNotationPt.Literal _
653   | CicNotationPt.Layout _
654   | CicNotationPt.Magic _
655   | CicNotationPt.Variable _ -> assert false
656
657 and domain_rev_of_term_option loc context = function
658   | None -> []
659   | Some t -> domain_rev_of_term ~loc context t
660
661 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
662
663 let domain_of_obj ~context ast =
664  assert (context = []);
665  let domain_rev =
666   match ast with
667    | CicNotationPt.Theorem (_,_,ty,bo) ->
668       (match bo with
669           None -> []
670         | Some bo -> domain_rev_of_term [] bo) @
671       domain_rev_of_term [] ty
672    | CicNotationPt.Inductive (params,tyl) ->
673       let dom =
674        List.flatten (
675         List.rev_map
676          (fun (_,_,ty,cl) ->
677            List.flatten (
678             List.rev_map
679              (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
680             domain_rev_of_term [] ty) tyl) in
681       let dom = 
682        List.fold_left
683         (fun dom (_,ty) ->
684           domain_rev_of_term [] ty @ dom
685         ) dom params
686       in
687        List.filter
688         (fun (_,name) ->
689           not (  List.exists (fun (name',_) -> name = Id name') params
690               || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
691         ) dom
692    | CicNotationPt.Record (params,_,ty,fields) ->
693       let dom =
694        List.flatten
695         (List.rev_map (fun (_,ty,_) -> domain_rev_of_term [] ty) fields) in
696       let dom =
697        List.fold_left
698         (fun dom (_,ty) ->
699           domain_rev_of_term [] ty @ dom
700         ) (dom @ domain_rev_of_term [] ty) params
701       in
702        List.filter
703         (fun (_,name) ->
704           not (  List.exists (fun (name',_) -> name = Id name') params
705               || List.exists (fun (name',_,_) -> name = Id name') fields)
706         ) dom
707  in
708   rev_uniq domain_rev
709
710   (* dom1 \ dom2 *)
711 let domain_diff dom1 dom2 =
712 (* let domain_diff = Domain.diff *)
713   let is_in_dom2 =
714     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
715       (fun _ -> false) dom2
716   in
717   List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
718
719 module type Disambiguator =
720 sig
721   val disambiguate_term :
722     ?fresh_instances:bool ->
723     dbd:HMysql.dbd ->
724     context:Cic.context ->
725     metasenv:Cic.metasenv ->
726     ?initial_ugraph:CicUniv.universe_graph -> 
727     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
728     universe:DisambiguateTypes.multiple_environment option ->
729     CicNotationPt.term disambiguator_input ->
730     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
731      Cic.metasenv *                  (* new metasenv *)
732      Cic.term*
733      CicUniv.universe_graph) list *  (* disambiguated term *)
734     bool
735
736   val disambiguate_obj :
737     ?fresh_instances:bool ->
738     dbd:HMysql.dbd ->
739     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
740     universe:DisambiguateTypes.multiple_environment option ->
741     uri:UriManager.uri option ->     (* required only for inductive types *)
742     CicNotationPt.obj disambiguator_input ->
743     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
744      Cic.metasenv *                  (* new metasenv *)
745      Cic.obj *
746      CicUniv.universe_graph) list *  (* disambiguated obj *)
747     bool
748 end
749
750 module Make (C: Callbacks) =
751   struct
752     let choices_of_id dbd id =
753       let uris = Whelp.locate ~dbd id in
754       let uris =
755        match uris with
756         | [] ->
757            (match 
758              (C.input_or_locate_uri 
759                ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ()) 
760            with
761            | None -> []
762            | Some uri -> [uri])
763         | [uri] -> [uri]
764         | _ ->
765             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
766              ~ok:"Try selected." ~enable_button_for_non_vars:true
767              ~title:"Ambiguous input." ~id
768              ~msg: ("Ambiguous input \"" ^ id ^
769                 "\". Please, choose one or more interpretations:")
770              uris
771       in
772       List.map
773         (fun uri ->
774           (UriManager.string_of_uri uri,
775            let term =
776              try
777                CicUtil.term_of_uri uri
778              with exn ->
779                debug_print (lazy (UriManager.string_of_uri uri));
780                debug_print (lazy (Printexc.to_string exn));
781                assert false
782             in
783            fun _ _ _ -> term))
784         uris
785
786 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
787
788     let disambiguate_thing ~dbd ~context ~metasenv
789       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
790       ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing 
791       (thing_txt,thing_txt_prefix_len,thing)
792     =
793       debug_print (lazy "DISAMBIGUATE INPUT");
794       let disambiguate_context =  (* cic context -> disambiguate context *)
795         List.map
796           (function None -> Cic.Anonymous | Some (name, _) -> name)
797           context
798       in
799       debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
800       let thing_dom = domain_of_thing ~context:disambiguate_context thing in
801       debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
802         (string_of_domain (List.map snd thing_dom))));
803 (*
804       debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
805         (DisambiguatePp.pp_environment aliases)));
806       debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
807         (match universe with None -> "None" | Some _ -> "Some _")));
808 *)
809       let current_dom =
810         Environment.fold (fun item _ dom -> item :: dom) aliases []
811       in
812       let todo_dom = domain_diff thing_dom current_dom in
813       (* (2) lookup function for any item (Id/Symbol/Num) *)
814       let lookup_choices =
815         fun item ->
816           let choices =
817             let lookup_in_library () =
818               match item with
819               | Id id -> choices_of_id dbd id
820               | Symbol (symb, _) ->
821                   List.map DisambiguateChoices.mk_choice
822                     (TermAcicContent.lookup_interpretations symb)
823               | Num instance ->
824                   DisambiguateChoices.lookup_num_choices ()
825             in
826             match universe with
827             | None -> lookup_in_library ()
828             | Some e ->
829                 (try
830                   let item =
831                     match item with
832                     | Symbol (symb, _) -> Symbol (symb, 0)
833                     | item -> item
834                   in
835                   Environment.find item e
836                 with Not_found -> lookup_in_library ())
837           in
838           choices
839       in
840 (*
841       (* <benchmark> *)
842       let _ =
843         if benchmark then begin
844           let per_item_choices =
845             List.map
846               (fun dom_item ->
847                 try
848                   let len = List.length (lookup_choices dom_item) in
849                   debug_print (lazy (sprintf "BENCHMARK %s: %d"
850                     (string_of_domain_item dom_item) len));
851                   len
852                 with No_choices _ -> 0)
853               thing_dom
854           in
855           max_refinements := List.fold_left ( * ) 1 per_item_choices;
856           actual_refinements := 0;
857           domain_size := List.length thing_dom;
858           choices_avg :=
859             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
860         end
861       in
862       (* </benchmark> *)
863 *)
864
865       (* (3) test an interpretation filling with meta uninterpreted identifiers
866        *)
867       let test_env aliases todo_dom ugraph = 
868         let filled_env =
869           List.fold_left
870             (fun env (_,item) ->
871                Environment.add item
872                ("Implicit",
873                  (match item with
874                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
875                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
876             aliases todo_dom 
877         in
878         try
879           let localization_tbl = Cic.CicHash.create 503 in
880           let cic_thing =
881             interpretate_thing ~context:disambiguate_context ~env:filled_env
882              ~uri ~is_path:false thing ~localization_tbl
883           in
884 let foo () =
885           let k,ugraph1 =
886            refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
887           in
888             (k , ugraph1 )
889 in refine_profiler.HExtlib.profile foo ()
890         with
891         | Try_again msg -> Uncertain (None,msg), ugraph
892         | Invalid_choice msg -> Ko (None,msg), ugraph
893       in
894       (* (4) build all possible interpretations *)
895       let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
896       let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
897         match todo_dom with
898         | [] ->
899             assert (lookup_in_todo_dom = None);
900             (match test_env aliases [] base_univ with
901             | Ok (thing, metasenv),new_univ -> 
902                [ aliases, diff, metasenv, thing, new_univ ], []
903             | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
904         | (locs,item) :: remaining_dom ->
905             debug_print (lazy (sprintf "CHOOSED ITEM: %s"
906              (string_of_domain_item item)));
907             let choices =
908              match lookup_in_todo_dom with
909                 None -> lookup_choices item
910               | Some choices -> choices in
911             match choices with
912                [] ->
913                 [], [Some (List.hd locs),
914                      lazy ("No choices for " ^ string_of_domain_item item)]
915              | [codomain_item] ->
916                  (* just one choice. We perform a one-step look-up and
917                     if the next set of choices is also a singleton we
918                     skip this refinement step *)
919                  debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
920                  let new_env = Environment.add item codomain_item aliases in
921                  let new_diff = (item,codomain_item)::diff in
922                  let lookup_in_todo_dom,next_choice_is_single =
923                   match remaining_dom with
924                      [] -> None,false
925                    | (_,he)::_ ->
926                       let choices = lookup_choices he in
927                        Some choices,List.length choices = 1
928                  in
929                   if next_choice_is_single then
930                    aux new_env new_diff lookup_in_todo_dom remaining_dom
931                     base_univ
932                   else
933                     (match test_env new_env remaining_dom base_univ with
934                     | Ok (thing, metasenv),new_univ ->
935                         (match remaining_dom with
936                         | [] ->
937                            [ new_env, new_diff, metasenv, thing, new_univ ], []
938                         | _ ->
939                            aux new_env new_diff lookup_in_todo_dom
940                             remaining_dom new_univ)
941                     | Uncertain (loc,msg),new_univ ->
942                         (match remaining_dom with
943                         | [] -> [], [loc,msg]
944                         | _ ->
945                            aux new_env new_diff lookup_in_todo_dom
946                             remaining_dom new_univ)
947                     | Ko (loc,msg),_ -> [], [loc,msg])
948              | _::_ ->
949                let rec filter univ = function 
950                 | [] -> [],[]
951                 | codomain_item :: tl ->
952                     debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
953                     let new_env = Environment.add item codomain_item aliases in
954                     let new_diff = (item,codomain_item)::diff in
955                     (match test_env new_env remaining_dom univ with
956                     | Ok (thing, metasenv),new_univ ->
957                         (match remaining_dom with
958                         | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
959                         | _ -> aux new_env new_diff None remaining_dom new_univ
960                         ) @@ 
961                           filter univ tl
962                     | Uncertain (loc,msg),new_univ ->
963                         (match remaining_dom with
964                         | [] -> [],[loc,msg]
965                         | _ -> aux new_env new_diff None remaining_dom new_univ
966                         ) @@ 
967                           filter univ tl
968                     | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
969                in
970                 filter base_univ choices
971       in
972       let base_univ = initial_ugraph in
973       try
974         let res =
975          match aux aliases [] None todo_dom base_univ with
976          | [],errors -> raise (NoWellTypedInterpretation (0,errors))
977          | [_,diff,metasenv,t,ugraph],_ ->
978              debug_print (lazy "SINGLE INTERPRETATION");
979              [diff,metasenv,t,ugraph], false
980          | l,_ ->
981              debug_print 
982                (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
983              let choices =
984                List.map
985                  (fun (env, _, _, _, _) ->
986                    List.map
987                      (fun (locs,domain_item) ->
988                        let description =
989                          fst (Environment.find domain_item env)
990                        in
991                        locs,descr_of_domain_item domain_item, description)
992                      thing_dom)
993                  l
994              in
995              let choosed = 
996                C.interactive_interpretation_choice 
997                  thing_txt thing_txt_prefix_len choices 
998              in
999              (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1000               true
1001         in
1002          res
1003      with
1004       CicEnvironment.CircularDependency s -> 
1005         failwith "Disambiguate: circular dependency"
1006
1007     let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1008       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe 
1009       (text,prefix_len,term)
1010     =
1011       let term =
1012         if fresh_instances then CicNotationUtil.freshen_term term else term
1013       in
1014       disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1015         ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1016         ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1017         ~refine_thing:refine_term (text,prefix_len,term)
1018
1019     let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1020      (text,prefix_len,obj)
1021     =
1022       let obj =
1023         if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1024       in
1025       disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1026         ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1027         ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1028         (text,prefix_len,obj)
1029   end
1030