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