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