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