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