]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_cic_content/nTermCicContent.ml
56a3f35077e97d308427b7283193cecb21936f02
[helm.git] / helm / software / 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 = CicNotationPt
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 (*
38 type interpretation_id = int
39
40 type term_info =
41   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
42     uri: (Cic.id, UriManager.uri) Hashtbl.t;
43   }
44
45 let get_types uri =
46   let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
47     match o with
48       | Cic.InductiveDefinition (l,_,leftno,_) -> l, leftno 
49       | _ -> assert false
50 *)
51
52 let idref register_ref =
53  let id = ref 0 in
54   fun ?reference t ->
55    incr id;
56    let id = "i" ^ string_of_int !id in
57     (match reference with None -> () | Some r -> register_ref id r);
58     Ast.AttributedTerm (`IdRef id, t)
59 ;;
60
61 (* CODICE c&p da NCicPp *)
62 let nast_of_cic0 status
63  ~(idref:
64     ?reference:NReference.reference -> CicNotationPt.term -> CicNotationPt.term)
65  ~output_type ~metasenv ~subst k ~context =
66   function
67     | NCic.Rel n ->
68        (try 
69          let name,_ = List.nth context (n-1) in
70          let name = if name = "_" then "__"^string_of_int n else name in
71           idref (Ast.Ident (name,None))
72         with Failure "nth" | Invalid_argument "List.nth" -> 
73          idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
74     | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
75     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
76         let _,_,t,_ = List.assoc n subst in
77          k ~context (NCicSubstitution.subst_meta lc t)
78     | NCic.Meta (n,(s,l)) ->
79        (* CSC: qua non dovremmo espandere *)
80        let l = NCicUtils.expand_local_context l in
81         idref (Ast.Meta
82          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
83     | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
84     | NCic.Sort NCic.Type _ -> idref (Ast.Sort `Set)
85     (* CSC: | C.Sort (C.Type []) -> F.fprintf f "Type0"
86     | C.Sort (C.Type [false, u]) -> F.fprintf f "%s" (NUri.name_of_uri u)
87     | C.Sort (C.Type [true, u]) -> F.fprintf f "S(%s)" (NUri.name_of_uri u)
88     | C.Sort (C.Type l) -> 
89        F.fprintf f "Max(";
90        aux ctx (C.Sort (C.Type [List.hd l]));
91        List.iter (fun x -> F.fprintf f ",";aux ctx (C.Sort (C.Type [x])))
92         (List.tl l);
93        F.fprintf f ")"*)
94     (* CSC: qua siamo grezzi *)
95     | NCic.Implicit `Hole -> idref (Ast.UserInput)
96     | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
97     | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
98     | NCic.Prod (n,s,t) ->
99         let n = if n.[0] = '_' then "_" else n in
100         let binder_kind = `Forall in
101          idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
102           k ~context:((n,NCic.Decl s)::context) t))
103     | NCic.Lambda (n,s,t) ->
104         idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
105          k ~context:((n,NCic.Decl s)::context) t))
106     | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
107         idref (Ast.Cast (k ~context ty, k ~context s))
108     | NCic.LetIn (n,s,ty,t) ->
109         idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
110           ty, k ~context:((n,NCic.Decl s)::context) t))
111     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
112        let _,_,t,_ = List.assoc n subst in
113        let hd = NCicSubstitution.subst_meta lc t in
114         k ~context
115          (NCicReduction.head_beta_reduce ~upto:(List.length args)
116            (match hd with
117            | NCic.Appl l -> NCic.Appl (l@args)
118            | _ -> NCic.Appl (hd :: args)))
119     | NCic.Appl args as t ->
120        let args =
121         if not !Acic2content.hide_coercions then args
122         else
123          match
124           NCicCoercion.match_coercion status ~metasenv ~context ~subst t
125          with
126           | None -> args
127           | Some (_,sats,cpos) -> 
128 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
129    argomenti da saltare, come prima! *)
130              if cpos < List.length args - 1 then
131               List.nth args (cpos + 1) ::
132                try snd (HExtlib.split_nth (cpos+sats+2) args) with Failure _->[]
133              else
134               args
135        in
136         (match args with
137             [arg] -> idref (k ~context arg)
138           | _ -> idref (Ast.Appl (List.map (k ~context) args)))
139     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
140         let name = NUri.name_of_uri uri in
141 (* CSC
142         let uri_str = UriManager.string_of_uri uri in
143         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
144         let ctor_puri j =
145           UriManager.uri_of_string
146             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
147         in
148 *)
149         let case_indty =
150          name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
151         let constructors, leftno =
152          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
153          let _,_,_,cl  = List.nth tys n in
154           cl,leftno
155         in
156         let rec eat_branch n ctx ty pat =
157           match (ty, pat) with
158           | NCic.Prod (name, s, t), _ when n > 0 ->
159              eat_branch (pred n) ctx t pat 
160           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
161               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
162               (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
163           | _, _ -> [], k ~context:ctx pat
164         in
165         let j = ref 0 in
166         let patterns =
167           try
168             List.map2
169               (fun (_, name, ty) pat ->
170                 incr j;
171                 let name,(capture_variables,rhs) =
172                  match output_type with
173                     `Term -> name, eat_branch leftno context ty pat
174                   | `Pattern -> "_", ([], k ~context pat)
175                 in
176                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
177               ) constructors patterns
178           with Invalid_argument _ -> assert false
179         in
180         let indty =
181          match output_type with
182             `Pattern -> None
183           | `Term -> Some case_indty
184         in
185          idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
186 ;;
187
188   (* persistent state *)
189
190 (*
191 let initial_level2_patterns32 () = Hashtbl.create 211
192 let initial_interpretations () = Hashtbl.create 211
193
194 let level2_patterns32 = ref (initial_level2_patterns32 ())
195 (* symb -> id list ref *)
196 let interpretations = ref (initial_interpretations ())
197 *)
198 let compiled32 = ref None
199 (*
200 let pattern32_matrix = ref []
201 let counter = ref ~-1 
202
203 let stack = ref []
204
205 let push () =
206  stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
207  counter := ~-1;
208  level2_patterns32 := initial_level2_patterns32 ();
209  interpretations := initial_interpretations ();
210  compiled32 := None;
211  pattern32_matrix := []
212 ;;
213
214 let pop () =
215  match !stack with
216     [] -> assert false
217   | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
218    stack := old;
219    counter := ocounter;
220    level2_patterns32 := olevel2_patterns32;
221    interpretations := ointerpretations;
222    compiled32 := ocompiled32;
223    pattern32_matrix := opattern32_matrix
224 ;;
225 *)
226
227 let get_compiled32 () =
228   match !compiled32 with
229   | None -> assert false
230   | Some f -> Lazy.force f
231
232 let set_compiled32 f = compiled32 := Some f
233
234 let add_idrefs =
235   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
236
237 let instantiate32 idrefs env symbol args =
238   let rec instantiate_arg = function
239     | Ast.IdentArg (n, name) ->
240         let t = 
241           try List.assoc name env 
242           with Not_found -> prerr_endline ("name not found in env: "^name);
243                             assert false
244         in
245         let rec count_lambda = function
246           | Ast.AttributedTerm (_, t) -> count_lambda t
247           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
248           | _ -> 0
249         in
250         let rec add_lambda t n =
251           if n > 0 then
252             let name = CicNotationUtil.fresh_name () in
253             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
254               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
255           else
256             t
257         in
258         add_lambda t (n - count_lambda t)
259   in
260   let head =
261     let symbol = Ast.Symbol (symbol, 0) in
262     add_idrefs idrefs symbol
263   in
264   if args = [] then head
265   else Ast.Appl (head :: List.map instantiate_arg args)
266
267 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
268   match (get_compiled32 ()) term with
269   | None ->
270      nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
271       (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term 
272   | Some (env, ctors, pid) -> 
273       let idrefs =
274        List.map
275         (fun term ->
276           let attrterm =
277            idref
278             ~reference:
279               (match term with NCic.Const nref -> nref | _ -> assert false)
280            (CicNotationPt.Ident ("dummy",None))
281           in
282            match attrterm with
283               Ast.AttributedTerm (`IdRef id, _) -> id
284             | _ -> assert false
285         ) ctors
286       in
287       let env =
288        List.map
289         (fun (name, term) ->
290           name,
291            nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
292             term
293         ) env
294       in
295       let _, symbol, args, _ =
296         try
297           TermAcicContent.find_level2_patterns32 pid
298         with Not_found -> assert false
299       in
300       let ast = instantiate32 idrefs env symbol args in
301       idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
302 ;;
303
304 let load_patterns32 t =
305  let t =
306   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
307  in
308   set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
309 in
310  TermAcicContent.add_load_patterns32 load_patterns32;
311  TermAcicContent.init ()
312 ;;
313
314 (*
315 let ast_of_acic ~output_type id_to_sort annterm =
316   debug_print (lazy ("ast_of_acic <- "
317     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
318   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
319   let ast = ast_of_acic1 ~output_type term_info annterm in
320   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
321   ast, term_info.uri
322
323 let fresh_id =
324   fun () ->
325     incr counter;
326     !counter
327
328 let add_interpretation dsc (symbol, args) appl_pattern =
329   let id = fresh_id () in
330   Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
331   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
332   load_patterns32 !pattern32_matrix;
333   (try
334     let ids = Hashtbl.find !interpretations symbol in
335     ids := id :: !ids
336   with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
337   id
338
339 let get_all_interpretations () =
340   List.map
341     (function (_, _, id) ->
342       let (dsc, _, _, _) =
343         try
344           Hashtbl.find !level2_patterns32 id
345         with Not_found -> assert false
346       in
347       (id, dsc))
348     !pattern32_matrix
349
350 let get_active_interpretations () =
351   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
352     !pattern32_matrix
353
354 let set_active_interpretations ids =
355   let pattern32_matrix' =
356     List.map
357       (function 
358         | (_, ap, id) when List.mem id ids -> (true, ap, id)
359         | (_, ap, id) -> (false, ap, id))
360       !pattern32_matrix
361   in
362   pattern32_matrix := pattern32_matrix';
363   load_patterns32 !pattern32_matrix
364
365 exception Interpretation_not_found
366
367 let lookup_interpretations symbol =
368   try
369    HExtlib.list_uniq
370     (List.sort Pervasives.compare
371      (List.map
372       (fun id ->
373         let (dsc, _, args, appl_pattern) =
374           try
375             Hashtbl.find !level2_patterns32 id
376           with Not_found -> assert false 
377         in
378         dsc, args, appl_pattern)
379       !(Hashtbl.find !interpretations symbol)))
380   with Not_found -> raise Interpretation_not_found
381
382 let remove_interpretation id =
383   (try
384     let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
385     let ids = Hashtbl.find !interpretations symbol in
386     ids := List.filter ((<>) id) !ids;
387     Hashtbl.remove !level2_patterns32 id;
388   with Not_found -> raise Interpretation_not_found);
389   pattern32_matrix :=
390     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
391   load_patterns32 !pattern32_matrix
392
393 let _ = load_patterns32 []
394
395 let instantiate_appl_pattern 
396   ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern 
397 =
398   let lookup name =
399     try List.assoc name env
400     with Not_found ->
401       prerr_endline (sprintf "Name %s not found" name);
402       assert false
403   in
404   let rec aux = function
405     | Ast.UriPattern uri -> term_of_uri uri
406     | Ast.ImplicitPattern -> mk_implicit false
407     | Ast.VarPattern name -> lookup name
408     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
409   in
410   aux appl_pattern
411 *)
412
413 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
414  let module K = Content in
415  let nast_of_cic =
416   nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
417  let context',_ =
418   List.fold_right
419    (fun item (res,context) ->
420      match item with
421       | name,NCic.Decl t ->
422          Some
423           (* We should call build_decl_item, but we have not computed *)
424           (* the inner-types ==> we always produce a declaration      *)
425           (`Declaration
426             { K.dec_name = (Some name);
427               K.dec_id = "-1"; 
428               K.dec_inductive = false;
429               K.dec_aref = "-1";
430               K.dec_type = nast_of_cic ~context t
431             })::res,item::context
432       | name,NCic.Def (t,ty) ->
433          Some
434           (* We should call build_def_item, but we have not computed *)
435           (* the inner-types ==> we always produce a declaration     *)
436           (`Definition
437              { K.def_name = (Some name);
438                K.def_id = "-1"; 
439                K.def_aref = "-1";
440                K.def_term = nast_of_cic ~context t;
441                K.def_type = nast_of_cic ~context ty
442              })::res,item::context
443    ) context ([],[])
444  in
445   ("-1",i,context',nast_of_cic ~context ty)
446 ;;
447
448 let nmap_sequent status ~metasenv ~subst conjecture =
449  let module K = Content in
450  let ids_to_refs = Hashtbl.create 211 in
451  let register_ref = Hashtbl.add ids_to_refs in
452   nmap_sequent0 status ~idref:(idref register_ref) ~metasenv ~subst conjecture,
453   ids_to_refs
454 ;;
455
456 let object_prefix = "obj:";;
457 let declaration_prefix = "decl:";;
458 let definition_prefix = "def:";;
459 let inductive_prefix = "ind:";;
460 let joint_prefix = "joint:";;
461
462 let get_id =
463  function
464     Ast.AttributedTerm (`IdRef id, _) -> id
465   | _ -> assert false
466 ;;
467
468 let gen_id prefix seed =
469  let res = prefix ^ string_of_int !seed in
470   incr seed ;
471   res
472 ;;
473
474 let build_def_item seed context metasenv id n t ty =
475  let module K = Content in
476 (*
477   try
478    let sort = Hashtbl.find ids_to_inner_sorts id in
479    if sort = `Prop then
480        (let p = 
481         (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts  ~ids_to_inner_types t)
482        in 
483         `Proof p;)
484    else 
485 *)
486       `Definition
487         { K.def_name = Some n;
488           K.def_id = gen_id definition_prefix seed; 
489           K.def_aref = id;
490           K.def_term = t;
491           K.def_type = ty
492         }
493 (*
494   with
495    Not_found -> assert false
496 *)
497
498 let build_decl_item seed id n s =
499  let module K = Content in
500 (*
501  let sort =
502    try
503     Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
504    with Not_found -> None
505  in
506  match sort with
507  | Some `Prop ->
508     `Hypothesis
509       { K.dec_name = name_of n;
510         K.dec_id = gen_id declaration_prefix seed; 
511         K.dec_inductive = false;
512         K.dec_aref = id;
513         K.dec_type = s
514       }
515  | _ ->
516 *)
517     `Declaration
518       { K.dec_name = Some n;
519         K.dec_id = gen_id declaration_prefix seed; 
520         K.dec_inductive = false;
521         K.dec_aref = id;
522         K.dec_type = s
523       }
524 ;;
525
526 let nmap_obj status (uri,_,metasenv,subst,kind) =
527   let module K = Content in
528   let ids_to_refs = Hashtbl.create 211 in
529   let register_ref = Hashtbl.add ids_to_refs in
530   let idref = idref register_ref in
531   let nast_of_cic =
532    nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
533   let seed = ref 0 in
534   let conjectures =
535    match metasenv with
536       [] -> None
537     | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
538       (*CSC: used to be the previous line, that uses seed *)
539       Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
540   in
541 let  build_constructors seed l =
542       List.map 
543        (fun (_,n,ty) ->
544            let ty = nast_of_cic ~context:[] ty in
545            { K.dec_name = Some n;
546              K.dec_id = gen_id declaration_prefix seed;
547              K.dec_inductive = false;
548              K.dec_aref = "";
549              K.dec_type = ty
550            }) l
551 in
552 let build_inductive b seed = 
553       fun (_,n,ty,cl) ->
554         let ty = nast_of_cic ~context:[] ty in
555         `Inductive
556           { K.inductive_id = gen_id inductive_prefix seed;
557             K.inductive_name = n;
558             K.inductive_kind = b;
559             K.inductive_type = ty;
560             K.inductive_constructors = build_constructors seed cl
561            }
562 in
563   let res =
564    match kind with
565     | NCic.Fixpoint (is_rec, ifl, _) -> assert false
566     | NCic.Inductive (is_ind, lno, itl, _) ->
567          (gen_id object_prefix seed, [], conjectures,
568             `Joint
569               { K.joint_id = gen_id joint_prefix seed;
570                 K.joint_kind = `Inductive lno;
571                 K.joint_defs = List.map (build_inductive is_ind seed) itl
572               }) 
573     | NCic.Constant (_,_,Some bo,ty,_) ->
574        let ty = nast_of_cic ~context:[] ty in
575        let bo = nast_of_cic ~context:[] bo in
576         (gen_id object_prefix seed, [], conjectures,
577           `Def (K.Const,ty,
578             build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
579     | NCic.Constant (_,_,None,ty,_) ->
580        let ty = nast_of_cic ~context:[] ty in
581          (gen_id object_prefix seed, [], conjectures,
582            `Decl (K.Const,
583              (*CSC: ??? get_id ty here used to be the id of the axiom! *)
584              build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
585  in
586   res,ids_to_refs
587 ;;