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/
30 module Ast = NotationPt
34 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
37 let hide_coercions = ref true;;
43 { sort: (cic_id, Ast.sort_kind) Hashtbl.t;
44 uri: (cic_id, NReference.reference) Hashtbl.t;
48 module IntMap = Map.Make(struct type t = int let compare = compare end);;
49 module StringMap = Map.Make(String);;
53 pattern32_matrix: (bool * NotationPt.cic_appl_pattern * int) list;
55 (string * string * NotationPt.argument_pattern list *
56 NotationPt.cic_appl_pattern) IntMap.t;
57 interpretations: int list StringMap.t; (* symb -> id list *)
59 (NCic.term -> ((string * NCic.term) list * NCic.term list * int) option)
63 let initial_db status = {
65 pattern32_matrix = [];
66 level2_patterns32 = IntMap.empty;
67 interpretations = StringMap.empty;
68 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status [])
73 inherit NCicCoercion.g_status
77 class virtual status =
79 inherit NCicCoercion.status
80 val mutable interp_db = None (* mutable only to initialize it :-( *)
81 method interp_db = match interp_db with None -> assert false | Some x -> x
82 method set_interp_db v = {< interp_db = Some v >}
83 method set_interp_status
84 : 'status. #g_status as 'status -> 'self
85 = fun o -> {< interp_db = Some o#interp_db >}#set_coercion_status o
87 interp_db <- Some (initial_db self)
90 let idref register_ref =
94 let id = "i" ^ string_of_int !id in
95 (match reference with None -> () | Some r -> register_ref id r);
96 Ast.AttributedTerm (`IdRef id, t)
100 let name = NUri.name_of_uri u in
101 assert(String.length name > String.length "Type");
102 String.sub name 4 (String.length name - 4)
105 let find_level2_patterns32 status pid =
106 IntMap.find pid status#interp_db.level2_patterns32
109 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
111 let instantiate32 idrefs env symbol args =
112 let instantiate_arg = function
113 | Ast.IdentArg (n, name) ->
115 try List.assoc name env
116 with Not_found -> prerr_endline ("name not found in env: "^name);
119 let rec count_lambda = function
120 | Ast.AttributedTerm (_, t) -> count_lambda t
121 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
124 let rec add_lambda t n =
126 let name = NotationUtil.fresh_name () in
127 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
128 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
132 add_lambda t (n - count_lambda t)
135 let symbol = Ast.Symbol (symbol, 0) in
136 add_idrefs idrefs symbol
138 if args = [] then head
139 else Ast.Appl (head :: List.map instantiate_arg args)
141 let fresh_id status =
142 let counter = status#interp_db.counter+1 in
143 status#set_interp_db ({ status#interp_db with counter = counter }), counter
145 let load_patterns32 status t =
147 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
150 {status#interp_db with
151 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status t) }
154 let add_interpretation status dsc (symbol, args) appl_pattern =
155 let status,id = fresh_id status in
158 id::StringMap.find symbol status#interp_db.interpretations
159 with Not_found -> [id] in
161 status#set_interp_db { status#interp_db with
163 IntMap.add id (dsc, symbol, args, appl_pattern)
164 status#interp_db.level2_patterns32;
165 pattern32_matrix = (true,appl_pattern,id)::status#interp_db.pattern32_matrix;
166 interpretations = StringMap.add symbol ids status#interp_db.interpretations
169 load_patterns32 status status#interp_db.pattern32_matrix
171 let toggle_active_interpretations status b =
172 status#set_interp_db { status#interp_db with
174 List.map (fun (_,ap,id) -> b,ap,id) status#interp_db.pattern32_matrix }
176 exception Interpretation_not_found
178 let lookup_interpretations status ?(sorted=true) symbol =
183 let (dsc, _, args, appl_pattern) =
184 try IntMap.find id status#interp_db.level2_patterns32
185 with Not_found -> assert false
187 dsc, args, appl_pattern
188 ) (StringMap.find symbol status#interp_db.interpretations)
190 if sorted then HExtlib.list_uniq (List.sort Stdlib.compare raw)
192 with Not_found -> raise Interpretation_not_found
194 let instantiate_appl_pattern
195 ~mk_appl ~mk_implicit ~term_of_nref env appl_pattern
198 try List.assoc name env
200 prerr_endline (sprintf "Name %s not found" name);
203 let rec aux = function
204 | Ast.NRefPattern nref -> term_of_nref nref
205 | Ast.ImplicitPattern -> mk_implicit false
206 | Ast.VarPattern name -> lookup name
207 | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
212 let is_nat_URI = NUri.eq (NUri.uri_of_string
213 "cic:/matita/arithmetics/nat/nat.ind") in
214 let is_zero = function
215 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
216 is_nat_URI uri -> true
219 let is_succ = function
220 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
221 is_nat_URI uri -> true
224 let rec aux acc = function
225 | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
226 | t when is_zero t -> Some acc
231 (* CODICE c&p da NCicPp *)
232 let nast_of_cic0 status
234 ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
235 ~output_type ~metasenv ~subst k ~context =
239 let name,_ = List.nth context (n-1) in
240 let name = if name = "_" then "__"^string_of_int n else name in
241 idref (Ast.Ident (name,None))
242 with Failure "nth" | Invalid_argument "List.nth" ->
243 idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
244 | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s status true r, None))
245 | NCic.Meta (n,lc) when List.mem_assoc n subst ->
246 let _,_,t,_ = List.assoc n subst in
247 k ~context (NCicSubstitution.subst_meta status lc t)
248 | NCic.Meta (n,(s,l)) ->
249 (* CSC: qua non dovremmo espandere *)
250 let l = NCicUtils.expand_local_context l in
252 (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift status s x))) l))
253 | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
254 | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
255 | NCic.Sort NCic.Type ((`Type,u)::_) ->
256 idref(Ast.Sort (`NType (level_of_uri u)))
257 | NCic.Sort NCic.Type ((`CProp,u)::_) ->
258 idref(Ast.Sort (`NCProp (level_of_uri u)))
259 | NCic.Sort NCic.Type ((`Succ,u)::_) ->
260 idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
261 | NCic.Implicit `Hole -> idref (Ast.UserInput)
262 | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
263 | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
264 | NCic.Prod (n,s,t) ->
265 let n = if n.[0] = '_' then "_" else n in
266 let binder_kind = `Forall in
267 idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
268 k ~context:((n,NCic.Decl s)::context) t))
269 | NCic.Lambda (n,s,t) ->
270 idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
271 k ~context:((n,NCic.Decl s)::context) t))
272 | NCic.LetIn (_n,s,ty,NCic.Rel 1) ->
273 idref (Ast.Cast (k ~context ty, k ~context s))
274 | NCic.LetIn (n,s,ty,t) ->
275 idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
276 ty, k ~context:((n,NCic.Decl s)::context) t))
277 | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst ->
278 let _,_,t,_ = List.assoc n subst in
279 let hd = NCicSubstitution.subst_meta status lc t in
281 (NCicReduction.head_beta_reduce status ~upto:(List.length args)
283 | NCic.Appl l -> NCic.Appl (l@args)
284 | _ -> NCic.Appl (hd :: args)))
285 | NCic.Appl args as t ->
286 (match destroy_nat t with
287 | Some n -> idref (Ast.Num (string_of_int n, -1))
290 if not !hide_coercions then args
293 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
296 | Some (_,sats,cpos) ->
297 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
298 argomenti da saltare, come prima! *)
299 if cpos < List.length args - 1 then
300 List.nth args (cpos + 1) ::
301 try snd (HExtlib.split_nth (cpos+sats+2) args)
307 [arg] -> idref (k ~context arg)
308 | _ -> idref (Ast.Appl (List.map (k ~context) args))))
309 | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
311 let name = NUri.name_of_uri uri in
313 let uri_str = UriManager.string_of_uri uri in
314 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
316 UriManager.uri_of_string
317 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
321 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
322 let constructors, leftno =
323 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys status r in
324 let _,_,_,cl = List.nth tys n in
327 let rec eat_branch n ctx ty pat =
329 | NCic.Prod (_name, _s, t), _ when n > 0 ->
330 eat_branch (pred n) ctx t pat
331 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
332 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
333 (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
334 | _, _ -> [], k ~context:ctx pat
340 (fun (_, name, ty) pat ->
342 let name,(capture_variables,rhs) =
343 match output_type with
344 `Term -> name, eat_branch leftno context ty pat
345 | `Pattern -> "_", ([], k ~context pat)
347 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
348 ) constructors patterns
349 with Invalid_argument _ -> assert false
352 match output_type with
354 | `Term -> Some case_indty
356 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
358 NCicEnvironment.ObjectNotFound msg ->
359 idref (Ast.Case(k ~context te,Some ("NOT_FOUND: " ^ Lazy.force msg,None),
360 Some (k ~context outty),
361 (List.map (fun t -> Ast.Pattern ("????", None, []), k ~context t)
365 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
366 match Lazy.force status#interp_db.compiled32 term with
368 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
369 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
370 | Some (env, ctors, pid) ->
377 (match term with NCic.Const nref -> nref | _ -> assert false)
378 (NotationPt.Ident ("dummy",None))
381 Ast.AttributedTerm (`IdRef id, _) -> id
389 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
393 let _, symbol, args, _ =
395 find_level2_patterns32 status pid
396 with Not_found -> assert false
398 let ast = instantiate32 idrefs env symbol args in
399 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
402 let nmap_context0 status ~idref ~metasenv ~subst context =
403 let module K = Content in
405 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
409 (fun item (res,context) ->
411 | name,NCic.Decl t ->
413 (* We should call build_decl_item, but we have not computed *)
414 (* the inner-types ==> we always produce a declaration *)
416 { K.dec_name = (Some name);
418 K.dec_inductive = false;
420 K.dec_type = nast_of_cic ~context t
421 })::res,item::context
422 | name,NCic.Def (t,ty) ->
424 (* We should call build_def_item, but we have not computed *)
425 (* the inner-types ==> we always produce a declaration *)
427 { K.def_name = (Some name);
430 K.def_term = nast_of_cic ~context t;
431 K.def_type = nast_of_cic ~context ty
432 })::res,item::context
436 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(_n,context,ty)) =
437 let module K = Content in
439 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
440 let context' = nmap_context0 status ~idref ~metasenv ~subst context in
441 ("-1",i,context',nast_of_cic ~context ty)
444 let object_prefix = "obj:";;
445 let declaration_prefix = "decl:";;
446 let definition_prefix = "def:";;
447 let inductive_prefix = "ind:";;
448 let joint_prefix = "joint:";;
452 Ast.AttributedTerm (`IdRef id, _) -> id
456 let gen_id prefix seed =
457 let res = prefix ^ string_of_int !seed in
462 let build_def_item seed _context _metasenv id n t ty =
463 let module K = Content in
466 let sort = Hashtbl.find ids_to_inner_sorts id in
469 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
475 { K.def_name = Some n;
476 K.def_id = gen_id definition_prefix seed;
483 Not_found -> assert false
486 let build_decl_item seed id n s =
487 let module K = Content in
491 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
492 with Not_found -> None
497 { K.dec_name = name_of n;
498 K.dec_id = gen_id declaration_prefix seed;
499 K.dec_inductive = false;
506 { K.dec_name = Some n;
507 K.dec_id = gen_id declaration_prefix seed;
508 K.dec_inductive = false;
514 let nmap_cobj0 status ~idref (uri,_,metasenv,subst,kind) =
515 let module K = Content in
517 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
522 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
523 (*CSC: used to be the previous line, that uses seed *)
524 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
526 let build_constructors seed l =
529 let ty = nast_of_cic ~context:[] ty in
530 { K.dec_name = Some n;
531 K.dec_id = gen_id declaration_prefix seed;
532 K.dec_inductive = false;
537 let build_inductive b seed =
539 let ty = nast_of_cic ~context:[] ty in
541 { K.inductive_id = gen_id inductive_prefix seed;
542 K.inductive_name = n;
543 K.inductive_kind = b;
544 K.inductive_type = ty;
545 K.inductive_constructors = build_constructors seed cl
548 let build_fixpoint _b seed =
550 let t = nast_of_cic ~context:[] t in
551 let ty = nast_of_cic ~context:[] ty in
553 { K.def_id = gen_id inductive_prefix seed;
561 | NCic.Fixpoint (is_rec, ifl, _) ->
562 (gen_id object_prefix seed, conjectures,
564 { K.joint_id = gen_id joint_prefix seed;
567 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
569 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
571 | NCic.Inductive (is_ind, lno, itl, _) ->
572 (gen_id object_prefix seed, conjectures,
574 { K.joint_id = gen_id joint_prefix seed;
576 if is_ind then `Inductive lno else `CoInductive lno;
577 K.joint_defs = List.map (build_inductive is_ind seed) itl
579 | NCic.Constant (_,_,Some bo,ty,_) ->
580 let ty = nast_of_cic ~context:[] ty in
581 let bo = nast_of_cic ~context:[] bo in
582 (gen_id object_prefix seed, conjectures,
584 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
585 | NCic.Constant (_,_,None,ty,_) ->
586 let ty = nast_of_cic ~context:[] ty in
587 (gen_id object_prefix seed, conjectures,
589 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
590 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
593 let with_idrefs foo status obj =
594 let ids_to_refs = Hashtbl.create 211 in
595 let register_ref = Hashtbl.add ids_to_refs in
596 foo status ~idref:(idref register_ref) obj, ids_to_refs
599 let nmap_cobj status = with_idrefs nmap_cobj0 status
601 let nmap_sequent status ~metasenv ~subst =
602 with_idrefs (nmap_sequent0 ~metasenv ~subst) status
604 let nmap_term status ~metasenv ~subst ~context =
605 with_idrefs (nast_of_cic1 ~output_type:`Term ~metasenv ~subst ~context) status
607 let nmap_context status ~metasenv ~subst =
608 with_idrefs (nmap_context0 ~metasenv ~subst) status
610 (* FG ***********************************************************************)
612 let nmap_obj0 status ~idref (_, _, metasenv, subst, kind) =
613 let module N = NotationPt in
615 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
617 let rec mk_captures lno k c u = match lno, u with
619 | _, NCic.Prod (n, w, u) when lno > 0 ->
620 let cap = nast_of_cic ~context:c w, None in
621 let hyp = n, NCic.Decl w in
622 mk_captures (pred lno) (cap :: k) (hyp :: c) u
625 let build_captures lno = function
627 | (_, _, u, _) :: _ -> mk_captures lno [] [] u
629 let rec eat_prods prods lno t = match prods, lno, t with
631 | true, _, NCic.Prod (_, _, t) when lno > 0 -> eat_prods prods (pred lno) t
632 | false, _, NCic.Lambda (_, _, t) when lno > 0 -> eat_prods prods (pred lno) t
635 let build_constractor lno context (_, n, bo) =
636 let bo = nast_of_cic ~context (eat_prods false lno bo) in
639 let build_inductive is_ind lno context (_, n, ty, cl) =
640 let ty = nast_of_cic ~context (eat_prods true lno ty) in
641 n, is_ind, ty, List.map (build_constractor lno context) cl
644 | NCic.Constant (_, n, xbo, ty, attrs) ->
645 let ty = nast_of_cic ~context:[] ty in
646 let xbo = match xbo with
647 | Some bo -> Some (nast_of_cic ~context:[] bo)
650 N.Theorem (n, ty, xbo, attrs)
651 | NCic.Inductive (is_ind, lno, itl, (src, `Regular)) ->
652 let captures, context = build_captures lno itl in
653 N.Inductive (captures, List.map (build_inductive is_ind lno context) itl, src)
654 | _ -> assert false (* NCic.Fixpoint (is_rec, ifl, _) -> *)
656 let nmap_obj status = with_idrefs nmap_obj0 status