]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/disambiguate.ml
added syntax for URIs
[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     | CicAst.Uri (name, subst) as ast ->
200         let is_uri = function CicAst.Uri _ -> true | _ -> false in
201         (try
202           if is_uri ast then raise Not_found;(* don't search the env for URIs *)
203           let index = find_in_environment name context in
204           if subst <> None then
205             CicTextualParser2.fail loc
206               "Explicit substitutions not allowed here";
207           Cic.Rel index
208         with Not_found ->
209           let cic =
210             if is_uri ast then  (* we have the URI, build the term out of it *)
211               try
212                 CicUtil.term_of_uri name
213               with UriManager.IllFormedUri _ ->
214                 CicTextualParser2.fail loc "Ill formed URI"
215             else
216               resolve env (Id name) ()
217           in
218           let mk_subst uris =
219             let ids_to_uris =
220               List.map (fun uri -> UriManager.name_of_uri uri, uri) uris
221             in
222             (match subst with
223             | Some subst ->
224                 List.map
225                   (fun (s, term) ->
226                     (try
227                       List.assoc s ids_to_uris, aux loc context term
228                      with Not_found ->
229                        raise DisambiguateChoices.Invalid_choice))
230                   subst
231             | None -> List.map (fun uri -> uri, Cic.Implicit None) uris)
232           in
233           (* the try is for CicTypeChecker.typecheck *)
234           (try 
235             match cic with
236             | Cic.Const (uri, []) ->
237                 let uris =
238                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
239                   match o with
240                   (*match CicTypeChecker.typecheck uri with*)
241                   | Cic.Constant (_, _, _, uris) -> uris
242                   | _ -> assert false
243                 in
244                 Cic.Const (uri, mk_subst uris)
245             | Cic.Var (uri, []) ->
246                 let uris =
247                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
248                   match o with
249                   (*match CicTypeChecker.typecheck uri with*)
250                   | Cic.Variable (_, _, _, uris) -> uris
251                   | _ -> assert false
252                 in
253                 Cic.Var (uri, mk_subst uris)
254             | Cic.MutInd (uri, i, []) ->
255                 let uris =
256                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
257                   match o with
258                   (*match CicTypeChecker.typecheck uri with*)
259                   | Cic.InductiveDefinition (_, uris, _) -> uris
260                   | _ -> assert false
261                 in
262                 Cic.MutInd (uri, i, mk_subst uris)
263             | Cic.MutConstruct (uri, i, j, []) ->
264                 let uris =
265                   let o,_ = CicEnvironment.get_obj uri CicUniv.empty_ugraph in
266                   match o with
267                   (*match CicTypeChecker.typecheck uri with*)
268                   | Cic.InductiveDefinition (_, uris, _) -> uris
269                   | _ -> assert false
270                 in
271                 Cic.MutConstruct (uri, i, j, mk_subst uris)
272             | Cic.Meta _ | Cic.Implicit _ as t ->
273 (*
274                 prerr_endline (sprintf
275                   "Warning: %s must be instantiated with _[%s] but we do not enforce it"
276                   (CicPp.ppterm t)
277                   (String.concat "; "
278                     (List.map
279                       (fun (s, term) -> s ^ " := " ^ CicAstPp.pp_term term)
280                       subst)));
281 *)
282                 t
283             | _ ->
284               raise DisambiguateChoices.Invalid_choice
285            with 
286              CicEnvironment.CircularDependency _ -> 
287                raise DisambiguateChoices.Invalid_choice))
288     | CicAst.Implicit -> Cic.Implicit None
289     | CicAst.Num (num, i) -> resolve env (Num i) ~num ()
290     | CicAst.Meta (index, subst) ->
291         let cic_subst =
292           List.map
293             (function None -> None | Some term -> Some (aux loc context term))
294             subst
295         in
296         Cic.Meta (index, cic_subst)
297     | CicAst.Sort `Prop -> Cic.Sort Cic.Prop
298     | CicAst.Sort `Set -> Cic.Sort Cic.Set
299     | CicAst.Sort `Type -> Cic.Sort (Cic.Type (CicUniv.fresh())) (* TASSI *)
300     | CicAst.Sort `CProp -> Cic.Sort Cic.CProp
301     | CicAst.Symbol (symbol, instance) ->
302         resolve env (Symbol (symbol, instance)) ()
303     | CicAst.UserInput -> assert false
304   and aux_option loc context = function
305     | None -> Cic.Implicit (Some `Type)
306     | Some term -> aux loc context term
307   in
308   match ast with
309   | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
310   | term -> aux CicAst.dummy_floc context term
311
312 let domain_of_term ~context ast =
313     (* "aux" keeps domain in reverse order and doesn't care about duplicates.
314      * Domain item more in deep in the list will be processed first.
315      *)
316   let rec aux loc context = function
317     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
318     | CicAst.AttributedTerm (_, term) -> aux loc context term
319     | CicAst.Appl terms ->
320         List.fold_left (fun dom term -> aux loc context term @ dom) [] terms
321     | CicAst.Binder (kind, (var, typ), body) ->
322         let kind_dom =
323           match kind with
324           | `Exists -> [ Symbol ("exists", 0) ]
325           | _ -> []
326         in
327         let type_dom = aux_option loc context typ in
328         let body_dom = aux loc (var :: context) body in
329         body_dom @ type_dom @ kind_dom
330     | CicAst.Case (term, indty_ident, outtype, branches) ->
331         let term_dom = aux loc context term in
332         let outtype_dom = aux_option loc context outtype in
333         let do_branch ((head, args), term) =
334           let (term_context, args_domain) =
335             List.fold_left
336               (fun (cont, dom) (name, typ) ->
337                 (name :: cont,
338                  (match typ with
339                  | None -> dom
340                  | Some typ -> aux loc cont typ @ dom)))
341               (context, []) args
342           in
343           args_domain @ aux loc term_context term
344         in
345         let branches_dom =
346           List.fold_left (fun dom branch -> do_branch branch @ dom) [] branches
347         in
348         branches_dom @ outtype_dom @ term_dom @
349         (match indty_ident with None -> [] | Some ident -> [ Id ident ])
350     | CicAst.LetIn ((var, typ), body, where) ->
351         let body_dom = aux loc context body in
352         let type_dom = aux_option loc context typ in
353         let where_dom = aux loc (var :: context) where in
354         where_dom @ type_dom @ body_dom
355     | CicAst.LetRec (kind, defs, where) ->
356         let context' =
357           List.fold_left (fun acc ((var, typ), _, _) -> var :: acc)
358             context defs
359         in
360         let where_dom = aux loc context' where in
361         let defs_dom =
362           List.fold_left
363             (fun dom ((_, typ), body, _) ->
364               aux loc context' body @ aux_option loc context typ)
365             [] defs
366         in
367         where_dom @ defs_dom
368     | CicAst.Ident (name, subst) ->
369         (try
370           let index = find_in_environment name context in
371           if subst <> None then
372             CicTextualParser2.fail loc
373               "Explicit substitutions not allowed here"
374           else
375             []
376         with Not_found ->
377           (match subst with
378           | None -> [Id name]
379           | Some subst ->
380               List.fold_left
381                 (fun dom (_, term) ->
382                   let dom' = aux loc context term in
383                   dom' @ dom)
384                 [Id name] subst))
385     | CicAst.Uri _ -> []
386     | CicAst.Implicit -> []
387     | CicAst.Num (num, i) -> [ Num i ]
388     | CicAst.Meta (index, local_context) ->
389         List.fold_left (fun dom term -> aux_option loc context term @ dom) []
390           local_context
391     | CicAst.Sort _ -> []
392     | CicAst.Symbol (symbol, instance) -> [ Symbol (symbol, instance) ]
393     | CicAst.UserInput -> assert false
394
395   and aux_option loc context = function
396     | None -> []
397     | Some t -> aux loc context t
398   in
399
400     (* e.g. [5;1;1;1;2;3;4;1;2] -> [2;1;4;3;5] *)
401   let rev_uniq =
402     let module SortedItem =
403       struct
404         type t = DisambiguateTypes.domain_item
405         let compare = Pervasives.compare
406       end
407     in
408     let module Set = Set.Make (SortedItem) in
409     fun l ->
410       let rev_l = List.rev l in
411       let (_, uniq_rev_l) =
412         List.fold_left
413           (fun (members, rev_l) elt ->
414             if Set.mem elt members then
415               (members, rev_l)
416             else
417               Set.add elt members, elt :: rev_l)
418           (Set.empty, []) rev_l
419       in
420       List.rev uniq_rev_l
421   in
422             
423   rev_uniq
424     (match ast with
425     | CicAst.AttributedTerm (`Loc loc, term) -> aux loc context term
426     | term -> aux CicAst.dummy_floc context term)
427
428
429   (* dom1 \ dom2 *)
430 let domain_diff dom1 dom2 =
431 (* let domain_diff = Domain.diff *)
432   let is_in_dom2 =
433     List.fold_left (fun pred elt -> (fun elt' -> elt' = elt || pred elt'))
434       (fun _ -> false) dom2
435   in
436   List.filter (fun elt -> not (is_in_dom2 elt)) dom1
437
438 module Make (C: Callbacks) =
439   struct
440     let choices_of_id dbd id =
441       let uris = MetadataQuery.locate ~dbd id in
442       let uris =
443        match uris with
444         | [] ->
445            [UriManager.string_of_uri (C.input_or_locate_uri
446             ~title:("URI matching \"" ^ id ^ "\" unknown.") ~id ())]
447         | [uri] -> [uri]
448         | _ ->
449             C.interactive_user_uri_choice ~selection_mode:`MULTIPLE
450              ~ok:"Try selected." ~enable_button_for_non_vars:true
451              ~title:"Ambiguous input." ~id
452              ~msg: ("Ambiguous input \"" ^ id ^
453                 "\". Please, choose one or more interpretations:")
454              uris
455       in
456       List.map
457         (fun uri ->
458           (uri,
459            let term =
460              try
461                CicUtil.term_of_uri uri
462              with exn ->
463                prerr_endline uri;
464                prerr_endline (Printexc.to_string exn);
465                assert false
466             in
467            fun _ _ _ -> term))
468         uris
469
470     let disambiguate_term ~(dbd:Mysql.dbd) context metasenv term
471       ?(initial_ugraph = CicUniv.empty_ugraph)  ~aliases:current_env
472     =
473       debug_print "NEW DISAMBIGUATE INPUT";
474       let disambiguate_context =  (* cic context -> disambiguate context *)
475         List.map
476           (function None -> Cic.Anonymous | Some (name, _) -> name)
477           context
478       in
479       let term_dom = domain_of_term ~context:disambiguate_context term in
480       debug_print (sprintf "DISAMBIGUATION DOMAIN: %s"
481         (string_of_domain term_dom));
482       let current_dom =
483         Environment.fold (fun item _ dom -> item :: dom) current_env []
484       in
485       let todo_dom = domain_diff term_dom current_dom in
486       (* (2) lookup function for any item (Id/Symbol/Num) *)
487       let lookup_choices =
488         let id_choices = Hashtbl.create 1023 in
489         fun item ->
490         let choices =
491           match item with
492           | Id id ->
493               (try
494                 Hashtbl.find id_choices id
495               with Not_found ->
496                 let choices = choices_of_id dbd id in
497                 Hashtbl.add id_choices id choices;
498                 choices)
499           | Symbol (symb, _) -> DisambiguateChoices.lookup_symbol_choices symb
500           | Num instance -> DisambiguateChoices.lookup_num_choices ()
501         in
502         if choices = [] then raise (No_choices item);
503         choices
504       in
505
506 (*
507       (* <benchmark> *)
508       let _ =
509         if benchmark then begin
510           let per_item_choices =
511             List.map
512               (fun dom_item ->
513                 try
514                   let len = List.length (lookup_choices dom_item) in
515                   prerr_endline (sprintf "BENCHMARK %s: %d"
516                     (string_of_domain_item dom_item) len);
517                   len
518                 with No_choices _ -> 0)
519               term_dom
520           in
521           max_refinements := List.fold_left ( * ) 1 per_item_choices;
522           actual_refinements := 0;
523           domain_size := List.length term_dom;
524           choices_avg :=
525             (float_of_int !max_refinements) ** (1. /. float_of_int !domain_size)
526         end
527       in
528       (* </benchmark> *)
529 *)
530
531       (* (3) test an interpretation filling with meta uninterpreted identifiers
532        *)
533       let test_env current_env todo_dom ugraph = 
534         let filled_env =
535           List.fold_left
536             (fun env item ->
537                Environment.add item
538                ("Implicit",
539                  (match item with
540                     | Id _ | Num _ -> (fun _ _ _ -> Cic.Implicit (Some `Closed))
541                     | Symbol _ -> (fun _ _ _ -> Cic.Implicit None))) env)
542             current_env todo_dom 
543         in
544         try
545           let cic_term =
546             interpretate ~context:disambiguate_context ~env:filled_env term
547           in
548           let k,ugraph1 = refine metasenv context cic_term ugraph in
549             (k , ugraph1 )
550         with
551         | Try_again -> Uncertain,ugraph
552         | DisambiguateChoices.Invalid_choice -> Ko,ugraph
553       in
554       (* (4) build all possible interpretations *)
555       let rec aux current_env todo_dom base_univ =
556         match todo_dom with
557         | [] ->
558             (match test_env current_env [] base_univ with
559             | Ok (term, metasenv),new_univ -> 
560                                [ current_env, metasenv, term, new_univ ]
561             | Ko,_ | Uncertain,_ -> [])
562         | item :: remaining_dom ->
563             debug_print (sprintf "CHOOSED ITEM: %s"
564              (string_of_domain_item item));
565             let choices = lookup_choices item in
566             let rec filter univ = function 
567               | [] -> []
568               | codomain_item :: tl ->
569                   debug_print (sprintf "%s CHOSEN" (fst codomain_item)) ;
570                   let new_env =
571                     Environment.add item codomain_item current_env
572                   in
573                   (match test_env new_env remaining_dom univ with
574                   | Ok (term, metasenv),new_univ ->
575                       (match remaining_dom with
576                       | [] -> [ new_env, metasenv, term, new_univ ]
577                       | _ -> aux new_env remaining_dom new_univ )@ 
578                         filter univ tl
579                   | Uncertain,new_univ ->
580                       (match remaining_dom with
581                       | [] -> []
582                       | _ -> aux new_env remaining_dom new_univ )@ 
583                         filter univ tl
584                   | Ko,_ -> filter univ tl)
585             in
586             filter base_univ choices 
587       in
588       let base_univ = initial_ugraph in
589       try
590         let res =
591          match aux current_env todo_dom base_univ with
592          | [] -> raise NoWellTypedInterpretation
593          | [ e,me,t,u ] as l ->
594              debug_print "UNA SOLA SCELTA";
595              [ e,me,t,u]
596          | l ->
597              debug_print (sprintf "PIU' SCELTE (%d)" (List.length l));
598              let choices =
599                List.map
600                  (fun (env, _, _, _) ->
601                    List.map
602                      (fun domain_item ->
603                        let description =
604                          fst (Environment.find domain_item env)
605                        in
606                        (descr_of_domain_item domain_item, description))
607                      term_dom)
608                  l
609              in
610              let choosed = C.interactive_interpretation_choice choices in
611              List.map (List.nth l) choosed
612         in
613 (*
614         (if benchmark then
615           let res_size = List.length res in
616           prerr_endline (sprintf
617             ("BENCHMARK: %d/%d refinements performed, domain size %d, interps %d, k %.2f\n" ^^
618             "BENCHMARK:   estimated %.2f")
619             !actual_refinements !max_refinements !domain_size res_size
620             !choices_avg
621             (float_of_int (!domain_size - 1) *. !choices_avg *. (float_of_int res_size) +. !choices_avg)));
622 *)
623         res
624      with
625       CicEnvironment.CircularDependency s -> 
626         raise (Failure "e chi la becca sta CircularDependency?");
627   end
628