]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
1. useless code (undebrujin) removed from disambiguate.ml
[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 tyl =
449       List.map
450        (fun (name,b,ty,cl) ->
451          let ty' = add_params (interpretate_term context env None false ty) in
452          let cl' =
453           List.map
454            (fun (name,ty) ->
455              let ty' =
456               add_params (interpretate_term context con_env None false ty)
457              in
458               name,ty'
459            ) cl
460          in
461           name,b,ty',cl'
462        ) tyl
463      in
464       Cic.InductiveDefinition (tyl,[],List.length params,[])
465   | CicNotationPt.Record (params,name,ty,fields) ->
466      let uri = match uri with Some uri -> uri | None -> assert false in
467      let context,params =
468       let context,res =
469        List.fold_left
470         (fun (context,res) (name,t) ->
471           (Cic.Name name :: context),
472           (name, interpretate_term context env None false t)::res
473         ) ([],[]) params
474       in
475        context,List.rev res in
476      let add_params =
477       List.fold_right
478        (fun (name,ty) t -> Cic.Prod (Cic.Name name,ty,t)) params in
479      let ty' = add_params (interpretate_term context env None false ty) in
480      let fields' =
481       snd (
482        List.fold_left
483         (fun (context,res) (name,ty,_coercion) ->
484           let context' = Cic.Name name :: context in
485            context',(name,interpretate_term context env None false ty)::res
486         ) (context,[]) fields) in
487      let concl =
488       (*here the explicit_named_substituion is assumed to be of length 0 *)
489       let mutind = Cic.MutInd (uri,0,[]) in
490       if params = [] then mutind
491       else
492        Cic.Appl
493         (mutind::CicUtil.mk_rels (List.length params) (List.length fields)) in
494      let con =
495       List.fold_left
496        (fun t (name,ty) -> Cic.Prod (Cic.Name name,ty,t))
497        concl fields' in
498      let con' = add_params con in
499      let tyl = [name,true,ty',["mk_" ^ name,con']] in
500      let field_names = List.map (fun (x,_,y) -> x,y) fields in
501       Cic.InductiveDefinition
502        (tyl,[],List.length params,[`Class (`Record field_names)])
503   | CicNotationPt.Theorem (flavour, name, ty, bo) ->
504      let attrs = [`Flavour flavour] in
505      let ty' = interpretate_term [] env None false ty in
506      (match bo with
507         None ->
508          Cic.CurrentProof (name,[],Cic.Implicit None,ty',[],attrs)
509       | Some bo ->
510          let bo' = Some (interpretate_term [] env None false bo) in
511           Cic.Constant (name,bo',ty',[],attrs))
512           
513
514   (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
515 let rev_uniq =
516   let module SortedItem =
517     struct
518       type t = DisambiguateTypes.domain_item
519       let compare = Pervasives.compare
520     end
521   in
522   let module Set = Set.Make (SortedItem) in
523   fun l ->
524     let rev_l = List.rev l in
525     let (_, uniq_rev_l) =
526       List.fold_left
527         (fun (members, rev_l) elt ->
528           if Set.mem elt members then
529             (members, rev_l)
530           else
531             Set.add elt members, elt :: rev_l)
532         (Set.empty, []) rev_l
533     in
534     List.rev uniq_rev_l
535
536 (* "aux" keeps domain in reverse order and doesn't care about duplicates.
537  * Domain item more in deep in the list will be processed first.
538  *)
539 let rec domain_rev_of_term ?(loc = dummy_floc) context = function
540   | CicNotationPt.AttributedTerm (`Loc loc, term) ->
541      domain_rev_of_term ~loc context term
542   | CicNotationPt.AttributedTerm (_, term) ->
543       domain_rev_of_term ~loc context term
544   | CicNotationPt.Appl terms ->
545       List.fold_left
546        (fun dom term -> domain_rev_of_term ~loc context term @ dom) [] terms
547   | CicNotationPt.Binder (kind, (var, typ), body) ->
548       let kind_dom =
549         match kind with
550         | `Exists -> [ Symbol ("exists", 0) ]
551         | _ -> []
552       in
553       let type_dom = domain_rev_of_term_option loc context typ in
554       let body_dom =
555         domain_rev_of_term ~loc
556           (CicNotationUtil.cic_name_of_name var :: context) body
557       in
558       body_dom @ type_dom @ kind_dom
559   | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
560       let term_dom = domain_rev_of_term ~loc context term in
561       let outtype_dom = domain_rev_of_term_option loc context outtype in
562       let get_first_constructor = function
563         | [] -> []
564         | ((head, _, _), _) :: _ -> [ Id head ]
565       in
566       let do_branch ((head, _, args), term) =
567         let (term_context, args_domain) =
568           List.fold_left
569             (fun (cont, dom) (name, typ) ->
570               (CicNotationUtil.cic_name_of_name name :: cont,
571                (match typ with
572                | None -> dom
573                | Some typ -> domain_rev_of_term ~loc cont typ @ dom)))
574             (context, []) args
575         in
576         args_domain @ domain_rev_of_term ~loc term_context term
577       in
578       let branches_dom =
579         List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
580       in
581       branches_dom @ outtype_dom @ term_dom @
582       (match indty_ident with
583        | None -> get_first_constructor branches
584        | Some (ident, _) -> [ Id ident ])
585   | CicNotationPt.Cast (term, ty) ->
586       let term_dom = domain_rev_of_term ~loc context term in
587       let ty_dom = domain_rev_of_term ~loc context ty in
588       ty_dom @ term_dom
589   | CicNotationPt.LetIn ((var, typ), body, where) ->
590       let body_dom = domain_rev_of_term ~loc context body in
591       let type_dom = domain_rev_of_term_option loc context typ in
592       let where_dom =
593         domain_rev_of_term ~loc
594           (CicNotationUtil.cic_name_of_name var :: context) where
595       in
596       where_dom @ type_dom @ body_dom
597   | CicNotationPt.LetRec (kind, defs, where) ->
598       let context' =
599         List.fold_left
600           (fun acc ((var, typ), _, _) ->
601             CicNotationUtil.cic_name_of_name var :: acc)
602           context defs
603       in
604       let where_dom = domain_rev_of_term ~loc context' where in
605       let defs_dom =
606         List.fold_left
607           (fun dom ((_, typ), body, _) ->
608             domain_rev_of_term ~loc context' body @
609             domain_rev_of_term_option loc context typ)
610           [] defs
611       in
612       where_dom @ defs_dom
613   | CicNotationPt.Ident (name, subst) ->
614       (try
615         let index = find_in_context name context in
616         if subst <> None then
617           CicNotationPt.fail loc "Explicit substitutions not allowed here"
618         else
619           []
620       with Not_found ->
621         (match subst with
622         | None -> [Id name]
623         | Some subst ->
624             List.fold_left
625               (fun dom (_, term) ->
626                 let dom' = domain_rev_of_term ~loc context term in
627                 dom' @ dom)
628               [Id name] subst))
629   | CicNotationPt.Uri _ -> []
630   | CicNotationPt.Implicit -> []
631   | CicNotationPt.Num (num, i) -> [ Num i ]
632   | CicNotationPt.Meta (index, local_context) ->
633       List.fold_left
634        (fun dom term -> domain_rev_of_term_option loc context term @ dom) []
635         local_context
636   | CicNotationPt.Sort _ -> []
637   | CicNotationPt.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
638   | CicNotationPt.UserInput
639   | CicNotationPt.Literal _
640   | CicNotationPt.Layout _
641   | CicNotationPt.Magic _
642   | CicNotationPt.Variable _ -> assert false
643
644 and domain_rev_of_term_option loc context = function
645   | None -> []
646   | Some t -> domain_rev_of_term ~loc context t
647
648 let domain_of_term ~context ast = rev_uniq (domain_rev_of_term context ast)
649
650 let domain_of_obj ~context ast =
651  assert (context = []);
652  let domain_rev =
653   match ast with
654    | CicNotationPt.Theorem (_,_,ty,bo) ->
655       (match bo with
656           None -> []
657         | Some bo -> domain_rev_of_term [] bo) @
658       domain_of_term [] ty
659    | CicNotationPt.Inductive (params,tyl) ->
660       let dom =
661        List.flatten (
662         List.rev_map
663          (fun (_,_,ty,cl) ->
664            List.flatten (
665             List.rev_map
666              (fun (_,ty) -> domain_rev_of_term [] ty) cl) @
667             domain_rev_of_term [] ty) tyl) in
668       let dom = 
669        List.fold_left
670         (fun dom (_,ty) ->
671           domain_rev_of_term [] ty @ dom
672         ) dom params
673       in
674        List.filter
675         (fun name ->
676           not (  List.exists (fun (name',_) -> name = Id name') params
677               || List.exists (fun (name',_,_,_) -> name = Id name') tyl)
678         ) dom
679    | CicNotationPt.Record (params,_,ty,fields) ->
680       let dom =
681        List.flatten
682         (List.rev_map (fun (_,ty,_) -> domain_rev_of_term [] ty) fields) in
683       let dom =
684        List.filter
685         (fun name->
686           not (  List.exists (fun (name',_) -> name = Id name') params
687               || List.exists (fun (name',_,_) -> name = Id name') fields)
688         ) dom
689       in
690        List.fold_left
691         (fun dom (_,ty) ->
692           domain_rev_of_term [] ty @ dom
693         ) (dom @ domain_rev_of_term [] ty) params
694  in
695   rev_uniq domain_rev
696
697   (* dom1 \ dom2 *)
698 let domain_diff dom1 dom2 =
699 (* let domain_diff = Domain.diff *)
700   let is_in_dom2 =
701     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
702       (fun _ -> false) dom2
703   in
704   List.filter (fun elt -> not (is_in_dom2 elt)) dom1
705
706 module type Disambiguator =
707 sig
708   val disambiguate_term :
709     ?fresh_instances:bool ->
710     dbd:HMysql.dbd ->
711     context:Cic.context ->
712     metasenv:Cic.metasenv ->
713     ?initial_ugraph:CicUniv.universe_graph -> 
714     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
715     universe:DisambiguateTypes.multiple_environment option ->
716     CicNotationPt.term ->
717     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
718      Cic.metasenv *                  (* new metasenv *)
719      Cic.term*
720      CicUniv.universe_graph) list *  (* disambiguated term *)
721     bool
722
723   val disambiguate_obj :
724     ?fresh_instances:bool ->
725     dbd:HMysql.dbd ->
726     aliases:DisambiguateTypes.environment ->(* previous interpretation status *)
727     universe:DisambiguateTypes.multiple_environment option ->
728     uri:UriManager.uri option ->     (* required only for inductive types *)
729     CicNotationPt.obj ->
730     ((DisambiguateTypes.domain_item * DisambiguateTypes.codomain_item) list *
731      Cic.metasenv *                  (* new metasenv *)
732      Cic.obj *
733      CicUniv.universe_graph) list *  (* disambiguated obj *)
734     bool
735 end
736
737 module Make (C: Callbacks) =
738   struct
739     let choices_of_id dbd id =
740       let uris = Whelp.locate ~dbd id in
741       let uris =
742        match uris with
743         | [] ->
744            [(C.input_or_locate_uri
745             ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
746         | [uri] -> [uri]
747         | _ ->
748             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
749              ~ok:"Try selected." ~enable_button_for_non_vars:true
750              ~title:"Ambiguous input." ~id
751              ~msg: ("Ambiguous input \"" ^ id ^
752                 "\". Please, choose one or more interpretations:")
753              uris
754       in
755       List.map
756         (fun uri ->
757           (UriManager.string_of_uri uri,
758            let term =
759              try
760                CicUtil.term_of_uri uri
761              with exn ->
762                debug_print (lazy (UriManager.string_of_uri uri));
763                debug_print (lazy (Printexc.to_string exn));
764                assert false
765             in
766            fun _ _ _ -> term))
767         uris
768
769 let refine_profiler = HExtlib.profile "disambiguate_thing.refine_thing"
770
771     let disambiguate_thing ~dbd ~context ~metasenv
772       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe
773       ~uri ~pp_thing ~domain_of_thing ~interpretate_thing ~refine_thing thing
774     =
775       debug_print (lazy "DISAMBIGUATE INPUT");
776       let disambiguate_context =  (* cic context -> disambiguate context *)
777         List.map
778           (function None -> Cic.Anonymous | Some (name, _) -> name)
779           context
780       in
781       debug_print (lazy ("TERM IS: " ^ (pp_thing thing)));
782       let thing_dom = domain_of_thing ~context:disambiguate_context thing in
783       debug_print (lazy (sprintf "DISAMBIGUATION DOMAIN: %s"
784         (string_of_domain thing_dom)));
785 (*
786       debug_print (lazy (sprintf "DISAMBIGUATION ENVIRONMENT: %s"
787         (DisambiguatePp.pp_environment aliases)));
788       debug_print (lazy (sprintf "DISAMBIGUATION UNIVERSE: %s"
789         (match universe with None -> "None" | Some _ -> "Some _")));
790 *)
791       let current_dom =
792         Environment.fold (fun item _ dom -> item :: dom) aliases []
793       in
794       let todo_dom = domain_diff thing_dom current_dom in
795       (* (2) lookup function for any item (Id/Symbol/Num) *)
796       let lookup_choices =
797         fun item ->
798           let choices =
799             let lookup_in_library () =
800               match item with
801               | Id id -> choices_of_id dbd id
802               | Symbol (symb, _) ->
803                   List.map DisambiguateChoices.mk_choice
804                     (TermAcicContent.lookup_interpretations symb)
805               | Num instance ->
806                   DisambiguateChoices.lookup_num_choices ()
807             in
808             match universe with
809             | None -> lookup_in_library ()
810             | Some e ->
811                 (try
812                   let item =
813                     match item with
814                     | Symbol (symb, _) -> Symbol (symb, 0)
815                     | item -> item
816                   in
817                   Environment.find item e
818                 with Not_found -> [])
819           in
820           choices
821       in
822 (*
823       (* <benchmark> *)
824       let _ =
825         if benchmark then begin
826           let per_item_choices =
827             List.map
828               (fun dom_item ->
829                 try
830                   let len = List.length (lookup_choices dom_item) in
831                   debug_print (lazy (sprintf "BENCHMARK %s: %d"
832                     (string_of_domain_item dom_item) len));
833                   len
834                 with No_choices _ -> 0)
835               thing_dom
836           in
837           max_refinements := List.fold_left ( * ) 1 per_item_choices;
838           actual_refinements := 0;
839           domain_size := List.length thing_dom;
840           choices_avg :=
841             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
842         end
843       in
844       (* </benchmark> *)
845 *)
846
847       (* (3) test an interpretation filling with meta uninterpreted identifiers
848        *)
849       let test_env aliases todo_dom ugraph = 
850         let filled_env =
851           List.fold_left
852             (fun env item ->
853                Environment.add item
854                ("Implicit",
855                  (match item with
856                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
857                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
858             aliases todo_dom 
859         in
860         try
861           let localization_tbl = Cic.CicHash.create 503 in
862           let cic_thing =
863             interpretate_thing ~context:disambiguate_context ~env:filled_env
864              ~uri ~is_path:false thing ~localization_tbl
865           in
866 let foo () =
867           let k,ugraph1 =
868            refine_thing metasenv context uri cic_thing ugraph ~localization_tbl
869           in
870             (k , ugraph1 )
871 in refine_profiler.HExtlib.profile foo ()
872         with
873         | Try_again msg -> Uncertain (None,msg), ugraph
874         | Invalid_choice msg -> Ko (None,msg), ugraph
875       in
876       (* (4) build all possible interpretations *)
877       let (@@) (l1,l2) (l1',l2') = l1@l1', l2@l2' in
878       let rec aux aliases diff lookup_in_todo_dom todo_dom base_univ =
879         match todo_dom with
880         | [] ->
881             assert (lookup_in_todo_dom = None);
882             (match test_env aliases [] base_univ with
883             | Ok (thing, metasenv),new_univ -> 
884                [ aliases, diff, metasenv, thing, new_univ ], []
885             | Ko (loc,msg),_ | Uncertain (loc,msg),_ -> [],[loc,msg])
886         | item :: remaining_dom ->
887             debug_print (lazy (sprintf "CHOOSED ITEM: %s"
888              (string_of_domain_item item)));
889             let choices =
890              match lookup_in_todo_dom with
891                 None -> lookup_choices item
892               | Some choices -> choices in
893             match choices with
894                [] ->
895                 [], [None,lazy ("No choices for " ^ string_of_domain_item item)]
896              | [codomain_item] ->
897                  (* just one choice. We perform a one-step look-up and
898                     if the next set of choices is also a singleton we
899                     skip this refinement step *)
900                  debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
901                  let new_env = Environment.add item codomain_item aliases in
902                  let new_diff = (item,codomain_item)::diff in
903                  let lookup_in_todo_dom,next_choice_is_single =
904                   match remaining_dom with
905                      [] -> None,false
906                    | he::_ ->
907                       let choices = lookup_choices he in
908                        Some choices,List.length choices = 1
909                  in
910                   if next_choice_is_single then
911                    aux new_env new_diff lookup_in_todo_dom remaining_dom
912                     base_univ
913                   else
914                     (match test_env new_env remaining_dom base_univ with
915                     | Ok (thing, metasenv),new_univ ->
916                         (match remaining_dom with
917                         | [] ->
918                            [ new_env, new_diff, metasenv, thing, new_univ ], []
919                         | _ ->
920                            aux new_env new_diff lookup_in_todo_dom
921                             remaining_dom new_univ)
922                     | Uncertain (loc,msg),new_univ ->
923                         (match remaining_dom with
924                         | [] -> [], [loc,msg]
925                         | _ ->
926                            aux new_env new_diff lookup_in_todo_dom
927                             remaining_dom new_univ)
928                     | Ko (loc,msg),_ -> [], [loc,msg])
929              | _::_ ->
930                let rec filter univ = function 
931                 | [] -> [],[]
932                 | codomain_item :: tl ->
933                     debug_print(lazy (sprintf "%s CHOSEN" (fst codomain_item)));
934                     let new_env = Environment.add item codomain_item aliases in
935                     let new_diff = (item,codomain_item)::diff in
936                     (match test_env new_env remaining_dom univ with
937                     | Ok (thing, metasenv),new_univ ->
938                         (match remaining_dom with
939                         | [] -> [ new_env, new_diff, metasenv, thing, new_univ ], []
940                         | _ -> aux new_env new_diff None remaining_dom new_univ
941                         ) @@ 
942                           filter univ tl
943                     | Uncertain (loc,msg),new_univ ->
944                         (match remaining_dom with
945                         | [] -> [],[loc,msg]
946                         | _ -> aux new_env new_diff None remaining_dom new_univ
947                         ) @@ 
948                           filter univ tl
949                     | Ko (loc,msg),_ -> ([],[loc,msg]) @@ filter univ tl)
950                in
951                 filter base_univ choices
952       in
953       let base_univ = initial_ugraph in
954       try
955         let res =
956          match aux aliases [] None todo_dom base_univ with
957          | [],errors -> raise (NoWellTypedInterpretation (0,errors))
958          | [_,diff,metasenv,t,ugraph],_ ->
959              debug_print (lazy "SINGLE INTERPRETATION");
960              [diff,metasenv,t,ugraph], false
961          | l,_ ->
962              debug_print (lazy (sprintf "MANY INTERPRETATIONS (%d)" (List.length l)));
963              let choices =
964                List.map
965                  (fun (env, _, _, _, _) ->
966                    List.map
967                      (fun domain_item ->
968                        let description =
969                          fst (Environment.find domain_item env)
970                        in
971                        (descr_of_domain_item domain_item, description))
972                      thing_dom)
973                  l
974              in
975              let choosed = C.interactive_interpretation_choice choices in
976              (List.map (fun n->let _,d,m,t,u= List.nth l n in d,m,t,u) choosed),
977               true
978         in
979          res
980      with
981       CicEnvironment.CircularDependency s -> 
982         failwith "Disambiguate: circular dependency"
983
984     let disambiguate_term ?(fresh_instances=false) ~dbd ~context ~metasenv
985       ?(initial_ugraph = CicUniv.empty_ugraph) ~aliases ~universe term
986     =
987       let term =
988         if fresh_instances then CicNotationUtil.freshen_term term else term
989       in
990       disambiguate_thing ~dbd ~context ~metasenv ~initial_ugraph ~aliases
991         ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
992         ~domain_of_thing:domain_of_term ~interpretate_thing:interpretate_term
993         ~refine_thing:refine_term term
994
995     let disambiguate_obj ?(fresh_instances=false) ~dbd ~aliases ~universe ~uri
996      obj
997     =
998       let obj =
999         if fresh_instances then CicNotationUtil.freshen_obj obj else obj
1000       in
1001       disambiguate_thing ~dbd ~context:[] ~metasenv:[] ~aliases ~universe ~uri
1002         ~pp_thing:CicNotationPp.pp_obj ~domain_of_thing:domain_of_obj
1003         ~interpretate_thing:interpretate_obj ~refine_thing:refine_obj
1004         obj
1005   end
1006