]> matita.cs.unibo.it Git - helm.git/blob - components/cic_disambiguation/disambiguate.ml
Bug fixed: a symbol alias Symb(s,0) now subsumes the case Symb(s,n) for each n.
[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 elt =
714     List.exists
715      (function
716        | Symbol (symb, 0) ->
717           (match elt with
718               Symbol (symb',_) when symb = symb' -> true
719             | _ -> false)
720        | item -> elt = item
721      ) dom2
722   in
723   List.filter (fun (_,elt) -> not (is_in_dom2 elt)) dom1
724
725 module type Disambiguator =
726 sig
727   val disambiguate_term :
728     ?fresh_instances:bool ->
729     dbd:HMysql.dbd ->
730     context:Cic.context ->
731     metasenv:Cic.metasenv ->
732     ?initial_ugraph:CicUniv.universe_graph -> 
733     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
734     universe:DisambiguateTypes.multiple_environment option ->
735     CicNotationPt.term disambiguator_input ->
736     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
737      Cic.metasenv *                  (* new metasenv *)
738      Cic.term*
739      CicUniv.universe_graph) list *  (* disambiguated term *)
740     bool
741
742   val disambiguate_obj :
743     ?fresh_instances:bool ->
744     dbd:HMysql.dbd ->
745     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
746     universe:DisambiguateTypes.multiple_environment option ->
747     uri:UriManager.uri option ->     (* required only for inductive types *)
748     CicNotationPt.obj disambiguator_input ->
749     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
750      Cic.metasenv *                  (* new metasenv *)
751      Cic.obj *
752      CicUniv.universe_graph) list *  (* disambiguated obj *)
753     bool
754 end
755
756 module Make (C: Callbacks) =
757   struct
758     let choices_of_id dbd id =
759       let uris = Whelp.locate ~dbd id in
760       let uris =
761        match uris with
762         | [] ->
763            (match 
764              (C.input_or_locate_uri 
765                ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ()) 
766            with
767            | None -> []
768            | Some uri -> [uri])
769         | [uri] -> [uri]
770         | _ ->
771             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
772              ~ok:"Try selected." ~enable_button_for_non_vars:true
773              ~title:"Ambiguous input." ~id
774              ~msg: ("Ambiguous input \"" ^ id ^
775                 "\". Please, choose one or more interpretations:")
776              uris
777       in
778       List.map
779         (fun uri ->
780           (UriManager.string_of_uri uri,
781            let term =
782              try
783                CicUtil.term_of_uri uri
784              with exn ->
785                debug_print (lazy (UriManager.string_of_uri uri));
786                debug_print (lazy (Printexc.to_string exn));
787                assert false
788             in
789            fun _ _ _ -> term))
790         uris
791
792 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
793
794     let disambiguate_thing ~dbd ~context ~metasenv
795       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
796       ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing 
797       (thing_txt,thing_txt_prefix_len,thing)
798     =
799       debug_print (lazy "DISAMBIGUATE INPUT");
800       let disambiguate_context =  (* cic context -> disambiguate context *)
801         List.map
802           (function None -> Cic.Anonymous | Some (name, _) -> name)
803           context
804       in
805       debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
806       let thing_dom = domain_of_thing ~context:disambiguate_context thing in
807       debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
808         (string_of_domain (List.map snd thing_dom))));
809 (*
810       debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
811         (DisambiguatePp.pp_environment aliases)));
812       debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
813         (match universe with None -> "None" | Some _ -> "Some _")));
814 *)
815       let current_dom =
816         Environment.fold (fun item _ dom -> item :: dom) aliases []
817       in
818       let todo_dom = domain_diff thing_dom current_dom in
819       (* (2) lookup function for any item (Id/Symbol/Num) *)
820       let lookup_choices =
821         fun item ->
822           let choices =
823             let lookup_in_library () =
824               match item with
825               | Id id -> choices_of_id dbd id
826               | Symbol (symb, _) ->
827                   List.map DisambiguateChoices.mk_choice
828                     (TermAcicContent.lookup_interpretations symb)
829               | Num instance ->
830                   DisambiguateChoices.lookup_num_choices ()
831             in
832             match universe with
833             | None -> lookup_in_library ()
834             | Some e ->
835                 (try
836                   let item =
837                     match item with
838                     | Symbol (symb, _) -> Symbol (symb, 0)
839                     | item -> item
840                   in
841                   Environment.find item e
842                 with Not_found -> lookup_in_library ())
843           in
844           choices
845       in
846 (*
847       (* <benchmark> *)
848       let _ =
849         if benchmark then begin
850           let per_item_choices =
851             List.map
852               (fun dom_item ->
853                 try
854                   let len = List.length (lookup_choices dom_item) in
855                   debug_print (lazy (sprintf "BENCHMARK %s: %d"
856                     (string_of_domain_item dom_item) len));
857                   len
858                 with No_choices _ -> 0)
859               thing_dom
860           in
861           max_refinements := List.fold_left ( * ) 1 per_item_choices;
862           actual_refinements := 0;
863           domain_size := List.length thing_dom;
864           choices_avg :=
865             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
866         end
867       in
868       (* </benchmark> *)
869 *)
870
871       (* (3) test an interpretation filling with meta uninterpreted identifiers
872        *)
873       let test_env aliases todo_dom ugraph = 
874         let filled_env =
875           List.fold_left
876             (fun env (_,item) ->
877                Environment.add item
878                ("Implicit",
879                  (match item with
880                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
881                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
882             aliases todo_dom 
883         in
884         try
885           let localization_tbl = Cic.CicHash.create 503 in
886           let cic_thing =
887             interpretate_thing ~context:disambiguate_context ~env:filled_env
888              ~uri ~is_path:false thing ~localization_tbl
889           in
890 let foo () =
891           let k,ugraph1 =
892            refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
893           in
894             (k , ugraph1 )
895 in refine_profiler.HExtlib.profile foo ()
896         with
897         | Try_again msg -> Uncertain (None,msg), ugraph
898         | Invalid_choice msg -> Ko (None,msg), ugraph
899       in
900       (* (4) build all possible interpretations *)
901       let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
902       let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
903         match todo_dom with
904         | [] ->
905             assert (lookup_in_todo_dom = None);
906             (match test_env aliases [] base_univ with
907             | Ok (thing, metasenv),new_univ -> 
908                [ aliases, diff, metasenv, thing, new_univ ], []
909             | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
910         | (locs,item) :: remaining_dom ->
911             debug_print (lazy (sprintf "CHOOSED ITEM: %s"
912              (string_of_domain_item item)));
913             let choices =
914              match lookup_in_todo_dom with
915                 None -> lookup_choices item
916               | Some choices -> choices in
917             match choices with
918                [] ->
919                 [], [Some (List.hd locs),
920                      lazy ("No choices for " ^ string_of_domain_item item)]
921              | [codomain_item] ->
922                  (* just one choice. We perform a one-step look-up and
923                     if the next set of choices is also a singleton we
924                     skip this refinement step *)
925                  debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
926                  let new_env = Environment.add item codomain_item aliases in
927                  let new_diff = (item,codomain_item)::diff in
928                  let lookup_in_todo_dom,next_choice_is_single =
929                   match remaining_dom with
930                      [] -> None,false
931                    | (_,he)::_ ->
932                       let choices = lookup_choices he in
933                        Some choices,List.length choices = 1
934                  in
935                   if next_choice_is_single then
936                    aux new_env new_diff lookup_in_todo_dom remaining_dom
937                     base_univ
938                   else
939                     (match test_env new_env remaining_dom base_univ with
940                     | Ok (thing, metasenv),new_univ ->
941                         (match remaining_dom with
942                         | [] ->
943                            [ new_env, new_diff, metasenv, thing, new_univ ], []
944                         | _ ->
945                            aux new_env new_diff lookup_in_todo_dom
946                             remaining_dom new_univ)
947                     | Uncertain (loc,msg),new_univ ->
948                         (match remaining_dom with
949                         | [] -> [], [loc,msg]
950                         | _ ->
951                            aux new_env new_diff lookup_in_todo_dom
952                             remaining_dom new_univ)
953                     | Ko (loc,msg),_ -> [], [loc,msg])
954              | _::_ ->
955                let rec filter univ = function 
956                 | [] -> [],[]
957                 | codomain_item :: tl ->
958                     debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
959                     let new_env = Environment.add item codomain_item aliases in
960                     let new_diff = (item,codomain_item)::diff in
961                     (match test_env new_env remaining_dom univ with
962                     | Ok (thing, metasenv),new_univ ->
963                         (match remaining_dom with
964                         | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
965                         | _ -> aux new_env new_diff None remaining_dom new_univ
966                         ) @@ 
967                           filter univ tl
968                     | Uncertain (loc,msg),new_univ ->
969                         (match remaining_dom with
970                         | [] -> [],[loc,msg]
971                         | _ -> aux new_env new_diff None remaining_dom new_univ
972                         ) @@ 
973                           filter univ tl
974                     | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
975                in
976                 filter base_univ choices
977       in
978       let base_univ = initial_ugraph in
979       try
980         let res =
981          match aux aliases [] None todo_dom base_univ with
982          | [],errors -> raise (NoWellTypedInterpretation (0,errors))
983          | [_,diff,metasenv,t,ugraph],_ ->
984              debug_print (lazy "SINGLE INTERPRETATION");
985              [diff,metasenv,t,ugraph], false
986          | l,_ ->
987              debug_print 
988                (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
989              let choices =
990                List.map
991                  (fun (env, _, _, _, _) ->
992                    List.map
993                      (fun (locs,domain_item) ->
994                        let description =
995                          fst (Environment.find domain_item env)
996                        in
997                        locs,descr_of_domain_item domain_item, description)
998                      thing_dom)
999                  l
1000              in
1001              let choosed = 
1002                C.interactive_interpretation_choice 
1003                  thing_txt thing_txt_prefix_len choices 
1004              in
1005              (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
1006               true
1007         in
1008          res
1009      with
1010       CicEnvironment.CircularDependency s -> 
1011         failwith "Disambiguate: circular dependency"
1012
1013     let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
1014       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe 
1015       (text,prefix_len,term)
1016     =
1017       let term =
1018         if fresh_instances then CicNotationUtil.freshen_term term else term
1019       in
1020       disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
1021         ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
1022         ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
1023         ~refine_thing:refine_term (text,prefix_len,term)
1024
1025     let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
1026      (text,prefix_len,obj)
1027     =
1028       let obj =
1029         if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1030       in
1031       disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1032         ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1033         ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1034         (text,prefix_len,obj)
1035   end
1036