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