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