]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_disambiguation/nCicDisambiguate.ml
added some hardcoded universes, needed to typecheck the librarya
[helm.git] / helm / software / components / ng_disambiguation / nCicDisambiguate.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 (* $Id: nCic.ml 9058 2008-10-13 17:42:30Z tassi $ *)
13
14 open Printf
15
16 open DisambiguateTypes
17 open UriManager
18
19 module Ast = CicNotationPt
20 module NRef = NReference 
21
22 let debug_print _ = ();;
23 (* let debug_print s = prerr_endline (Lazy.force s);; *)
24
25 let cic_name_of_name = function
26   | Ast.Ident (n, None) ->  n
27   | _ -> assert false
28 ;;
29
30 let refine_term 
31  metasenv subst context uri ~coercion_db ~use_coercions term _ ~localization_tbl=
32   assert (uri=None);
33   debug_print (lazy (sprintf "TEST_INTERPRETATION: %s" 
34     (NCicPp.ppterm ~metasenv ~subst ~context term)));
35   try
36     let localise t = 
37       try NCicUntrusted.NCicHash.find localization_tbl t
38       with Not_found -> 
39         prerr_endline (NCicPp.ppterm ~metasenv ~subst ~context t);
40         assert false
41     in
42     let metasenv, subst, term, _ = 
43       NCicRefiner.typeof 
44         ~look_for_coercion:(
45           if use_coercions then 
46            NCicCoercion.look_for_coercion coercion_db
47           else (fun _ _ _ _ _ -> []))
48         metasenv subst context term None ~localise 
49     in
50      Disambiguate.Ok (term, metasenv, subst, ())
51   with
52   | NCicRefiner.Uncertain loc_msg ->
53       debug_print (lazy ("UNCERTAIN: [" ^ snd (Lazy.force loc_msg) ^ "] " ^ 
54         NCicPp.ppterm ~metasenv ~subst ~context term)) ;
55       Disambiguate.Uncertain loc_msg
56   | NCicRefiner.RefineFailure loc_msg ->
57       debug_print (lazy (sprintf "PRUNED:\nterm%s\nmessage:%s"
58         (NCicPp.ppterm ~metasenv ~subst ~context term) (snd(Lazy.force loc_msg))));
59       Disambiguate.Ko loc_msg
60 ;;
61
62   (* TODO move it to Cic *)
63 let find_in_context name context =
64   let rec aux acc = function
65     | [] -> raise Not_found
66     | hd :: _ when hd = name -> acc
67     | _ :: tl ->  aux (acc + 1) tl
68   in
69   aux 1 context
70
71 let interpretate_term 
72   ?(create_dummy_ids=false) ~mk_choice ~context ~env ~uri ~is_path ast 
73   ~localization_tbl 
74 =
75   (* create_dummy_ids shouldbe used only for interpretating patterns *)
76   assert (uri = None);
77
78   let rec aux ~localize loc context = function
79     | CicNotationPt.AttributedTerm (`Loc loc, term) ->
80         let res = aux ~localize loc context term in
81         if localize then 
82          NCicUntrusted.NCicHash.add localization_tbl res loc;
83        res
84     | CicNotationPt.AttributedTerm (_, term) -> aux ~localize loc context term
85     | CicNotationPt.Appl (CicNotationPt.Symbol (symb, i) :: args) ->
86         let cic_args = List.map (aux ~localize loc context) args in
87         Disambiguate.resolve ~mk_choice ~env (Symbol (symb, i)) (`Args cic_args)
88     | CicNotationPt.Appl terms ->
89        NCic.Appl (List.map (aux ~localize loc context) terms)
90     | CicNotationPt.Binder (binder_kind, (var, typ), body) ->
91         let cic_type = aux_option ~localize loc context `Type typ in
92         let cic_name = cic_name_of_name var  in
93         let cic_body = aux ~localize loc (cic_name :: context) body in
94         (match binder_kind with
95         | `Lambda -> NCic.Lambda (cic_name, cic_type, cic_body)
96         | `Pi
97         | `Forall -> NCic.Prod (cic_name, cic_type, cic_body)
98         | `Exists ->
99             Disambiguate.resolve ~env ~mk_choice (Symbol ("exists", 0))
100               (`Args [ cic_type; NCic.Lambda (cic_name, cic_type, cic_body) ]))
101     | CicNotationPt.Case (term, indty_ident, outtype, branches) ->
102         let cic_term = aux ~localize loc context term in
103         let cic_outtype = aux_option ~localize loc context `Term outtype in
104         let do_branch ((_, _, args), term) =
105          let rec do_branch' context = function
106            | [] -> aux ~localize loc context term
107            | (name, typ) :: tl ->
108                let cic_name = cic_name_of_name name in
109                let cic_body = do_branch' (cic_name :: context) tl in
110                let typ =
111                  match typ with
112                  | None -> NCic.Implicit `Type
113                  | Some typ -> aux ~localize loc context typ
114                in
115                NCic.Lambda (cic_name, typ, cic_body)
116          in
117           do_branch' context args
118         in
119         if create_dummy_ids then
120          let branches =
121           List.map
122            (function
123                Ast.Wildcard,term -> ("wildcard",None,[]), term
124              | Ast.Pattern _,_ ->
125                 raise (DisambiguateTypes.Invalid_choice 
126                  (lazy (loc, "Syntax error: the left hand side of a "^
127                    "branch pattern must be \"_\"")))
128            ) branches
129          in
130          (*
131           NCic.MutCase (ref, cic_outtype, cic_term,
132             (List.map do_branch branches))
133           *) ignore branches; assert false (* patterns not implemented yet *)
134         else
135          let indtype_ref =
136           match indty_ident with
137           | Some (indty_ident, _) ->
138              (match Disambiguate.resolve ~env ~mk_choice 
139                 (Id indty_ident) (`Args []) with
140               | NCic.Const (NReference.Ref (_,NReference.Ind _) as r) -> r
141               | NCic.Implicit _ ->
142                  raise (Disambiguate.Try_again 
143                   (lazy "The type of the term to be matched is still unknown"))
144               | t ->
145                 raise (DisambiguateTypes.Invalid_choice 
146                   (lazy (loc,"The type of the term to be matched "^
147                           "is not (co)inductive: " ^ NCicPp.ppterm 
148                           ~metasenv:[] ~subst:[] ~context:[] t))))
149           | None ->
150               let rec fst_constructor =
151                 function
152                    (Ast.Pattern (head, _, _), _) :: _ -> head
153                  | (Ast.Wildcard, _) :: tl -> fst_constructor tl
154                  | [] -> raise (Invalid_choice (lazy (loc,"The type "^
155                      "of the term to be matched cannot be determined "^
156                      "because it is an inductive type without constructors "^
157                      "or because all patterns use wildcards")))
158               in
159 (*
160               DisambiguateTypes.Environment.iter
161                   (fun k v ->
162                       prerr_endline
163                         (DisambiguateTypes.string_of_domain_item k ^ " => " ^
164                         description_of_alias v)) env; 
165 *)
166               (match Disambiguate.resolve ~env ~mk_choice
167                 (Id (fst_constructor branches)) (`Args []) with
168               | NCic.Const (NReference.Ref (_,NReference.Con _) as r) -> 
169                    let b,_,_,_,_ = NCicEnvironment.get_checked_indtys r in
170                    NReference.mk_indty b r
171               | NCic.Implicit _ ->
172                  raise (Disambiguate.Try_again 
173                   (lazy "The type of the term to be matched is still unknown"))
174               | t ->
175                 raise (DisambiguateTypes.Invalid_choice 
176                   (lazy (loc, 
177                   "The type of the term to be matched is not (co)inductive: " 
178                   ^ NCicPp.ppterm ~metasenv:[] ~subst:[] ~context:[] t))))
179          in
180          let _,leftsno,itl,_,indtyp_no =
181           NCicEnvironment.get_checked_indtys indtype_ref in
182          let _,_,_,cl =
183           try
184            List.nth itl indtyp_no
185           with _ -> assert false in
186          let rec count_prod t =
187                  match NCicReduction.whd ~subst:[] [] t with
188                NCic.Prod (_, _, t) -> 1 + (count_prod t)
189              | _ -> 0 
190          in 
191          let rec sort branches cl =
192           match cl with
193              [] ->
194               let rec analyze unused unrecognized useless =
195                function
196                   [] ->
197                    if unrecognized != [] then
198                     raise (DisambiguateTypes.Invalid_choice
199                      (lazy
200                        (loc,"Unrecognized constructors: " ^
201                         String.concat " " unrecognized)))
202                    else if useless > 0 then
203                     raise (DisambiguateTypes.Invalid_choice
204                      (lazy
205                        (loc,"The last " ^ string_of_int useless ^
206                         "case" ^ if useless > 1 then "s are" else " is" ^
207                         " unused")))
208                    else
209                     []
210                 | (Ast.Wildcard,_)::tl when not unused ->
211                     analyze true unrecognized useless tl
212                 | (Ast.Pattern (head,_,_),_)::tl when not unused ->
213                     analyze unused (head::unrecognized) useless tl
214                 | _::tl -> analyze unused unrecognized (useless + 1) tl
215               in
216                analyze false [] 0 branches
217            | (_,name,ty)::cltl ->
218               let rec find_and_remove =
219                function
220                   [] ->
221                    raise
222                     (DisambiguateTypes.Invalid_choice
223                      (lazy (loc, "Missing case: " ^ name)))
224                 | ((Ast.Wildcard, _) as branch :: _) as branches ->
225                     branch, branches
226                 | (Ast.Pattern (name',_,_),_) as branch :: tl
227                    when name = name' ->
228                     branch,tl
229                 | branch::tl ->
230                    let found,rest = find_and_remove tl in
231                     found, branch::rest
232               in
233                let branch,tl = find_and_remove branches in
234                match branch with
235                   Ast.Pattern (name,y,args),term ->
236                    if List.length args = count_prod ty - leftsno then
237                     ((name,y,args),term)::sort tl cltl
238                    else
239                     raise
240                      (DisambiguateTypes.Invalid_choice
241                       (lazy (loc,"Wrong number of arguments for " ^ name)))
242                 | Ast.Wildcard,term ->
243                    let rec mk_lambdas =
244                     function
245                        0 -> term
246                      | n ->
247                         CicNotationPt.Binder
248                          (`Lambda, (CicNotationPt.Ident ("_", None), None),
249                            mk_lambdas (n - 1))
250                    in
251                     (("wildcard",None,[]),
252                      mk_lambdas (count_prod ty - leftsno)) :: sort tl cltl
253          in
254           let branches = sort branches cl in
255            NCic.Match (indtype_ref, cic_outtype, cic_term,
256             (List.map do_branch branches))
257     | CicNotationPt.Cast (t1, t2) ->
258         let cic_t1 = aux ~localize loc context t1 in
259         let cic_t2 = aux ~localize loc context t2 in
260         NCic.LetIn ("_",cic_t2,cic_t1, NCic.Rel 1)
261     | CicNotationPt.LetIn ((name, typ), def, body) ->
262         let cic_def = aux ~localize loc context def in
263         let cic_name = cic_name_of_name name in
264         let cic_typ =
265           match typ with
266           | None -> NCic.Implicit `Type
267           | Some t -> aux ~localize loc context t
268         in
269         let cic_body = aux ~localize loc (cic_name :: context) body in
270         NCic.LetIn (cic_name, cic_typ, cic_def, cic_body)
271     | CicNotationPt.LetRec (_kind, _defs, _body) ->
272        assert false (*
273         let context' =
274           List.fold_left
275             (fun acc (_, (name, _), _, _) ->
276               cic_name_of_name name :: acc)
277             context defs
278         in
279         let cic_body =
280          let unlocalized_body = aux ~localize:false loc context' body in
281          match unlocalized_body with
282             NCic.Rel n when n <= List.length defs -> `AvoidLetInNoAppl n
283           | NCic.Appl (NCic.Rel n::l) when n <= List.length defs ->
284              (try
285                let l' =
286                 List.map
287                  (function t ->
288                    let t',subst,metasenv =
289                     CicMetaSubst.delift_rels [] [] (List.length defs) t
290                    in
291                     assert (subst=[]);
292                     assert (metasenv=[]);
293                     t') l
294                in
295                 (* We can avoid the LetIn. But maybe we need to recompute l'
296                    so that it is localized *)
297                 if localize then
298                  match body with
299                     CicNotationPt.AttributedTerm (_,CicNotationPt.Appl(_::l)) ->
300                      (* since we avoid the letin, the context has no
301                       * recfuns in it *)
302                      let l' = List.map (aux ~localize loc context) l in
303                       `AvoidLetIn (n,l')
304                   | _ -> assert false
305                 else
306                  `AvoidLetIn (n,l')
307               with
308                CicMetaSubst.DeliftingARelWouldCaptureAFreeVariable ->
309                 if localize then
310                  `AddLetIn (aux ~localize loc context' body)
311                 else
312                  `AddLetIn unlocalized_body)
313           | _ ->
314              if localize then
315               `AddLetIn (aux ~localize loc context' body)
316              else
317               `AddLetIn unlocalized_body
318         in
319         let inductiveFuns =
320           List.map
321             (fun (params, (name, typ), body, decr_idx) ->
322               let add_binders kind t =
323                List.fold_right
324                 (fun var t -> CicNotationPt.Binder (kind, var, t)) params t
325               in
326               let cic_body =
327                aux ~localize loc context' (add_binders `Lambda body) in
328               let cic_type =
329                aux_option ~localize loc context (Some `Type)
330                 (HExtlib.map_option (add_binders `Pi) typ) in
331               let name =
332                 match cic_name_of_name name with
333                 | NCic.Anonymous ->
334                     CicNotationPt.fail loc
335                       "Recursive functions cannot be anonymous"
336                 | NCic.Name name -> name
337               in
338               (name, decr_idx, cic_type, cic_body))
339             defs
340         in
341         let fix_or_cofix n =
342          match kind with
343             `Inductive -> NCic.Fix (n,inductiveFuns)
344           | `CoInductive ->
345               let coinductiveFuns =
346                 List.map
347                  (fun (name, _, typ, body) -> name, typ, body)
348                  inductiveFuns
349               in
350                NCic.CoFix (n,coinductiveFuns)
351         in
352          let counter = ref ~-1 in
353          let build_term _ (var,_,ty,_) t =
354           incr counter;
355           NCic.LetIn (NCic.Name var, fix_or_cofix !counter, ty, t)
356          in
357           (match cic_body with
358               `AvoidLetInNoAppl n ->
359                 let n' = List.length inductiveFuns - n in
360                  fix_or_cofix n'
361             | `AvoidLetIn (n,l) ->
362                 let n' = List.length inductiveFuns - n in
363                  NCic.Appl (fix_or_cofix n'::l)
364             | `AddLetIn cic_body ->         
365                 List.fold_right (build_term inductiveFuns) inductiveFuns
366                  cic_body)
367 *)
368     | CicNotationPt.Ident _
369     | CicNotationPt.Uri _ when is_path -> raise Disambiguate.PathNotWellFormed
370     | CicNotationPt.Ident (name, subst) ->
371        assert (subst = None);
372        (try
373          NCic.Rel (find_in_context name context)
374        with Not_found -> 
375          Disambiguate.resolve ~env ~mk_choice (Id name) (`Args []))
376     | CicNotationPt.Uri (name, subst) ->
377        assert (subst = None);
378        (try
379          NCic.Const (NRef.reference_of_string name)
380         with NRef.IllFormedReference _ ->
381          CicNotationPt.fail loc "Ill formed reference")
382     | CicNotationPt.Implicit -> NCic.Implicit `Term
383     | CicNotationPt.UserInput -> assert false (*NCic.Implicit (Some `Hole)
384 patterns not implemented *)
385     | CicNotationPt.Num (num, i) -> 
386         Disambiguate.resolve ~env ~mk_choice (Num i) (`Num_arg num)
387     | CicNotationPt.Meta (index, subst) ->
388         let cic_subst =
389          List.map
390           (function None -> assert false| Some t -> aux ~localize loc context t)
391           subst
392         in
393          NCic.Meta (index, (0, NCic.Ctx cic_subst))
394     | CicNotationPt.Sort `Prop -> NCic.Sort NCic.Prop
395     | CicNotationPt.Sort `Set -> NCic.Sort (NCic.Type
396        [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
397     | CicNotationPt.Sort (`Type _u) -> NCic.Sort (NCic.Type
398        [false,NUri.uri_of_string "cic:/matita/pts/Type.univ"])
399     | CicNotationPt.Sort (`NType s) -> NCic.Sort (NCic.Type
400        [false,NUri.uri_of_string ("cic:/matita/pts/Type" ^ s ^ ".univ")])
401     | CicNotationPt.Sort (`CProp _u) -> NCic.Sort (NCic.Type
402        [false,NUri.uri_of_string "cic:/matita/pts/CProp.univ"])
403     | CicNotationPt.Symbol (symbol, instance) ->
404         Disambiguate.resolve ~env ~mk_choice 
405          (Symbol (symbol, instance)) (`Args [])
406     | CicNotationPt.Variable _
407     | CicNotationPt.Magic _
408     | CicNotationPt.Layout _
409     | CicNotationPt.Literal _ -> assert false (* god bless Bologna *)
410   and aux_option ~localize loc context annotation = function
411     | None -> NCic.Implicit annotation
412     | Some (CicNotationPt.AttributedTerm (`Loc loc, term)) ->
413         let res = aux_option ~localize loc context annotation (Some term) in
414         if localize then 
415           NCicUntrusted.NCicHash.add localization_tbl res loc;
416         res
417     | Some (CicNotationPt.AttributedTerm (_, term)) ->
418         aux_option ~localize loc context annotation (Some term)
419     | Some CicNotationPt.Implicit -> NCic.Implicit annotation
420     | Some term -> aux ~localize loc context term
421   in
422    aux ~localize:true HExtlib.dummy_floc context ast
423
424 let interpretate_term ?(create_dummy_ids=false) ~context ~env ~uri ~is_path ast
425      ~localization_tbl
426 =
427   let context = List.map fst context in
428   interpretate_term ~create_dummy_ids ~context ~env ~uri ~is_path ast
429 ~localization_tbl
430 ;;
431
432 let disambiguate_term ~context ~metasenv ~subst ?goal
433    ~mk_implicit ~description_of_alias ~mk_choice
434    ~aliases ~universe ~coercion_db ~lookup_in_library 
435    (text,prefix_len,term) 
436  =
437   let mk_localization_tbl x = NCicUntrusted.NCicHash.create x in
438   let hint =
439    match goal with
440       None -> (fun _ y -> y),(fun x -> x)
441     | Some n ->
442        (fun metasenv y ->
443          let _,_,ty = NCicUtils.lookup_meta n metasenv in
444           NCic.LetIn ("_",ty,y,NCic.Rel 1)),
445        (function  
446         | Disambiguate.Ok (t,m,s,ug) ->
447             (match t with
448             | NCic.LetIn ("_",_,y,NCic.Rel 1) -> Disambiguate.Ok (y,m,s,ug)
449             | _ -> assert false)
450         | k -> k)
451   in
452    let res,b =
453     MultiPassDisambiguator.disambiguate_thing
454      ~freshen_thing:CicNotationUtil.freshen_term
455      ~context ~metasenv ~initial_ugraph:() ~aliases
456      ~mk_implicit ~description_of_alias
457      ~string_context_of_context:(List.map (fun (x,_) -> Some x))
458      ~universe ~uri:None ~pp_thing:CicNotationPp.pp_term
459      ~passes:(MultiPassDisambiguator.passes ())
460      ~lookup_in_library ~domain_of_thing:Disambiguate.domain_of_term
461      ~interpretate_thing:(interpretate_term ~mk_choice (?create_dummy_ids:None))
462      ~refine_thing:(refine_term ~coercion_db) (text,prefix_len,term)
463      ~mk_localization_tbl ~hint ~subst
464    in
465     List.map (function (a,b,c,d,_) -> a,b,c,d) res, b
466 ;;
467
468 let _ = 
469 let mk_type n = 
470   if n = 0 then
471      [false, NUri.uri_of_string ("cic:/matita/pts/Type.univ")]
472   else
473      [false, NUri.uri_of_string ("cic:/matita/pts/Type"^string_of_int n^".univ")]
474 in
475 let mk_cprop n = 
476   if n = 0 then 
477     [false, NUri.uri_of_string ("cic:/matita/pts/CProp.univ")]
478   else
479     [false, NUri.uri_of_string ("cic:/matita/pts/CProp"^string_of_int n^".univ")]
480 in
481          NCicEnvironment.add_constraint true (mk_type 0) (mk_type 1);
482          NCicEnvironment.add_constraint true (mk_cprop 0) (mk_cprop 1);
483          NCicEnvironment.add_constraint true (mk_cprop 0) (mk_type 1);
484          NCicEnvironment.add_constraint true (mk_type 0) (mk_cprop 1);
485          NCicEnvironment.add_constraint false (mk_cprop 0) (mk_type 0);
486          NCicEnvironment.add_constraint false (mk_type 0) (mk_cprop 0);
487
488          NCicEnvironment.add_constraint true (mk_type 1) (mk_type 2);
489          NCicEnvironment.add_constraint true (mk_cprop 1) (mk_cprop 2);
490          NCicEnvironment.add_constraint true (mk_cprop 1) (mk_type 2);
491          NCicEnvironment.add_constraint true (mk_type 1) (mk_cprop 2);
492          NCicEnvironment.add_constraint false (mk_cprop 1) (mk_type 1);
493          NCicEnvironment.add_constraint false (mk_type 1) (mk_cprop 1);
494
495          NCicEnvironment.add_constraint false (mk_cprop 2) (mk_type 2);
496          NCicEnvironment.add_constraint false (mk_type 2) (mk_cprop 2);
497
498 ;;
499