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 = NotationPt
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
37 let hide_coercions = ref true;;
40 type interpretation_id = int
43 { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
44 uri: (Cic.id, UriManager.uri) Hashtbl.t;
48 let idref register_ref =
52 let id = "i" ^ string_of_int !id in
53 (match reference with None -> () | Some r -> register_ref id r);
54 Ast.AttributedTerm (`IdRef id, t)
58 let name = NUri.name_of_uri u in
59 assert(String.length name > String.length "Type");
60 String.sub name 4 (String.length name - 4)
64 let is_nat_URI = NUri.eq (NUri.uri_of_string
65 "cic:/matita/ng/arithmetics/nat/nat.ind") in
66 let is_zero = function
67 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
68 is_nat_URI uri -> true
71 let is_succ = function
72 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
73 is_nat_URI uri -> true
76 let rec aux acc = function
77 | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
78 | t when is_zero t -> Some acc
83 (* CODICE c&p da NCicPp *)
84 let nast_of_cic0 status
86 ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
87 ~output_type ~metasenv ~subst k ~context =
91 let name,_ = List.nth context (n-1) in
92 let name = if name = "_" then "__"^string_of_int n else name in
93 idref (Ast.Ident (name,None))
94 with Failure "nth" | Invalid_argument "List.nth" ->
95 idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
96 | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
97 | NCic.Meta (n,lc) when List.mem_assoc n subst ->
98 let _,_,t,_ = List.assoc n subst in
99 k ~context (NCicSubstitution.subst_meta lc t)
100 | NCic.Meta (n,(s,l)) ->
101 (* CSC: qua non dovremmo espandere *)
102 let l = NCicUtils.expand_local_context l in
104 (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
105 | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
106 | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
107 | NCic.Sort NCic.Type ((`Type,u)::_) ->
108 idref(Ast.Sort (`NType (level_of_uri u)))
109 | NCic.Sort NCic.Type ((`CProp,u)::_) ->
110 idref(Ast.Sort (`NCProp (level_of_uri u)))
111 | NCic.Sort NCic.Type ((`Succ,u)::_) ->
112 idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
113 | NCic.Implicit `Hole -> idref (Ast.UserInput)
114 | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
115 | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
116 | NCic.Prod (n,s,t) ->
117 let n = if n.[0] = '_' then "_" else n in
118 let binder_kind = `Forall in
119 idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
120 k ~context:((n,NCic.Decl s)::context) t))
121 | NCic.Lambda (n,s,t) ->
122 idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
123 k ~context:((n,NCic.Decl s)::context) t))
124 | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
125 idref (Ast.Cast (k ~context ty, k ~context s))
126 | NCic.LetIn (n,s,ty,t) ->
127 idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
128 ty, k ~context:((n,NCic.Decl s)::context) t))
129 | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst ->
130 let _,_,t,_ = List.assoc n subst in
131 let hd = NCicSubstitution.subst_meta lc t in
133 (NCicReduction.head_beta_reduce ~upto:(List.length args)
135 | NCic.Appl l -> NCic.Appl (l@args)
136 | _ -> NCic.Appl (hd :: args)))
137 | NCic.Appl args as t ->
138 (match destroy_nat t with
139 | Some n -> idref (Ast.Num (string_of_int n, -1))
142 if not !hide_coercions then args
145 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
148 | Some (_,sats,cpos) ->
149 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
150 argomenti da saltare, come prima! *)
151 if cpos < List.length args - 1 then
152 List.nth args (cpos + 1) ::
153 try snd (HExtlib.split_nth (cpos+sats+2) args)
159 [arg] -> idref (k ~context arg)
160 | _ -> idref (Ast.Appl (List.map (k ~context) args))))
161 | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
162 let name = NUri.name_of_uri uri in
164 let uri_str = UriManager.string_of_uri uri in
165 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
167 UriManager.uri_of_string
168 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
172 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
173 let constructors, leftno =
174 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
175 let _,_,_,cl = List.nth tys n in
178 let rec eat_branch n ctx ty pat =
180 | NCic.Prod (name, s, t), _ when n > 0 ->
181 eat_branch (pred n) ctx t pat
182 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
183 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
184 (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
185 | _, _ -> [], k ~context:ctx pat
191 (fun (_, name, ty) pat ->
193 let name,(capture_variables,rhs) =
194 match output_type with
195 `Term -> name, eat_branch leftno context ty pat
196 | `Pattern -> "_", ([], k ~context pat)
198 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
199 ) constructors patterns
200 with Invalid_argument _ -> assert false
203 match output_type with
205 | `Term -> Some case_indty
207 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
210 (* persistent state *)
213 let initial_level2_patterns32 () = Hashtbl.create 211
214 let initial_interpretations () = Hashtbl.create 211
216 let level2_patterns32 = ref (initial_level2_patterns32 ())
217 (* symb -> id list ref *)
218 let interpretations = ref (initial_interpretations ())
220 let compiled32 = ref None
222 let pattern32_matrix = ref []
223 let counter = ref ~-1
228 stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
230 level2_patterns32 := initial_level2_patterns32 ();
231 interpretations := initial_interpretations ();
233 pattern32_matrix := []
239 | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
242 level2_patterns32 := olevel2_patterns32;
243 interpretations := ointerpretations;
244 compiled32 := ocompiled32;
245 pattern32_matrix := opattern32_matrix
249 let get_compiled32 () =
250 match !compiled32 with
251 | None -> assert false
252 | Some f -> Lazy.force f
254 let set_compiled32 f = compiled32 := Some f
257 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
259 let instantiate32 idrefs env symbol args =
260 let rec instantiate_arg = function
261 | Ast.IdentArg (n, name) ->
263 try List.assoc name env
264 with Not_found -> prerr_endline ("name not found in env: "^name);
267 let rec count_lambda = function
268 | Ast.AttributedTerm (_, t) -> count_lambda t
269 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
272 let rec add_lambda t n =
274 let name = NotationUtil.fresh_name () in
275 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
276 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
280 add_lambda t (n - count_lambda t)
283 let symbol = Ast.Symbol (symbol, 0) in
284 add_idrefs idrefs symbol
286 if args = [] then head
287 else Ast.Appl (head :: List.map instantiate_arg args)
289 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
290 match (get_compiled32 ()) term with
292 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
293 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
294 | Some (env, ctors, pid) ->
301 (match term with NCic.Const nref -> nref | _ -> assert false)
302 (NotationPt.Ident ("dummy",None))
305 Ast.AttributedTerm (`IdRef id, _) -> id
313 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
317 let _, symbol, args, _ =
319 Interpretations.find_level2_patterns32 pid
320 with Not_found -> assert false
322 let ast = instantiate32 idrefs env symbol args in
323 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
326 let load_patterns32 t =
328 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
330 set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
332 Interpretations.add_load_patterns32 load_patterns32;
333 Interpretations.init ()
342 let add_interpretation dsc (symbol, args) appl_pattern =
343 let id = fresh_id () in
344 Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
345 pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
346 load_patterns32 !pattern32_matrix;
348 let ids = Hashtbl.find !interpretations symbol in
350 with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
353 let get_all_interpretations () =
355 (function (_, _, id) ->
358 Hashtbl.find !level2_patterns32 id
359 with Not_found -> assert false
364 let get_active_interpretations () =
365 HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
368 let set_active_interpretations ids =
369 let pattern32_matrix' =
372 | (_, ap, id) when List.mem id ids -> (true, ap, id)
373 | (_, ap, id) -> (false, ap, id))
376 pattern32_matrix := pattern32_matrix';
377 load_patterns32 !pattern32_matrix
379 exception Interpretation_not_found
381 let lookup_interpretations symbol =
384 (List.sort Pervasives.compare
387 let (dsc, _, args, appl_pattern) =
389 Hashtbl.find !level2_patterns32 id
390 with Not_found -> assert false
392 dsc, args, appl_pattern)
393 !(Hashtbl.find !interpretations symbol)))
394 with Not_found -> raise Interpretation_not_found
396 let remove_interpretation id =
398 let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
399 let ids = Hashtbl.find !interpretations symbol in
400 ids := List.filter ((<>) id) !ids;
401 Hashtbl.remove !level2_patterns32 id;
402 with Not_found -> raise Interpretation_not_found);
404 List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
405 load_patterns32 !pattern32_matrix
407 let _ = load_patterns32 []
409 let instantiate_appl_pattern
410 ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern
413 try List.assoc name env
415 prerr_endline (sprintf "Name %s not found" name);
418 let rec aux = function
419 | Ast.UriPattern uri -> term_of_uri uri
420 | Ast.ImplicitPattern -> mk_implicit false
421 | Ast.VarPattern name -> lookup name
422 | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
427 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
428 let module K = Content in
430 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
433 (fun item (res,context) ->
435 | name,NCic.Decl t ->
437 (* We should call build_decl_item, but we have not computed *)
438 (* the inner-types ==> we always produce a declaration *)
440 { K.dec_name = (Some name);
442 K.dec_inductive = false;
444 K.dec_type = nast_of_cic ~context t
445 })::res,item::context
446 | name,NCic.Def (t,ty) ->
448 (* We should call build_def_item, but we have not computed *)
449 (* the inner-types ==> we always produce a declaration *)
451 { K.def_name = (Some name);
454 K.def_term = nast_of_cic ~context t;
455 K.def_type = nast_of_cic ~context ty
456 })::res,item::context
459 ("-1",i,context',nast_of_cic ~context ty)
462 let nmap_sequent status ~metasenv ~subst conjecture =
463 let module K = Content in
464 let ids_to_refs = Hashtbl.create 211 in
465 let register_ref = Hashtbl.add ids_to_refs in
466 nmap_sequent0 status ~idref:(idref register_ref) ~metasenv ~subst conjecture,
470 let object_prefix = "obj:";;
471 let declaration_prefix = "decl:";;
472 let definition_prefix = "def:";;
473 let inductive_prefix = "ind:";;
474 let joint_prefix = "joint:";;
478 Ast.AttributedTerm (`IdRef id, _) -> id
482 let gen_id prefix seed =
483 let res = prefix ^ string_of_int !seed in
488 let build_def_item seed context metasenv id n t ty =
489 let module K = Content in
492 let sort = Hashtbl.find ids_to_inner_sorts id in
495 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
501 { K.def_name = Some n;
502 K.def_id = gen_id definition_prefix seed;
509 Not_found -> assert false
512 let build_decl_item seed id n s =
513 let module K = Content in
517 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
518 with Not_found -> None
523 { K.dec_name = name_of n;
524 K.dec_id = gen_id declaration_prefix seed;
525 K.dec_inductive = false;
532 { K.dec_name = Some n;
533 K.dec_id = gen_id declaration_prefix seed;
534 K.dec_inductive = false;
540 let nmap_obj status (uri,_,metasenv,subst,kind) =
541 let module K = Content in
542 let ids_to_refs = Hashtbl.create 211 in
543 let register_ref = Hashtbl.add ids_to_refs in
544 let idref = idref register_ref in
546 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
551 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
552 (*CSC: used to be the previous line, that uses seed *)
553 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
555 let build_constructors seed l =
558 let ty = nast_of_cic ~context:[] ty in
559 { K.dec_name = Some n;
560 K.dec_id = gen_id declaration_prefix seed;
561 K.dec_inductive = false;
566 let build_inductive b seed =
568 let ty = nast_of_cic ~context:[] ty in
570 { K.inductive_id = gen_id inductive_prefix seed;
571 K.inductive_name = n;
572 K.inductive_kind = b;
573 K.inductive_type = ty;
574 K.inductive_constructors = build_constructors seed cl
577 let build_fixpoint b seed =
579 let t = nast_of_cic ~context:[] t in
580 let ty = nast_of_cic ~context:[] ty in
582 { K.def_id = gen_id inductive_prefix seed;
591 | NCic.Fixpoint (is_rec, ifl, _) ->
592 (gen_id object_prefix seed, [], conjectures,
594 { K.joint_id = gen_id joint_prefix seed;
597 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
599 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
601 | NCic.Inductive (is_ind, lno, itl, _) ->
602 (gen_id object_prefix seed, [], conjectures,
604 { K.joint_id = gen_id joint_prefix seed;
606 if is_ind then `Inductive lno else `CoInductive lno;
607 K.joint_defs = List.map (build_inductive is_ind seed) itl
609 | NCic.Constant (_,_,Some bo,ty,_) ->
610 let ty = nast_of_cic ~context:[] ty in
611 let bo = nast_of_cic ~context:[] bo in
612 (gen_id object_prefix seed, [], conjectures,
614 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
615 | NCic.Constant (_,_,None,ty,_) ->
616 let ty = nast_of_cic ~context:[] ty in
617 (gen_id object_prefix seed, [], conjectures,
619 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
620 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))