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 *)
64 ?reference:NReference.reference -> CicNotationPt.term -> CicNotationPt.term)
65 ~output_type ~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 _ -> 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
112 (NCicReduction.head_beta_reduce ~upto:(List.length args)
114 | NCic.Appl l -> NCic.Appl (l@args)
115 | _ -> NCic.Appl (hd :: args)))
116 | NCic.Appl args -> idref (Ast.Appl (List.map (k ~context) args))
117 | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
118 let name = NUri.name_of_uri uri in
120 let uri_str = UriManager.string_of_uri uri in
121 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
123 UriManager.uri_of_string
124 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
128 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
129 let constructors, leftno =
130 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
131 let _,_,_,cl = List.nth tys n in
134 let rec eat_branch n ctx ty pat =
136 | NCic.Prod (name, s, t), _ when n > 0 ->
137 eat_branch (pred n) ((name,NCic.Decl s)::ctx) t pat
138 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
139 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
140 (Ast.Ident (name,None), Some (k ~context s)) :: cv, rhs
141 | _, _ -> [], k ~context pat
147 (fun (_, name, ty) pat ->
149 let name,(capture_variables,rhs) =
150 match output_type with
151 `Term -> name, eat_branch leftno context ty pat
152 | `Pattern -> "_", ([], k ~context pat)
154 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
155 ) constructors patterns
156 with Invalid_argument _ -> assert false
159 match output_type with
161 | `Term -> Some case_indty
163 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
166 (* persistent state *)
169 let initial_level2_patterns32 () = Hashtbl.create 211
170 let initial_interpretations () = Hashtbl.create 211
172 let level2_patterns32 = ref (initial_level2_patterns32 ())
173 (* symb -> id list ref *)
174 let interpretations = ref (initial_interpretations ())
176 let compiled32 = ref None
178 let pattern32_matrix = ref []
179 let counter = ref ~-1
184 stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
186 level2_patterns32 := initial_level2_patterns32 ();
187 interpretations := initial_interpretations ();
189 pattern32_matrix := []
195 | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
198 level2_patterns32 := olevel2_patterns32;
199 interpretations := ointerpretations;
200 compiled32 := ocompiled32;
201 pattern32_matrix := opattern32_matrix
205 let get_compiled32 () =
206 match !compiled32 with
207 | None -> assert false
208 | Some f -> Lazy.force f
210 let set_compiled32 f = compiled32 := Some f
213 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
215 let instantiate32 idrefs env symbol args =
216 let rec instantiate_arg = function
217 | Ast.IdentArg (n, name) ->
219 try List.assoc name env
220 with Not_found -> prerr_endline ("name not found in env: "^name);
223 let rec count_lambda = function
224 | Ast.AttributedTerm (_, t) -> count_lambda t
225 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
228 let rec add_lambda t n =
230 let name = CicNotationUtil.fresh_name () in
231 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
232 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
236 add_lambda t (n - count_lambda t)
239 let symbol = Ast.Symbol (symbol, 0) in
240 add_idrefs idrefs symbol
242 if args = [] then head
243 else Ast.Appl (head :: List.map instantiate_arg args)
245 let rec nast_of_cic1 ~idref ~output_type ~subst ~context term =
246 match (get_compiled32 ()) term with
248 nast_of_cic0 ~idref ~output_type ~subst
249 (nast_of_cic1 ~idref ~output_type ~subst) ~context term
250 | Some (env, ctors, pid) ->
257 (match term with NCic.Const nref -> nref | _ -> assert false)
258 (CicNotationPt.Ident ("dummy",None))
261 Ast.AttributedTerm (`IdRef id, _) -> id
269 nast_of_cic1 ~idref ~output_type ~subst ~context term
272 let _, symbol, args, _ =
274 TermAcicContent.find_level2_patterns32 pid
275 with Not_found -> assert false
277 let ast = instantiate32 idrefs env symbol args in
278 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
281 let load_patterns32 t =
283 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
285 set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
287 TermAcicContent.add_load_patterns32 load_patterns32;
288 TermAcicContent.init ()
292 let ast_of_acic ~output_type id_to_sort annterm =
293 debug_print (lazy ("ast_of_acic <- "
294 ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
295 let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
296 let ast = ast_of_acic1 ~output_type term_info annterm in
297 debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
305 let add_interpretation dsc (symbol, args) appl_pattern =
306 let id = fresh_id () in
307 Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
308 pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
309 load_patterns32 !pattern32_matrix;
311 let ids = Hashtbl.find !interpretations symbol in
313 with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
316 let get_all_interpretations () =
318 (function (_, _, id) ->
321 Hashtbl.find !level2_patterns32 id
322 with Not_found -> assert false
327 let get_active_interpretations () =
328 HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
331 let set_active_interpretations ids =
332 let pattern32_matrix' =
335 | (_, ap, id) when List.mem id ids -> (true, ap, id)
336 | (_, ap, id) -> (false, ap, id))
339 pattern32_matrix := pattern32_matrix';
340 load_patterns32 !pattern32_matrix
342 exception Interpretation_not_found
344 let lookup_interpretations symbol =
347 (List.sort Pervasives.compare
350 let (dsc, _, args, appl_pattern) =
352 Hashtbl.find !level2_patterns32 id
353 with Not_found -> assert false
355 dsc, args, appl_pattern)
356 !(Hashtbl.find !interpretations symbol)))
357 with Not_found -> raise Interpretation_not_found
359 let remove_interpretation id =
361 let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
362 let ids = Hashtbl.find !interpretations symbol in
363 ids := List.filter ((<>) id) !ids;
364 Hashtbl.remove !level2_patterns32 id;
365 with Not_found -> raise Interpretation_not_found);
367 List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
368 load_patterns32 !pattern32_matrix
370 let _ = load_patterns32 []
372 let instantiate_appl_pattern
373 ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern
376 try List.assoc name env
378 prerr_endline (sprintf "Name %s not found" name);
381 let rec aux = function
382 | Ast.UriPattern uri -> term_of_uri uri
383 | Ast.ImplicitPattern -> mk_implicit false
384 | Ast.VarPattern name -> lookup name
385 | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
390 let nmap_sequent0 ~idref ~subst (i,(n,context,ty):int * NCic.conjecture) =
391 let module K = Content in
392 let nast_of_cic = nast_of_cic1 ~idref ~output_type:`Term ~subst in
395 (fun item (res,context) ->
397 | name,NCic.Decl t ->
399 (* We should call build_decl_item, but we have not computed *)
400 (* the inner-types ==> we always produce a declaration *)
402 { K.dec_name = (Some name);
404 K.dec_inductive = false;
406 K.dec_type = nast_of_cic ~context t
407 })::res,item::context
408 | name,NCic.Def (t,ty) ->
410 (* We should call build_def_item, but we have not computed *)
411 (* the inner-types ==> we always produce a declaration *)
413 { K.def_name = (Some name);
416 K.def_term = nast_of_cic ~context t;
417 K.def_type = nast_of_cic ~context ty
418 })::res,item::context
421 ("-1",i,context',nast_of_cic ~context ty)
424 let nmap_sequent ~subst metasenv =
425 let module K = Content in
426 let ids_to_refs = Hashtbl.create 211 in
427 let register_ref = Hashtbl.add ids_to_refs in
428 nmap_sequent0 ~idref:(idref register_ref) ~subst metasenv, ids_to_refs
431 let object_prefix = "obj:";;
432 let declaration_prefix = "decl:";;
433 let definition_prefix = "def:";;
437 Ast.AttributedTerm (`IdRef id, _) -> id
441 let gen_id prefix seed =
442 let res = prefix ^ string_of_int !seed in
447 let build_def_item seed context metasenv id n t ty =
448 let module K = Content in
451 let sort = Hashtbl.find ids_to_inner_sorts id in
454 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
460 { K.def_name = Some n;
461 K.def_id = gen_id definition_prefix seed;
468 Not_found -> assert false
471 let build_decl_item seed id n s =
472 let module K = Content in
476 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
477 with Not_found -> None
482 { K.dec_name = name_of n;
483 K.dec_id = gen_id declaration_prefix seed;
484 K.dec_inductive = false;
491 { K.dec_name = Some n;
492 K.dec_id = gen_id declaration_prefix seed;
493 K.dec_inductive = false;
499 let nmap_obj (uri,_,metasenv,subst,kind) =
500 let module K = Content in
501 let ids_to_refs = Hashtbl.create 211 in
502 let register_ref = Hashtbl.add ids_to_refs in
503 let idref = idref register_ref in
505 nast_of_cic1 ~idref ~output_type:`Term ~subst in
510 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
511 (*CSC: used to be the previous line, that uses seed *)
512 Some (List.map (nmap_sequent0 ~idref ~subst) metasenv)
516 NCic.Constant (_,_,Some bo,ty,_) ->
517 let ty = nast_of_cic ~context:[] ty in
518 let bo = nast_of_cic ~context:[] bo in
519 (gen_id object_prefix seed, [], conjectures,
521 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
522 | NCic.Constant (_,_,None,ty,_) ->
523 let ty = nast_of_cic ~context:[] ty in
524 (gen_id object_prefix seed, [], conjectures,
526 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
527 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
529 | C.AInductiveDefinition (id,l,params,nparams,_) ->
530 (gen_id object_prefix seed, params, conjectures,
532 { K.joint_id = gen_id joint_prefix seed;
533 K.joint_kind = `Inductive nparams;
534 K.joint_defs = List.map (build_inductive seed) l
538 build_inductive seed =
539 let module K = Content in
542 { K.inductive_id = gen_id inductive_prefix seed;
543 K.inductive_name = n;
544 K.inductive_kind = b;
545 K.inductive_type = ty;
546 K.inductive_constructors = build_constructors seed l
550 build_constructors seed l =
551 let module K = Content in
554 { K.dec_name = Some n;
555 K.dec_id = gen_id declaration_prefix seed;
556 K.dec_inductive = false;