1 (* Copyright (C) 2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
26 (* $Id: termAcicContent.ml 9304 2008-12-05 23:12:39Z sacerdot $ *)
30 module Ast = CicNotationPt
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
38 type interpretation_id = int
41 { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
42 uri: (Cic.id, UriManager.uri) Hashtbl.t;
46 let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
48 | Cic.InductiveDefinition (l,_,leftno,_) -> l, leftno
52 let idref register_ref =
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)
61 (* CODICE c&p da NCicPp *)
62 let nast_of_cic0 status
64 ?reference:NReference.reference -> CicNotationPt.term -> CicNotationPt.term)
65 ~output_type ~metasenv ~subst k ~context =
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
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) ->
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])))
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
113 (NCicReduction.head_beta_reduce ~upto:(List.length args)
115 | NCic.Appl l -> NCic.Appl (l@args)
116 | _ -> NCic.Appl (hd :: args)))
117 | NCic.Appl args as t ->
119 if not !Acic2content.hide_coercions then args
122 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
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 _->[]
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
140 let uri_str = UriManager.string_of_uri uri in
141 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
143 UriManager.uri_of_string
144 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
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
154 let rec eat_branch n ctx ty pat =
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
167 (fun (_, name, ty) pat ->
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)
174 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
175 ) constructors patterns
176 with Invalid_argument _ -> assert false
179 match output_type with
181 | `Term -> Some case_indty
183 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
186 (* persistent state *)
189 let initial_level2_patterns32 () = Hashtbl.create 211
190 let initial_interpretations () = Hashtbl.create 211
192 let level2_patterns32 = ref (initial_level2_patterns32 ())
193 (* symb -> id list ref *)
194 let interpretations = ref (initial_interpretations ())
196 let compiled32 = ref None
198 let pattern32_matrix = ref []
199 let counter = ref ~-1
204 stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
206 level2_patterns32 := initial_level2_patterns32 ();
207 interpretations := initial_interpretations ();
209 pattern32_matrix := []
215 | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
218 level2_patterns32 := olevel2_patterns32;
219 interpretations := ointerpretations;
220 compiled32 := ocompiled32;
221 pattern32_matrix := opattern32_matrix
225 let get_compiled32 () =
226 match !compiled32 with
227 | None -> assert false
228 | Some f -> Lazy.force f
230 let set_compiled32 f = compiled32 := Some f
233 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
235 let instantiate32 idrefs env symbol args =
236 let rec instantiate_arg = function
237 | Ast.IdentArg (n, name) ->
239 try List.assoc name env
240 with Not_found -> prerr_endline ("name not found in env: "^name);
243 let rec count_lambda = function
244 | Ast.AttributedTerm (_, t) -> count_lambda t
245 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
248 let rec add_lambda t n =
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)])
256 add_lambda t (n - count_lambda t)
259 let symbol = Ast.Symbol (symbol, 0) in
260 add_idrefs idrefs symbol
262 if args = [] then head
263 else Ast.Appl (head :: List.map instantiate_arg args)
265 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
266 match (get_compiled32 ()) term with
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) ->
277 (match term with NCic.Const nref -> nref | _ -> assert false)
278 (CicNotationPt.Ident ("dummy",None))
281 Ast.AttributedTerm (`IdRef id, _) -> id
289 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
293 let _, symbol, args, _ =
295 TermAcicContent.find_level2_patterns32 pid
296 with Not_found -> assert false
298 let ast = instantiate32 idrefs env symbol args in
299 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
302 let load_patterns32 t =
304 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
306 set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
308 TermAcicContent.add_load_patterns32 load_patterns32;
309 TermAcicContent.init ()
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));
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;
332 let ids = Hashtbl.find !interpretations symbol in
334 with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
337 let get_all_interpretations () =
339 (function (_, _, id) ->
342 Hashtbl.find !level2_patterns32 id
343 with Not_found -> assert false
348 let get_active_interpretations () =
349 HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
352 let set_active_interpretations ids =
353 let pattern32_matrix' =
356 | (_, ap, id) when List.mem id ids -> (true, ap, id)
357 | (_, ap, id) -> (false, ap, id))
360 pattern32_matrix := pattern32_matrix';
361 load_patterns32 !pattern32_matrix
363 exception Interpretation_not_found
365 let lookup_interpretations symbol =
368 (List.sort Pervasives.compare
371 let (dsc, _, args, appl_pattern) =
373 Hashtbl.find !level2_patterns32 id
374 with Not_found -> assert false
376 dsc, args, appl_pattern)
377 !(Hashtbl.find !interpretations symbol)))
378 with Not_found -> raise Interpretation_not_found
380 let remove_interpretation id =
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);
388 List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
389 load_patterns32 !pattern32_matrix
391 let _ = load_patterns32 []
393 let instantiate_appl_pattern
394 ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern
397 try List.assoc name env
399 prerr_endline (sprintf "Name %s not found" name);
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)
411 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
412 let module K = Content in
414 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
417 (fun item (res,context) ->
419 | name,NCic.Decl t ->
421 (* We should call build_decl_item, but we have not computed *)
422 (* the inner-types ==> we always produce a declaration *)
424 { K.dec_name = (Some name);
426 K.dec_inductive = false;
428 K.dec_type = nast_of_cic ~context t
429 })::res,item::context
430 | name,NCic.Def (t,ty) ->
432 (* We should call build_def_item, but we have not computed *)
433 (* the inner-types ==> we always produce a declaration *)
435 { K.def_name = (Some name);
438 K.def_term = nast_of_cic ~context t;
439 K.def_type = nast_of_cic ~context ty
440 })::res,item::context
443 ("-1",i,context',nast_of_cic ~context ty)
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,
454 let object_prefix = "obj:";;
455 let declaration_prefix = "decl:";;
456 let definition_prefix = "def:";;
460 Ast.AttributedTerm (`IdRef id, _) -> id
464 let gen_id prefix seed =
465 let res = prefix ^ string_of_int !seed in
470 let build_def_item seed context metasenv id n t ty =
471 let module K = Content in
474 let sort = Hashtbl.find ids_to_inner_sorts id in
477 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
483 { K.def_name = Some n;
484 K.def_id = gen_id definition_prefix seed;
491 Not_found -> assert false
494 let build_decl_item seed id n s =
495 let module K = Content in
499 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
500 with Not_found -> None
505 { K.dec_name = name_of n;
506 K.dec_id = gen_id declaration_prefix seed;
507 K.dec_inductive = false;
514 { K.dec_name = Some n;
515 K.dec_id = gen_id declaration_prefix seed;
516 K.dec_inductive = false;
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
528 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
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)
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,
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,
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))
552 | C.AInductiveDefinition (id,l,params,nparams,_) ->
553 (gen_id object_prefix seed, params, conjectures,
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
561 build_inductive seed =
562 let module K = Content in
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
573 build_constructors seed l =
574 let module K = Content in
577 { K.dec_name = Some n;
578 K.dec_id = gen_id declaration_prefix seed;
579 K.dec_inductive = false;