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