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