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) ->
308 let name = NUri.name_of_uri uri in
310 let uri_str = UriManager.string_of_uri uri in
311 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
313 UriManager.uri_of_string
314 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
318 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
319 let constructors, leftno =
320 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys status r in
321 let _,_,_,cl = List.nth tys n in
324 let rec eat_branch n ctx ty pat =
326 | NCic.Prod (name, s, t), _ when n > 0 ->
327 eat_branch (pred n) ctx t pat
328 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
329 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
330 (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
331 | _, _ -> [], k ~context:ctx pat
337 (fun (_, name, ty) pat ->
339 let name,(capture_variables,rhs) =
340 match output_type with
341 `Term -> name, eat_branch leftno context ty pat
342 | `Pattern -> "_", ([], k ~context pat)
344 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
345 ) constructors patterns
346 with Invalid_argument _ -> assert false
349 match output_type with
351 | `Term -> Some case_indty
353 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
356 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
357 match Lazy.force status#interp_db.compiled32 term with
359 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
360 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
361 | Some (env, ctors, pid) ->
368 (match term with NCic.Const nref -> nref | _ -> assert false)
369 (NotationPt.Ident ("dummy",None))
372 Ast.AttributedTerm (`IdRef id, _) -> id
380 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
384 let _, symbol, args, _ =
386 find_level2_patterns32 status pid
387 with Not_found -> assert false
389 let ast = instantiate32 idrefs env symbol args in
390 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
393 let nmap_context0 status ~idref ~metasenv ~subst context =
394 let module K = Content in
396 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
400 (fun item (res,context) ->
402 | name,NCic.Decl t ->
404 (* We should call build_decl_item, but we have not computed *)
405 (* the inner-types ==> we always produce a declaration *)
407 { K.dec_name = (Some name);
409 K.dec_inductive = false;
411 K.dec_type = nast_of_cic ~context t
412 })::res,item::context
413 | name,NCic.Def (t,ty) ->
415 (* We should call build_def_item, but we have not computed *)
416 (* the inner-types ==> we always produce a declaration *)
418 { K.def_name = (Some name);
421 K.def_term = nast_of_cic ~context t;
422 K.def_type = nast_of_cic ~context ty
423 })::res,item::context
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
431 let context' = nmap_context0 status ~idref ~metasenv ~subst context in
432 ("-1",i,context',nast_of_cic ~context ty)
435 let object_prefix = "obj:";;
436 let declaration_prefix = "decl:";;
437 let definition_prefix = "def:";;
438 let inductive_prefix = "ind:";;
439 let joint_prefix = "joint:";;
443 Ast.AttributedTerm (`IdRef id, _) -> id
447 let gen_id prefix seed =
448 let res = prefix ^ string_of_int !seed in
453 let build_def_item seed context metasenv id n t ty =
454 let module K = Content in
457 let sort = Hashtbl.find ids_to_inner_sorts id in
460 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
466 { K.def_name = Some n;
467 K.def_id = gen_id definition_prefix seed;
474 Not_found -> assert false
477 let build_decl_item seed id n s =
478 let module K = Content in
482 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
483 with Not_found -> None
488 { K.dec_name = name_of n;
489 K.dec_id = gen_id declaration_prefix seed;
490 K.dec_inductive = false;
497 { K.dec_name = Some n;
498 K.dec_id = gen_id declaration_prefix seed;
499 K.dec_inductive = false;
505 let nmap_obj0 status ~idref (uri,_,metasenv,subst,kind) =
506 let module K = Content in
508 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
513 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
514 (*CSC: used to be the previous line, that uses seed *)
515 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
517 let build_constructors seed l =
520 let ty = nast_of_cic ~context:[] ty in
521 { K.dec_name = Some n;
522 K.dec_id = gen_id declaration_prefix seed;
523 K.dec_inductive = false;
528 let build_inductive b seed =
530 let ty = nast_of_cic ~context:[] ty in
532 { K.inductive_id = gen_id inductive_prefix seed;
533 K.inductive_name = n;
534 K.inductive_kind = b;
535 K.inductive_type = ty;
536 K.inductive_constructors = build_constructors seed cl
539 let build_fixpoint b seed =
541 let t = nast_of_cic ~context:[] t in
542 let ty = nast_of_cic ~context:[] ty in
544 { K.def_id = gen_id inductive_prefix seed;
552 | NCic.Fixpoint (is_rec, ifl, _) ->
553 (gen_id object_prefix seed, conjectures,
555 { K.joint_id = gen_id joint_prefix seed;
558 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
560 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
562 | NCic.Inductive (is_ind, lno, itl, _) ->
563 (gen_id object_prefix seed, conjectures,
565 { K.joint_id = gen_id joint_prefix seed;
567 if is_ind then `Inductive lno else `CoInductive lno;
568 K.joint_defs = List.map (build_inductive is_ind seed) itl
570 | NCic.Constant (_,_,Some bo,ty,_) ->
571 let ty = nast_of_cic ~context:[] ty in
572 let bo = nast_of_cic ~context:[] bo in
573 (gen_id object_prefix seed, conjectures,
575 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
576 | NCic.Constant (_,_,None,ty,_) ->
577 let ty = nast_of_cic ~context:[] ty in
578 (gen_id object_prefix seed, conjectures,
580 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
581 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
584 let with_idrefs foo status obj =
585 let ids_to_refs = Hashtbl.create 211 in
586 let register_ref = Hashtbl.add ids_to_refs in
587 foo status ~idref:(idref register_ref) obj, ids_to_refs
590 let nmap_obj status = with_idrefs nmap_obj0 status
592 let nmap_sequent status ~metasenv ~subst =
593 with_idrefs (nmap_sequent0 ~metasenv ~subst) status
595 let nmap_term status ~metasenv ~subst ~context =
596 with_idrefs (nast_of_cic1 ~output_type:`Term ~metasenv ~subst ~context) status
598 let nmap_context status ~metasenv ~subst =
599 with_idrefs (nmap_context0 ~metasenv ~subst) status