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