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