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