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;;
42 { sort: (cic_id, Ast.sort_kind) Hashtbl.t;
43 uri: (cic_id, NReference.reference) Hashtbl.t;
46 module IntMap = Map.Make(struct type t = int let compare = compare end);;
47 module StringMap = Map.Make(String);;
51 pattern32_matrix: (bool * NotationPt.cic_appl_pattern * int) list;
53 (string * string * NotationPt.argument_pattern list *
54 NotationPt.cic_appl_pattern) IntMap.t;
55 interpretations: int list StringMap.t; (* symb -> id list *)
57 (NCic.term -> ((string * NCic.term) list * NCic.term list * int) option)
61 let initial_db status = {
63 pattern32_matrix = [];
64 level2_patterns32 = IntMap.empty;
65 interpretations = StringMap.empty;
66 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status [])
71 inherit NCicCoercion.g_status
75 class virtual status =
77 inherit NCicCoercion.status
78 val mutable interp_db = None (* mutable only to initialize it :-( *)
79 method interp_db = match interp_db with None -> assert false | Some x -> x
80 method set_interp_db v = {< interp_db = Some v >}
81 method set_interp_status
82 : 'status. #g_status as 'status -> 'self
83 = fun o -> {< interp_db = Some o#interp_db >}#set_coercion_status o
85 interp_db <- Some (initial_db self)
88 let idref register_ref =
92 let id = "i" ^ string_of_int !id in
93 (match reference with None -> () | Some r -> register_ref id r);
94 Ast.AttributedTerm (`IdRef id, t)
98 let name = NUri.name_of_uri u in
99 assert(String.length name > String.length "Type");
100 String.sub name 4 (String.length name - 4)
103 let find_level2_patterns32 status pid =
104 IntMap.find pid status#interp_db.level2_patterns32
107 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
109 let instantiate32 idrefs env symbol args =
110 let rec instantiate_arg = function
111 | Ast.IdentArg (n, name) ->
113 try List.assoc name env
114 with Not_found -> prerr_endline ("name not found in env: "^name);
117 let rec count_lambda = function
118 | Ast.AttributedTerm (_, t) -> count_lambda t
119 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
122 let rec add_lambda t n =
124 let name = NotationUtil.fresh_name () in
125 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
126 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
130 add_lambda t (n - count_lambda t)
133 let symbol = Ast.Symbol (symbol, 0) in
134 add_idrefs idrefs symbol
136 if args = [] then head
137 else Ast.Appl (head :: List.map instantiate_arg args)
139 let fresh_id status =
140 let counter = status#interp_db.counter+1 in
141 status#set_interp_db ({ status#interp_db with counter = counter }), counter
143 let load_patterns32 status t =
145 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
148 {status#interp_db with
149 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler status t) }
152 let add_interpretation status dsc (symbol, args) appl_pattern =
153 let status,id = fresh_id status in
156 id::StringMap.find symbol status#interp_db.interpretations
157 with Not_found -> [id] in
159 status#set_interp_db { status#interp_db with
161 IntMap.add id (dsc, symbol, args, appl_pattern)
162 status#interp_db.level2_patterns32;
163 pattern32_matrix = (true,appl_pattern,id)::status#interp_db.pattern32_matrix;
164 interpretations = StringMap.add symbol ids status#interp_db.interpretations
167 load_patterns32 status status#interp_db.pattern32_matrix
169 let toggle_active_interpretations status b =
170 status#set_interp_db { status#interp_db with
172 List.map (fun (_,ap,id) -> b,ap,id) status#interp_db.pattern32_matrix }
174 exception Interpretation_not_found
176 let lookup_interpretations status ?(sorted=true) symbol =
181 let (dsc, _, args, appl_pattern) =
182 try IntMap.find id status#interp_db.level2_patterns32
183 with Not_found -> assert false
185 dsc, args, appl_pattern
186 ) (StringMap.find symbol status#interp_db.interpretations)
188 if sorted then HExtlib.list_uniq (List.sort Pervasives.compare raw)
190 with Not_found -> raise Interpretation_not_found
192 let instantiate_appl_pattern
193 ~mk_appl ~mk_implicit ~term_of_nref env appl_pattern
196 try List.assoc name env
198 prerr_endline (sprintf "Name %s not found" name);
201 let rec aux = function
202 | Ast.NRefPattern nref -> term_of_nref nref
203 | Ast.ImplicitPattern -> mk_implicit false
204 | Ast.VarPattern name -> lookup name
205 | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
210 let is_nat_URI = NUri.eq (NUri.uri_of_string
211 "cic:/matita/arithmetics/nat/nat.ind") in
212 let is_zero = function
213 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
214 is_nat_URI uri -> true
217 let is_succ = function
218 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
219 is_nat_URI uri -> true
222 let rec aux acc = function
223 | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
224 | t when is_zero t -> Some acc
229 (* CODICE c&p da NCicPp *)
230 let nast_of_cic0 status
232 ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
233 ~output_type ~metasenv ~subst k ~context =
237 let name,_ = List.nth context (n-1) in
238 let name = if name = "_" then "__"^string_of_int n else name in
239 idref (Ast.Ident (name,None))
240 with Failure "nth" | Invalid_argument "List.nth" ->
241 idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
242 | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s status true r, None))
243 | NCic.Meta (n,lc) when List.mem_assoc n subst ->
244 let _,_,t,_ = List.assoc n subst in
245 k ~context (NCicSubstitution.subst_meta status lc t)
246 | NCic.Meta (n,(s,l)) ->
247 (* CSC: qua non dovremmo espandere *)
248 let l = NCicUtils.expand_local_context l in
250 (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift status s x))) l))
251 | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
252 | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
253 | NCic.Sort NCic.Type ((`Type,u)::_) ->
254 idref(Ast.Sort (`NType (level_of_uri u)))
255 | NCic.Sort NCic.Type ((`CProp,u)::_) ->
256 idref(Ast.Sort (`NCProp (level_of_uri u)))
257 | NCic.Sort NCic.Type ((`Succ,u)::_) ->
258 idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
259 | NCic.Implicit `Hole -> idref (Ast.UserInput)
260 | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
261 | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
262 | NCic.Prod (n,s,t) ->
263 let n = if n.[0] = '_' then "_" else n in
264 let binder_kind = `Forall in
265 idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
266 k ~context:((n,NCic.Decl s)::context) t))
267 | NCic.Lambda (n,s,t) ->
268 idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
269 k ~context:((n,NCic.Decl s)::context) t))
270 | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
271 idref (Ast.Cast (k ~context ty, k ~context s))
272 | NCic.LetIn (n,s,ty,t) ->
273 idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
274 ty, k ~context:((n,NCic.Decl s)::context) t))
275 | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst ->
276 let _,_,t,_ = List.assoc n subst in
277 let hd = NCicSubstitution.subst_meta status lc t in
279 (NCicReduction.head_beta_reduce status ~upto:(List.length args)
281 | NCic.Appl l -> NCic.Appl (l@args)
282 | _ -> NCic.Appl (hd :: args)))
283 | NCic.Appl args as t ->
284 (match destroy_nat t with
285 | Some n -> idref (Ast.Num (string_of_int n, -1))
288 if not !hide_coercions then args
291 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
294 | Some (_,sats,cpos) ->
295 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
296 argomenti da saltare, come prima! *)
297 if cpos < List.length args - 1 then
298 List.nth args (cpos + 1) ::
299 try snd (HExtlib.split_nth (cpos+sats+2) args)
305 [arg] -> idref (k ~context arg)
306 | _ -> idref (Ast.Appl (List.map (k ~context) args))))
307 | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
309 let name = NUri.name_of_uri uri in
311 let uri_str = UriManager.string_of_uri uri in
312 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
314 UriManager.uri_of_string
315 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
319 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
320 let constructors, leftno =
321 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys status r in
322 let _,_,_,cl = List.nth tys n in
325 let rec eat_branch n ctx ty pat =
327 | NCic.Prod (name, s, t), _ when n > 0 ->
328 eat_branch (pred n) ctx t pat
329 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
330 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
331 (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
332 | _, _ -> [], k ~context:ctx pat
338 (fun (_, name, ty) pat ->
340 let name,(capture_variables,rhs) =
341 match output_type with
342 `Term -> name, eat_branch leftno context ty pat
343 | `Pattern -> "_", ([], k ~context pat)
345 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
346 ) constructors patterns
347 with Invalid_argument _ -> assert false
350 match output_type with
352 | `Term -> Some case_indty
354 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
356 NCicEnvironment.ObjectNotFound msg ->
357 idref (Ast.Case(k ~context te,Some ("NOT_FOUND: " ^ Lazy.force msg,None),
358 Some (k ~context outty),
359 (List.map (fun t -> Ast.Pattern ("????", None, []), k ~context t)
363 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
364 match Lazy.force status#interp_db.compiled32 term with
366 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
367 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
368 | Some (env, ctors, pid) ->
375 (match term with NCic.Const nref -> nref | _ -> assert false)
376 (NotationPt.Ident ("dummy",None))
379 Ast.AttributedTerm (`IdRef id, _) -> id
387 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
391 let _, symbol, args, _ =
393 find_level2_patterns32 status pid
394 with Not_found -> assert false
396 let ast = instantiate32 idrefs env symbol args in
397 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
400 let nmap_context0 status ~idref ~metasenv ~subst context =
401 let module K = Content in
403 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
407 (fun item (res,context) ->
409 | name,NCic.Decl t ->
411 (* We should call build_decl_item, but we have not computed *)
412 (* the inner-types ==> we always produce a declaration *)
414 { K.dec_name = (Some name);
416 K.dec_inductive = false;
418 K.dec_type = nast_of_cic ~context t
419 })::res,item::context
420 | name,NCic.Def (t,ty) ->
422 (* We should call build_def_item, but we have not computed *)
423 (* the inner-types ==> we always produce a declaration *)
425 { K.def_name = (Some name);
428 K.def_term = nast_of_cic ~context t;
429 K.def_type = nast_of_cic ~context ty
430 })::res,item::context
434 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
435 let module K = Content in
437 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
438 let context' = nmap_context0 status ~idref ~metasenv ~subst context in
439 ("-1",i,context',nast_of_cic ~context ty)
442 let object_prefix = "obj:";;
443 let declaration_prefix = "decl:";;
444 let definition_prefix = "def:";;
445 let inductive_prefix = "ind:";;
446 let joint_prefix = "joint:";;
450 Ast.AttributedTerm (`IdRef id, _) -> id
454 let gen_id prefix seed =
455 let res = prefix ^ string_of_int !seed in
460 let build_def_item seed context metasenv id n t ty =
461 let module K = Content in
464 let sort = Hashtbl.find ids_to_inner_sorts id in
467 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
473 { K.def_name = Some n;
474 K.def_id = gen_id definition_prefix seed;
481 Not_found -> assert false
484 let build_decl_item seed id n s =
485 let module K = Content in
489 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
490 with Not_found -> None
495 { K.dec_name = name_of n;
496 K.dec_id = gen_id declaration_prefix seed;
497 K.dec_inductive = false;
504 { K.dec_name = Some n;
505 K.dec_id = gen_id declaration_prefix seed;
506 K.dec_inductive = false;
512 let nmap_cobj0 status ~idref (uri,_,metasenv,subst,kind) =
513 let module K = Content in
515 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
520 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
521 (*CSC: used to be the previous line, that uses seed *)
522 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
524 let build_constructors seed l =
527 let ty = nast_of_cic ~context:[] ty in
528 { K.dec_name = Some n;
529 K.dec_id = gen_id declaration_prefix seed;
530 K.dec_inductive = false;
535 let build_inductive b seed =
537 let ty = nast_of_cic ~context:[] ty in
539 { K.inductive_id = gen_id inductive_prefix seed;
540 K.inductive_name = n;
541 K.inductive_kind = b;
542 K.inductive_type = ty;
543 K.inductive_constructors = build_constructors seed cl
546 let build_fixpoint b seed =
548 let t = nast_of_cic ~context:[] t in
549 let ty = nast_of_cic ~context:[] ty in
551 { K.def_id = gen_id inductive_prefix seed;
559 | NCic.Fixpoint (is_rec, ifl, _) ->
560 (gen_id object_prefix seed, conjectures,
562 { K.joint_id = gen_id joint_prefix seed;
565 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
567 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
569 | NCic.Inductive (is_ind, lno, itl, _) ->
570 (gen_id object_prefix seed, conjectures,
572 { K.joint_id = gen_id joint_prefix seed;
574 if is_ind then `Inductive lno else `CoInductive lno;
575 K.joint_defs = List.map (build_inductive is_ind seed) itl
577 | NCic.Constant (_,_,Some bo,ty,_) ->
578 let ty = nast_of_cic ~context:[] ty in
579 let bo = nast_of_cic ~context:[] bo in
580 (gen_id object_prefix seed, conjectures,
582 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
583 | NCic.Constant (_,_,None,ty,_) ->
584 let ty = nast_of_cic ~context:[] ty in
585 (gen_id object_prefix seed, conjectures,
587 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
588 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
591 let with_idrefs foo status obj =
592 let ids_to_refs = Hashtbl.create 211 in
593 let register_ref = Hashtbl.add ids_to_refs in
594 foo status ~idref:(idref register_ref) obj, ids_to_refs
597 let nmap_cobj status = with_idrefs nmap_cobj0 status
599 let nmap_sequent status ~metasenv ~subst =
600 with_idrefs (nmap_sequent0 ~metasenv ~subst) status
602 let nmap_term status ~metasenv ~subst ~context =
603 with_idrefs (nast_of_cic1 ~output_type:`Term ~metasenv ~subst ~context) status
605 let nmap_context status ~metasenv ~subst =
606 with_idrefs (nmap_context0 ~metasenv ~subst) status
608 (* FG ***********************************************************************)
610 let nmap_obj0 status ~idref (_, _, metasenv, subst, kind) =
611 let module N = NotationPt in
613 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
615 let rec mk_captures lno k c u = match lno, u with
617 | _, NCic.Prod (n, w, u) when lno > 0 ->
618 let cap = nast_of_cic ~context:c w, None in
619 let hyp = n, NCic.Decl w in
620 mk_captures (pred lno) (cap :: k) (hyp :: c) u
623 let build_captures lno = function
625 | (_, _, u, _) :: _ -> mk_captures lno [] [] u
627 let rec eat_prods prods lno t = match prods, lno, t with
629 | true, _, NCic.Prod (_, _, t) when lno > 0 -> eat_prods prods (pred lno) t
630 | false, _, NCic.Lambda (_, _, t) when lno > 0 -> eat_prods prods (pred lno) t
633 let build_constractor lno context (_, n, bo) =
634 let bo = nast_of_cic ~context (eat_prods false lno bo) in
637 let build_inductive is_ind lno context (_, n, ty, cl) =
638 let ty = nast_of_cic ~context (eat_prods true lno ty) in
639 n, is_ind, ty, List.map (build_constractor lno context) cl
642 | NCic.Constant (_, n, xbo, ty, (_, flavour, pragma)) ->
643 let ty = nast_of_cic ~context:[] ty in
644 let xbo = match xbo with
645 | Some bo -> Some (nast_of_cic ~context:[] bo)
648 N.Theorem (flavour, n, ty, xbo, pragma)
649 | NCic.Inductive (is_ind, lno, itl, (_, `Regular)) ->
650 let captures, context = build_captures lno itl in
651 N.Inductive (captures, List.map (build_inductive is_ind lno context) itl)
652 | _ -> assert false (* NCic.Fixpoint (is_rec, ifl, _) -> *)
654 let nmap_obj status = with_idrefs nmap_obj0 status