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