]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
Added universes handling. The PRE_UNIVERSES tag may help ;)
[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
34   (** raised when an environment is not enough informative to decide *)
35 exception Try_again
36
37 let debug = false
38 let debug_print = if debug then prerr_endline else ignore
39
40 (*
41   (** print benchmark information *)
42 let benchmark = true
43 let max_refinements = ref 0       (* benchmarking is not thread safe *)
44 let actual_refinements = ref 0
45 let domain_size = ref 0
46 let choices_avg = ref 0.
47 *)
48
49 let descr_of_domain_item = function
50  | Id s -> s
51  | Symbol (s, _) -> s
52  | Num i -> string_of_int i
53
54 type test_result =
55   | Ok of Cic.term * Cic.metasenv
56   | Ko
57   | Uncertain
58
59 let refine metasenv context term ugraph =
60 (*   if benchmark then incr actual_refinements; *)
61   let metasenv, term = 
62     CicMkImplicit.expand_implicits metasenv [] context term in
63     debug_print (sprintf "TEST_INTERPRETATION: %s" (CicPp.ppterm term));
64     try
65       let term', _, metasenv',ugraph1 = 
66         CicRefine.type_of_aux' metasenv context term ugraph in
67         (Ok (term', metasenv')),ugraph1
68     with
69       | CicRefine.Uncertain _ ->
70           debug_print ("%%% UNCERTAIN!!! " ^ CicPp.ppterm term) ;
71           Uncertain,ugraph
72       | CicRefine.RefineFailure _ ->
73           debug_print ("%%% PRUNED!!! " ^ CicPp.ppterm term) ;
74           Ko,ugraph
75       | CicUnification.UnificationFailure s -> 
76          prerr_endline ("PASSADI QUI: " ^ s);
77            raise ( CicUnification.UnificationFailure s )
78
79 let resolve (env: environment) (item: domain_item) ?(num = "") ?(args = []) () =
80   try
81     snd (Environment.find item env) env num args
82   with Not_found -> assert false
83
84   (* TODO move it to Cic *)
85 let find_in_environment name context =
86   let rec aux acc = function
87     | [] -> raise Not_found
88     | Cic.Name hd :: tl when hd = name -> acc
89     | _ :: tl ->  aux (acc + 1) tl
90   in
91   aux 1 context
92
93 let interpretate ~context ~env ast =
94   let rec aux loc context = function
95     | CicAst.AttributedTerm (`Loc loc, term) ->
96         aux loc context term
97     | CicAst.AttributedTerm (_, term) -> aux loc context term
98     | CicAst.Appl (CicAst.Symbol (symb, i) :: args) ->
99         let cic_args = List.map (aux loc context) args in
100         resolve env (Symbol (symb, i)) ~args:cic_args ()
101     | CicAst.Appl terms -> Cic.Appl (List.map (aux loc context) terms)
102     | CicAst.Binder (binder_kind, (var, typ), body) ->
103         let cic_type = aux_option loc context typ in
104         let cic_body = aux loc (var :: context) body in
105         (match binder_kind with
106         | `Lambda -> Cic.Lambda (var, cic_type, cic_body)
107         | `Pi | `Forall -> Cic.Prod (var, cic_type, cic_body)
108         | `Exists ->
109             resolve env (Symbol ("exists", 0))
110               ~args:[ cic_type; Cic.Lambda (var, cic_type, cic_body) ] ())
111     | CicAst.Case (term, indty_ident, outtype, branches) ->
112         let cic_term = aux loc context term in
113         let cic_outtype = aux_option loc context outtype in
114         let do_branch ((head, args), term) =
115           let rec do_branch' context = function
116             | [] -> aux loc context term
117             | (name, typ) :: tl ->
118                 let cic_body = do_branch' (name :: context) tl in
119                 let typ =
120                   match typ with
121                   | None -> Cic.Implicit (Some `Type)
122                   | Some typ -> aux loc context typ
123                 in
124                 Cic.Lambda (name, typ, cic_body)
125           in
126           do_branch' context args
127         in
128         let (indtype_uri, indtype_no) =
129           match indty_ident with
130           | Some indty_ident ->
131               (match resolve env (Id indty_ident) () with
132               | Cic.MutInd (uri, tyno, _) -> (uri, tyno)
133               | Cic.Implicit _ -> raise Try_again
134               | _ -> raise DisambiguateChoices.Invalid_choice)
135           | None ->
136               let fst_constructor =
137                 match branches with
138                 | ((head, _), _) :: _ -> head
139                 | [] -> raise DisambiguateChoices.Invalid_choice
140               in
141               (match resolve env (Id fst_constructor) () with
142               | Cic.MutConstruct (indtype_uri, indtype_no, _, _) ->
143                   (indtype_uri, indtype_no)
144               | Cic.Implicit _ -> raise Try_again
145               | _ -> raise DisambiguateChoices.Invalid_choice)
146         in
147         Cic.MutCase (indtype_uri, indtype_no, cic_outtype, cic_term,
148           (List.map do_branch branches))
149     | CicAst.LetIn ((name, typ), def, body) ->
150         let cic_def = aux loc context def in
151         let cic_def =
152           match typ with
153           | None -> cic_def
154           | Some t -> Cic.Cast (cic_def, aux loc context t)
155         in
156         let cic_body = aux loc (name :: context) body in
157         Cic.LetIn (name, cic_def, cic_body)
158     | CicAst.LetRec (kind, defs, body) ->
159         let context' =
160           List.fold_left (fun acc ((name, _), _, _) -> name :: acc)
161             context defs
162         in
163         let cic_body = aux loc context' body in
164         let inductiveFuns =
165           List.map
166             (fun ((name, typ), body, decr_idx) ->
167               let cic_body = aux loc context' body in
168               let cic_type = aux_option loc context typ in
169               let name =
170                 match name with
171                 | Cic.Anonymous ->
172                     CicTextualParser2.fail loc
173                       "Recursive functions cannot be anonymous"
174                 | Cic.Name name -> name
175               in
176               (name, decr_idx, cic_type, cic_body))
177             defs
178         in
179         let counter = ref ~-1 in
180         let build_term funs =
181           (* this is the body of the fold_right function below. Rationale: Fix
182            * and CoFix cases differs only in an additional index in the
183            * inductiveFun list, see Cic.term *)
184           match kind with
185           | `Inductive ->
186               (fun (var, _, _, _) cic ->
187                 incr counter;
188                 Cic.LetIn (Cic.Name var, Cic.Fix (!counter, funs), cic))
189           | `CoInductive ->
190               let funs =
191                 List.map (fun (name, _, typ, body) -> (name, typ, body)) funs
192               in
193               (fun (var, _, _, _) cic ->
194                 incr counter;
195                 Cic.LetIn (Cic.Name var, Cic.CoFix (!counter, funs), cic))
196         in
197         List.fold_right (build_term inductiveFuns) inductiveFuns cic_body
198     | CicAst.Ident (name, subst) ->
199         (try
200           let index = find_in_environment name context in
201           if subst <> None then
202             CicTextualParser2.fail loc
203               "Explicit substitutions not allowed here";
204           Cic.Rel index
205         with Not_found ->
206           let cic = resolve env (Id name) () in
207           let mk_subst uris =
208             let ids_to_uris =
209               List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
210             in
211             (match subst with
212             | Some subst ->
213                 List.map
214                   (fun (s, term) ->
215                     (try
216                       List.assoc s ids_to_uris, aux loc context term
217                      with Not_found ->
218                        raise DisambiguateChoices.Invalid_choice))
219                   subst
220             | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
221           in
222           (* the try is for CicTypeChecker.typecheck *)
223           (try 
224             match cic with
225             | Cic.Const (uri, []) ->
226                 let uris =
227                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
228                   match o with
229                   (*match CicTypeChecker.typecheck uri with*)
230                   | Cic.Constant (_, _, _, uris) -> uris
231                   | _ -> assert false
232                 in
233                 Cic.Const (uri, mk_subst uris)
234             | Cic.Var (uri, []) ->
235                 let uris =
236                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
237                   match o with
238                   (*match CicTypeChecker.typecheck uri with*)
239                   | Cic.Variable (_, _, _, uris) -> uris
240                   | _ -> assert false
241                 in
242                 Cic.Var (uri, mk_subst uris)
243             | Cic.MutInd (uri, i, []) ->
244                 let uris =
245                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
246                   match o with
247                   (*match CicTypeChecker.typecheck uri with*)
248                   | Cic.InductiveDefinition (_, uris, _) -> uris
249                   | _ -> assert false
250                 in
251                 Cic.MutInd (uri, i, mk_subst uris)
252             | Cic.MutConstruct (uri, i, j, []) ->
253                 let uris =
254                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
255                   match o with
256                   (*match CicTypeChecker.typecheck uri with*)
257                   | Cic.InductiveDefinition (_, uris, _) -> uris
258                   | _ -> assert false
259                 in
260                 Cic.MutConstruct (uri, i, j, mk_subst uris)
261             | Cic.Meta _ | Cic.Implicit _ as t ->
262 (*
263                 prerr_endline (sprintf
264                   "Warning: %s must be instantiated with _[%s] but we do not enforce it"
265                   (CicPp.ppterm t)
266                   (String.concat "; "
267                     (List.map
268                       (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
269                       subst)));
270 *)
271                 t
272             | _ ->
273               raise DisambiguateChoices.Invalid_choice
274            with 
275              CicEnvironment.CircularDependency _ -> 
276                raise DisambiguateChoices.Invalid_choice))
277     | CicAst.Implicit -> Cic.Implicit None
278     | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
279     | CicAst.Meta (index, subst) ->
280         let cic_subst =
281           List.map
282             (function None -> None | Some term -> Some (aux loc context term))
283             subst
284         in
285         Cic.Meta (index, cic_subst)
286     | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
287     | CicAst.Sort `Set -> Cic.Sort Cic.Set
288     | CicAst.Sort `Type -> Cic.Sort (Cic.Type (CicUniv.fresh())) (* TASSI *)
289     | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
290     | CicAst.Symbol (symbol, instance) ->
291         resolve env (Symbol (symbol, instance)) ()
292     | CicAst.UserInput -> assert false
293   and aux_option loc context = function
294     | None -> Cic.Implicit (Some `Type)
295     | Some term -> aux loc context term
296   in
297   match ast with
298   | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
299   | term -> aux CicAst.dummy_floc context term
300
301 let domain_of_term ~context ast =
302     (* "aux" keeps domain in reverse order and doesn't care about duplicates.
303      * Domain item more in deep in the list will be processed first.
304      *)
305   let rec aux loc context = function
306     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
307     | CicAst.AttributedTerm (_, term) -> aux loc context term
308     | CicAst.Appl terms ->
309         List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
310     | CicAst.Binder (kind, (var, typ), body) ->
311         let kind_dom =
312           match kind with
313           | `Exists -> [ Symbol ("exists", 0) ]
314           | _ -> []
315         in
316         let type_dom = aux_option loc context typ in
317         let body_dom = aux loc (var :: context) body in
318         body_dom @ type_dom @ kind_dom
319     | CicAst.Case (term, indty_ident, outtype, branches) ->
320         let term_dom = aux loc context term in
321         let outtype_dom = aux_option loc context outtype in
322         let do_branch ((head, args), term) =
323           let (term_context, args_domain) =
324             List.fold_left
325               (fun (cont, dom) (name, typ) ->
326                 (name :: cont,
327                  (match typ with
328                  | None -> dom
329                  | Some typ -> aux loc cont typ @ dom)))
330               (context, []) args
331           in
332           args_domain @ aux loc term_context term
333         in
334         let branches_dom =
335           List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
336         in
337         branches_dom @ outtype_dom @ term_dom @
338         (match indty_ident with None -> [] | Some ident -> [ Id ident ])
339     | CicAst.LetIn ((var, typ), body, where) ->
340         let body_dom = aux loc context body in
341         let type_dom = aux_option loc context typ in
342         let where_dom = aux loc (var :: context) where in
343         where_dom @ type_dom @ body_dom
344     | CicAst.LetRec (kind, defs, where) ->
345         let context' =
346           List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
347             context defs
348         in
349         let where_dom = aux loc context' where in
350         let defs_dom =
351           List.fold_left
352             (fun dom ((_, typ), body, _) ->
353               aux loc context' body @ aux_option loc context typ)
354             [] defs
355         in
356         where_dom @ defs_dom
357     | CicAst.Ident (name, subst) ->
358         (try
359           let index = find_in_environment name context in
360           if subst <> None then
361             CicTextualParser2.fail loc
362               "Explicit substitutions not allowed here"
363           else
364             []
365         with Not_found ->
366           (match subst with
367           | None -> [Id name]
368           | Some subst ->
369               List.fold_left
370                 (fun dom (_, term) ->
371                   let dom' = aux loc context term in
372                   dom' @ dom)
373                 [Id name] subst))
374     | CicAst.Implicit -> []
375     | CicAst.Num (num, i) -> [ Num i ]
376     | CicAst.Meta (index, local_context) ->
377         List.fold_left (fun dom term -> aux_option loc context term @ dom) []
378           local_context
379     | CicAst.Sort _ -> []
380     | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
381     | CicAst.UserInput -> assert false
382
383   and aux_option loc context = function
384     | None -> []
385     | Some t -> aux loc context t
386   in
387
388     (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
389   let rev_uniq =
390     let module SortedItem =
391       struct
392         type t = DisambiguateTypes.domain_item
393         let compare = Pervasives.compare
394       end
395     in
396     let module Set = Set.Make (SortedItem) in
397     fun l ->
398       let rev_l = List.rev l in
399       let (_, uniq_rev_l) =
400         List.fold_left
401           (fun (members, rev_l) elt ->
402             if Set.mem elt members then
403               (members, rev_l)
404             else
405               Set.add elt members, elt :: rev_l)
406           (Set.empty, []) rev_l
407       in
408       List.rev uniq_rev_l
409   in
410             
411   rev_uniq
412     (match ast with
413     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
414     | term -> aux CicAst.dummy_floc context term)
415
416
417   (* dom1 \ dom2 *)
418 let domain_diff dom1 dom2 =
419 (* let domain_diff = Domain.diff *)
420   let is_in_dom2 =
421     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
422       (fun _ -> false) dom2
423   in
424   List.filter (fun elt -> not (is_in_dom2 elt)) dom1
425
426 module Make (C: Callbacks) =
427   struct
428     let choices_of_id dbd id =
429       let uris = MetadataQuery.locate ~dbd id in
430       let uris =
431        match uris with
432         | [] ->
433            [UriManager.string_of_uri (C.input_or_locate_uri
434             ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
435         | [uri] -> [uri]
436         | _ ->
437             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
438              ~ok:"Try selected." ~enable_button_for_non_vars:true
439              ~title:"Ambiguous input." ~id
440              ~msg: ("Ambiguous input \"" ^ id ^
441                 "\". Please, choose one or more interpretations:")
442              uris
443       in
444       List.map
445         (fun uri ->
446           (uri,
447            let term =
448              try
449                CicUtil.term_of_uri uri
450              with exn ->
451                prerr_endline uri;
452                prerr_endline (Printexc.to_string exn);
453                assert false
454             in
455            fun _ _ _ -> term))
456         uris
457
458     let disambiguate_term ~(dbd:Mysql.dbd) context metasenv term
459       ?(initial_ugraph = CicUniv.empty_ugraph)  ~aliases:current_env
460     =
461       debug_print "NEW DISAMBIGUATE INPUT";
462       let disambiguate_context =  (* cic context -> disambiguate context *)
463         List.map
464           (function None -> Cic.Anonymous | Some (name, _) -> name)
465           context
466       in
467       let term_dom = domain_of_term ~context:disambiguate_context term in
468       debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
469         (string_of_domain term_dom));
470       let current_dom =
471         Environment.fold (fun item _ dom -> item :: dom) current_env []
472       in
473       let todo_dom = domain_diff term_dom current_dom in
474       (* (2) lookup function for any item (Id/Symbol/Num) *)
475       let lookup_choices =
476         let id_choices = Hashtbl.create 1023 in
477         fun item ->
478         let choices =
479           match item with
480           | Id id ->
481               (try
482                 Hashtbl.find id_choices id
483               with Not_found ->
484                 let choices = choices_of_id dbd id in
485                 Hashtbl.add id_choices id choices;
486                 choices)
487           | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
488           | Num instance -> DisambiguateChoices.lookup_num_choices ()
489         in
490         if choices = [] then raise (No_choices item);
491         choices
492       in
493
494 (*
495       (* <benchmark> *)
496       let _ =
497         if benchmark then begin
498           let per_item_choices =
499             List.map
500               (fun dom_item ->
501                 try
502                   let len = List.length (lookup_choices dom_item) in
503                   prerr_endline (sprintf "BENCHMARK %s: %d"
504                     (string_of_domain_item dom_item) len);
505                   len
506                 with No_choices _ -> 0)
507               term_dom
508           in
509           max_refinements := List.fold_left ( * ) 1 per_item_choices;
510           actual_refinements := 0;
511           domain_size := List.length term_dom;
512           choices_avg :=
513             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
514         end
515       in
516       (* </benchmark> *)
517 *)
518
519       (* (3) test an interpretation filling with meta uninterpreted identifiers
520        *)
521       let test_env current_env todo_dom ugraph = 
522         let filled_env =
523           List.fold_left
524             (fun env item ->
525                Environment.add item
526                ("Implicit",
527                  (match item with
528                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
529                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
530             current_env todo_dom 
531         in
532         try
533           let cic_term =
534             interpretate ~context:disambiguate_context ~env:filled_env term
535           in
536           let k,ugraph1 = refine metasenv context cic_term ugraph in
537             (k , ugraph1 )
538         with
539         | Try_again -> Uncertain,ugraph
540         | DisambiguateChoices.Invalid_choice -> Ko,ugraph
541       in
542       (* (4) build all possible interpretations *)
543       let rec aux current_env todo_dom base_univ =
544         match todo_dom with
545         | [] ->
546             (match test_env current_env [] base_univ with
547             | Ok (term, metasenv),new_univ -> 
548                                [ current_env, metasenv, term, new_univ ]
549             | Ko,_ | Uncertain,_ -> [])
550         | item :: remaining_dom ->
551             debug_print (sprintf "CHOOSED ITEM: %s"
552              (string_of_domain_item item));
553             let choices = lookup_choices item in
554             let rec filter univ = function 
555               | [] -> []
556               | codomain_item :: tl ->
557                   debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
558                   let new_env =
559                     Environment.add item codomain_item current_env
560                   in
561                   (match test_env new_env remaining_dom univ with
562                   | Ok (term, metasenv),new_univ ->
563                       (match remaining_dom with
564                       | [] -> [ new_env, metasenv, term, new_univ ]
565                       | _ -> aux new_env remaining_dom new_univ )@ 
566                         filter univ tl
567                   | Uncertain,new_univ ->
568                       (match remaining_dom with
569                       | [] -> []
570                       | _ -> aux new_env remaining_dom new_univ )@ 
571                         filter univ tl
572                   | Ko,_ -> filter univ tl)
573             in
574             filter base_univ choices 
575       in
576       let base_univ = initial_ugraph in
577       try
578         let res =
579          match aux current_env todo_dom base_univ with
580          | [] -> raise NoWellTypedInterpretation
581          | [ e,me,t,u ] as l ->
582              debug_print "UNA SOLA SCELTA";
583              [ e,me,t,u]
584          | l ->
585              debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
586              let choices =
587                List.map
588                  (fun (env, _, _, _) ->
589                    List.map
590                      (fun domain_item ->
591                        let description =
592                          fst (Environment.find domain_item env)
593                        in
594                        (descr_of_domain_item domain_item, description))
595                      term_dom)
596                  l
597              in
598              let choosed = C.interactive_interpretation_choice choices in
599              List.map (List.nth l) choosed
600         in
601 (*
602         (if benchmark then
603           let res_size = List.length res in
604           prerr_endline (sprintf
605             ("BENCHMARK: %d/%d refinements performed, domain size %d, interps %d, k %.2f\n" ^^
606             "BENCHMARK:   estimated %.2f")
607             !actual_refinements !max_refinements !domain_size res_size
608             !choices_avg
609             (float_of_int (!domain_size - 1) *. !choices_avg *. (float_of_int res_size) +. !choices_avg)));
610 *)
611         res
612      with
613       CicEnvironment.CircularDependency s -> 
614         raise (Failure "e chi la becca sta CircularDependency?");
615   end
616