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