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