]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_cic_content/nTermCicContent.ml
WARNING: partial commit (does not compile)
[helm.git] / matita / components / ng_cic_content / nTermCicContent.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id: termAcicContent.ml 9304 2008-12-05 23:12:39Z sacerdot $ *)
27
28 open Printf
29
30 module Ast = NotationPt
31
32 let debug = false
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
34
35 type id = string
36
37 let hide_coercions = ref true;;
38
39 class status =
40   object
41     inherit NCicCoercion.status
42     inherit Interpretations.status
43   end
44
45 let idref register_ref =
46  let id = ref 0 in
47   fun ?reference t ->
48    incr id;
49    let id = "i" ^ string_of_int !id in
50     (match reference with None -> () | Some r -> register_ref id r);
51     Ast.AttributedTerm (`IdRef id, t)
52 ;;
53
54 let level_of_uri u = 
55   let name = NUri.name_of_uri u in
56   assert(String.length name > String.length "Type");
57   String.sub name 4 (String.length name - 4)
58 ;;
59
60 let destroy_nat =
61   let is_nat_URI = NUri.eq (NUri.uri_of_string
62   "cic:/matita/ng/arithmetics/nat/nat.ind") in
63   let is_zero = function
64     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
65        is_nat_URI uri -> true
66     | _ -> false
67   in
68   let is_succ = function
69     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
70        is_nat_URI uri -> true
71     | _ -> false
72   in
73   let rec aux acc = function
74     | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
75     | t when is_zero t -> Some acc
76     | _ -> None
77   in
78    aux 0
79
80 (* CODICE c&p da NCicPp *)
81 let nast_of_cic0 status
82  ~(idref:
83     ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
84  ~output_type ~metasenv ~subst k ~context =
85   function
86     | NCic.Rel n ->
87        (try 
88          let name,_ = List.nth context (n-1) in
89          let name = if name = "_" then "__"^string_of_int n else name in
90           idref (Ast.Ident (name,None))
91         with Failure "nth" | Invalid_argument "List.nth" -> 
92          idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
93     | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
94     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
95         let _,_,t,_ = List.assoc n subst in
96          k ~context (NCicSubstitution.subst_meta lc t)
97     | NCic.Meta (n,(s,l)) ->
98        (* CSC: qua non dovremmo espandere *)
99        let l = NCicUtils.expand_local_context l in
100         idref (Ast.Meta
101          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
102     | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
103     | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
104     | NCic.Sort NCic.Type ((`Type,u)::_) -> 
105               idref(Ast.Sort (`NType (level_of_uri u)))
106     | NCic.Sort NCic.Type ((`CProp,u)::_) -> 
107               idref(Ast.Sort (`NCProp (level_of_uri u)))
108     | NCic.Sort NCic.Type ((`Succ,u)::_) -> 
109               idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
110     | NCic.Implicit `Hole -> idref (Ast.UserInput)
111     | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
112     | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
113     | NCic.Prod (n,s,t) ->
114         let n = if n.[0] = '_' then "_" else n in
115         let binder_kind = `Forall in
116          idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
117           k ~context:((n,NCic.Decl s)::context) t))
118     | NCic.Lambda (n,s,t) ->
119         idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
120          k ~context:((n,NCic.Decl s)::context) t))
121     | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
122         idref (Ast.Cast (k ~context ty, k ~context s))
123     | NCic.LetIn (n,s,ty,t) ->
124         idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
125           ty, k ~context:((n,NCic.Decl s)::context) t))
126     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
127        let _,_,t,_ = List.assoc n subst in
128        let hd = NCicSubstitution.subst_meta lc t in
129         k ~context
130          (NCicReduction.head_beta_reduce ~upto:(List.length args)
131            (match hd with
132            | NCic.Appl l -> NCic.Appl (l@args)
133            | _ -> NCic.Appl (hd :: args)))
134     | NCic.Appl args as t ->
135        (match destroy_nat t with
136          | Some n -> idref (Ast.Num (string_of_int n, -1))
137          | None ->
138             let args =
139              if not !hide_coercions then args
140              else
141               match
142                NCicCoercion.match_coercion status ~metasenv ~context ~subst t
143               with
144                | None -> args
145                | Some (_,sats,cpos) -> 
146 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
147    argomenti da saltare, come prima! *)
148                   if cpos < List.length args - 1 then
149                    List.nth args (cpos + 1) ::
150                     try snd (HExtlib.split_nth (cpos+sats+2) args)
151                     with Failure _->[]
152                   else
153                    args
154             in
155              (match args with
156                  [arg] -> idref (k ~context arg)
157                | _ -> idref (Ast.Appl (List.map (k ~context) args))))
158     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
159         let name = NUri.name_of_uri uri in
160 (* CSC
161         let uri_str = UriManager.string_of_uri uri in
162         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
163         let ctor_puri j =
164           UriManager.uri_of_string
165             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
166         in
167 *)
168         let case_indty =
169          name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
170         let constructors, leftno =
171          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
172          let _,_,_,cl  = List.nth tys n in
173           cl,leftno
174         in
175         let rec eat_branch n ctx ty pat =
176           match (ty, pat) with
177           | NCic.Prod (name, s, t), _ when n > 0 ->
178              eat_branch (pred n) ctx t pat 
179           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
180               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
181               (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
182           | _, _ -> [], k ~context:ctx pat
183         in
184         let j = ref 0 in
185         let patterns =
186           try
187             List.map2
188               (fun (_, name, ty) pat ->
189                 incr j;
190                 let name,(capture_variables,rhs) =
191                  match output_type with
192                     `Term -> name, eat_branch leftno context ty pat
193                   | `Pattern -> "_", ([], k ~context pat)
194                 in
195                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
196               ) constructors patterns
197           with Invalid_argument _ -> assert false
198         in
199         let indty =
200          match output_type with
201             `Pattern -> None
202           | `Term -> Some case_indty
203         in
204          idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
205 ;;
206
207 let compiled32 = ref None
208
209 let get_compiled32 () =
210   match !compiled32 with
211   | None -> assert false
212   | Some f -> Lazy.force f
213
214 let set_compiled32 f = compiled32 := Some f
215
216 let add_idrefs =
217   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
218
219 let instantiate32 idrefs env symbol args =
220   let rec instantiate_arg = function
221     | Ast.IdentArg (n, name) ->
222         let t = 
223           try List.assoc name env 
224           with Not_found -> prerr_endline ("name not found in env: "^name);
225                             assert false
226         in
227         let rec count_lambda = function
228           | Ast.AttributedTerm (_, t) -> count_lambda t
229           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
230           | _ -> 0
231         in
232         let rec add_lambda t n =
233           if n > 0 then
234             let name = NotationUtil.fresh_name () in
235             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
236               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
237           else
238             t
239         in
240         add_lambda t (n - count_lambda t)
241   in
242   let head =
243     let symbol = Ast.Symbol (symbol, 0) in
244     add_idrefs idrefs symbol
245   in
246   if args = [] then head
247   else Ast.Appl (head :: List.map instantiate_arg args)
248
249 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
250   match (get_compiled32 ()) term with
251   | None ->
252      nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
253       (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term 
254   | Some (env, ctors, pid) -> 
255       let idrefs =
256        List.map
257         (fun term ->
258           let attrterm =
259            idref
260             ~reference:
261               (match term with NCic.Const nref -> nref | _ -> assert false)
262            (NotationPt.Ident ("dummy",None))
263           in
264            match attrterm with
265               Ast.AttributedTerm (`IdRef id, _) -> id
266             | _ -> assert false
267         ) ctors
268       in
269       let env =
270        List.map
271         (fun (name, term) ->
272           name,
273            nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
274             term
275         ) env
276       in
277       let _, symbol, args, _ =
278         try
279           Interpretations.find_level2_patterns32 status pid
280         with Not_found -> assert false
281       in
282       let ast = instantiate32 idrefs env symbol args in
283       idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
284 ;;
285
286 let load_patterns32 t =
287  let t =
288   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
289  in
290   set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
291 ;;
292
293 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
294  let module K = Content in
295  let nast_of_cic =
296   nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
297  let context',_ =
298   List.fold_right
299    (fun item (res,context) ->
300      match item with
301       | name,NCic.Decl t ->
302          Some
303           (* We should call build_decl_item, but we have not computed *)
304           (* the inner-types ==> we always produce a declaration      *)
305           (`Declaration
306             { K.dec_name = (Some name);
307               K.dec_id = "-1"; 
308               K.dec_inductive = false;
309               K.dec_aref = "-1";
310               K.dec_type = nast_of_cic ~context t
311             })::res,item::context
312       | name,NCic.Def (t,ty) ->
313          Some
314           (* We should call build_def_item, but we have not computed *)
315           (* the inner-types ==> we always produce a declaration     *)
316           (`Definition
317              { K.def_name = (Some name);
318                K.def_id = "-1"; 
319                K.def_aref = "-1";
320                K.def_term = nast_of_cic ~context t;
321                K.def_type = nast_of_cic ~context ty
322              })::res,item::context
323    ) context ([],[])
324  in
325   ("-1",i,context',nast_of_cic ~context ty)
326 ;;
327
328 let nmap_sequent status ~metasenv ~subst conjecture =
329  let module K = Content in
330  let ids_to_refs = Hashtbl.create 211 in
331  let register_ref = Hashtbl.add ids_to_refs in
332   nmap_sequent0 status ~idref:(idref register_ref) ~metasenv ~subst conjecture,
333   ids_to_refs
334 ;;
335
336 let object_prefix = "obj:";;
337 let declaration_prefix = "decl:";;
338 let definition_prefix = "def:";;
339 let inductive_prefix = "ind:";;
340 let joint_prefix = "joint:";;
341
342 let get_id =
343  function
344     Ast.AttributedTerm (`IdRef id, _) -> id
345   | _ -> assert false
346 ;;
347
348 let gen_id prefix seed =
349  let res = prefix ^ string_of_int !seed in
350   incr seed ;
351   res
352 ;;
353
354 let build_def_item seed context metasenv id n t ty =
355  let module K = Content in
356 (*
357   try
358    let sort = Hashtbl.find ids_to_inner_sorts id in
359    if sort = `Prop then
360        (let p = 
361         (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts  ~ids_to_inner_types t)
362        in 
363         `Proof p;)
364    else 
365 *)
366       `Definition
367         { K.def_name = Some n;
368           K.def_id = gen_id definition_prefix seed; 
369           K.def_aref = id;
370           K.def_term = t;
371           K.def_type = ty
372         }
373 (*
374   with
375    Not_found -> assert false
376 *)
377
378 let build_decl_item seed id n s =
379  let module K = Content in
380 (*
381  let sort =
382    try
383     Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
384    with Not_found -> None
385  in
386  match sort with
387  | Some `Prop ->
388     `Hypothesis
389       { K.dec_name = name_of n;
390         K.dec_id = gen_id declaration_prefix seed; 
391         K.dec_inductive = false;
392         K.dec_aref = id;
393         K.dec_type = s
394       }
395  | _ ->
396 *)
397     `Declaration
398       { K.dec_name = Some n;
399         K.dec_id = gen_id declaration_prefix seed; 
400         K.dec_inductive = false;
401         K.dec_aref = id;
402         K.dec_type = s
403       }
404 ;;
405
406 let nmap_obj status (uri,_,metasenv,subst,kind) =
407   let module K = Content in
408   let ids_to_refs = Hashtbl.create 211 in
409   let register_ref = Hashtbl.add ids_to_refs in
410   let idref = idref register_ref in
411   let nast_of_cic =
412    nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
413   let seed = ref 0 in
414   let conjectures =
415    match metasenv with
416       [] -> None
417     | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
418       (*CSC: used to be the previous line, that uses seed *)
419       Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
420   in
421 let  build_constructors seed l =
422       List.map 
423        (fun (_,n,ty) ->
424            let ty = nast_of_cic ~context:[] ty in
425            { K.dec_name = Some n;
426              K.dec_id = gen_id declaration_prefix seed;
427              K.dec_inductive = false;
428              K.dec_aref = "";
429              K.dec_type = ty
430            }) l
431 in
432 let build_inductive b seed = 
433       fun (_,n,ty,cl) ->
434         let ty = nast_of_cic ~context:[] ty in
435         `Inductive
436           { K.inductive_id = gen_id inductive_prefix seed;
437             K.inductive_name = n;
438             K.inductive_kind = b;
439             K.inductive_type = ty;
440             K.inductive_constructors = build_constructors seed cl
441            }
442 in
443 let build_fixpoint b seed = 
444       fun (_,n,_,ty,t) ->
445         let t = nast_of_cic ~context:[] t in
446         let ty = nast_of_cic ~context:[] ty in
447         `Definition
448           { K.def_id = gen_id inductive_prefix seed;
449             K.def_name = Some n;
450             K.def_aref = "";
451             K.def_type = ty;
452             K.def_term = t;
453            }
454 in
455   let res =
456    match kind with
457     | NCic.Fixpoint (is_rec, ifl, _) -> 
458          (gen_id object_prefix seed, conjectures,
459             `Joint
460               { K.joint_id = gen_id joint_prefix seed;
461                 K.joint_kind = 
462                    if is_rec then 
463                         `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
464                    else `CoRecursive;
465                 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
466               }) 
467     | NCic.Inductive (is_ind, lno, itl, _) ->
468          (gen_id object_prefix seed, conjectures,
469             `Joint
470               { K.joint_id = gen_id joint_prefix seed;
471                 K.joint_kind = 
472                    if is_ind then `Inductive lno else `CoInductive lno;
473                 K.joint_defs = List.map (build_inductive is_ind seed) itl
474               }) 
475     | NCic.Constant (_,_,Some bo,ty,_) ->
476        let ty = nast_of_cic ~context:[] ty in
477        let bo = nast_of_cic ~context:[] bo in
478         (gen_id object_prefix seed, conjectures,
479           `Def (K.Const,ty,
480             build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
481     | NCic.Constant (_,_,None,ty,_) ->
482        let ty = nast_of_cic ~context:[] ty in
483          (gen_id object_prefix seed, conjectures,
484            `Decl (K.Const,
485              (*CSC: ??? get_id ty here used to be the id of the axiom! *)
486              build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
487  in
488   res,ids_to_refs
489 ;;
490
491 Interpretations.set_load_patterns32 load_patterns32