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