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)
63 pattern32_matrix = [];
64 level2_patterns32 = IntMap.empty;
65 interpretations = StringMap.empty;
66 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler [])
71 inherit NCicCoercion.g_status
77 inherit NCicCoercion.status
78 val interp_db = initial_db
79 method interp_db = interp_db
80 method set_interp_db v = {< interp_db = v >}
81 method set_interp_status
82 : 'status. #g_status as 'status -> 'self
83 = fun o -> {< interp_db = o#interp_db >}#set_coercion_status o
86 let idref register_ref =
90 let id = "i" ^ string_of_int !id in
91 (match reference with None -> () | Some r -> register_ref id r);
92 Ast.AttributedTerm (`IdRef id, t)
96 let name = NUri.name_of_uri u in
97 assert(String.length name > String.length "Type");
98 String.sub name 4 (String.length name - 4)
101 let find_level2_patterns32 status pid =
102 IntMap.find pid status#interp_db.level2_patterns32
105 List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
107 let instantiate32 idrefs env symbol args =
108 let rec instantiate_arg = function
109 | Ast.IdentArg (n, name) ->
111 try List.assoc name env
112 with Not_found -> prerr_endline ("name not found in env: "^name);
115 let rec count_lambda = function
116 | Ast.AttributedTerm (_, t) -> count_lambda t
117 | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
120 let rec add_lambda t n =
122 let name = NotationUtil.fresh_name () in
123 Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
124 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
128 add_lambda t (n - count_lambda t)
131 let symbol = Ast.Symbol (symbol, 0) in
132 add_idrefs idrefs symbol
134 if args = [] then head
135 else Ast.Appl (head :: List.map instantiate_arg args)
137 let fresh_id status =
138 let counter = status#interp_db.counter+1 in
139 status#set_interp_db ({ status#interp_db with counter = counter }), counter
141 let load_patterns32 status t =
143 HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
146 {status#interp_db with
147 compiled32 = lazy (Ncic2astMatcher.Matcher32.compiler t) }
150 let add_interpretation status dsc (symbol, args) appl_pattern =
151 let status,id = fresh_id status in
154 id::StringMap.find symbol status#interp_db.interpretations
155 with Not_found -> [id] in
157 status#set_interp_db { status#interp_db with
159 IntMap.add id (dsc, symbol, args, appl_pattern)
160 status#interp_db.level2_patterns32;
161 pattern32_matrix = (true,appl_pattern,id)::status#interp_db.pattern32_matrix;
162 interpretations = StringMap.add symbol ids status#interp_db.interpretations
165 load_patterns32 status status#interp_db.pattern32_matrix
167 let toggle_active_interpretations status b =
168 status#set_interp_db { status#interp_db with
170 List.map (fun (_,ap,id) -> b,ap,id) status#interp_db.pattern32_matrix }
172 exception Interpretation_not_found
174 let lookup_interpretations status ?(sorted=true) symbol =
179 let (dsc, _, args, appl_pattern) =
180 try IntMap.find id status#interp_db.level2_patterns32
181 with Not_found -> assert false
183 dsc, args, appl_pattern
184 ) (StringMap.find symbol status#interp_db.interpretations)
186 if sorted then HExtlib.list_uniq (List.sort Pervasives.compare raw)
188 with Not_found -> raise Interpretation_not_found
190 let instantiate_appl_pattern
191 ~mk_appl ~mk_implicit ~term_of_nref env appl_pattern
194 try List.assoc name env
196 prerr_endline (sprintf "Name %s not found" name);
199 let rec aux = function
200 | Ast.NRefPattern nref -> term_of_nref nref
201 | Ast.ImplicitPattern -> mk_implicit false
202 | Ast.VarPattern name -> lookup name
203 | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
208 let is_nat_URI = NUri.eq (NUri.uri_of_string
209 "cic:/matita/arithmetics/nat/nat.ind") in
210 let is_zero = function
211 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
212 is_nat_URI uri -> true
215 let is_succ = function
216 | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
217 is_nat_URI uri -> true
220 let rec aux acc = function
221 | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
222 | t when is_zero t -> Some acc
227 (* CODICE c&p da NCicPp *)
228 let nast_of_cic0 status
230 ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
231 ~output_type ~metasenv ~subst k ~context =
235 let name,_ = List.nth context (n-1) in
236 let name = if name = "_" then "__"^string_of_int n else name in
237 idref (Ast.Ident (name,None))
238 with Failure "nth" | Invalid_argument "List.nth" ->
239 idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
240 | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
241 | NCic.Meta (n,lc) when List.mem_assoc n subst ->
242 let _,_,t,_ = List.assoc n subst in
243 k ~context (NCicSubstitution.subst_meta lc t)
244 | NCic.Meta (n,(s,l)) ->
245 (* CSC: qua non dovremmo espandere *)
246 let l = NCicUtils.expand_local_context l in
248 (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
249 | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
250 | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
251 | NCic.Sort NCic.Type ((`Type,u)::_) ->
252 idref(Ast.Sort (`NType (level_of_uri u)))
253 | NCic.Sort NCic.Type ((`CProp,u)::_) ->
254 idref(Ast.Sort (`NCProp (level_of_uri u)))
255 | NCic.Sort NCic.Type ((`Succ,u)::_) ->
256 idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
257 | NCic.Implicit `Hole -> idref (Ast.UserInput)
258 | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
259 | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
260 | NCic.Prod (n,s,t) ->
261 let n = if n.[0] = '_' then "_" else n in
262 let binder_kind = `Forall in
263 idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
264 k ~context:((n,NCic.Decl s)::context) t))
265 | NCic.Lambda (n,s,t) ->
266 idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
267 k ~context:((n,NCic.Decl s)::context) t))
268 | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
269 idref (Ast.Cast (k ~context ty, k ~context s))
270 | NCic.LetIn (n,s,ty,t) ->
271 idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
272 ty, k ~context:((n,NCic.Decl s)::context) t))
273 | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst ->
274 let _,_,t,_ = List.assoc n subst in
275 let hd = NCicSubstitution.subst_meta lc t in
277 (NCicReduction.head_beta_reduce ~upto:(List.length args)
279 | NCic.Appl l -> NCic.Appl (l@args)
280 | _ -> NCic.Appl (hd :: args)))
281 | NCic.Appl args as t ->
282 (match destroy_nat t with
283 | Some n -> idref (Ast.Num (string_of_int n, -1))
286 if not !hide_coercions then args
289 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
292 | Some (_,sats,cpos) ->
293 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
294 argomenti da saltare, come prima! *)
295 if cpos < List.length args - 1 then
296 List.nth args (cpos + 1) ::
297 try snd (HExtlib.split_nth (cpos+sats+2) args)
303 [arg] -> idref (k ~context arg)
304 | _ -> idref (Ast.Appl (List.map (k ~context) args))))
305 | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
306 let name = NUri.name_of_uri uri in
308 let uri_str = UriManager.string_of_uri uri in
309 let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
311 UriManager.uri_of_string
312 (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
316 name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
317 let constructors, leftno =
318 let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
319 let _,_,_,cl = List.nth tys n in
322 let rec eat_branch n ctx ty pat =
324 | NCic.Prod (name, s, t), _ when n > 0 ->
325 eat_branch (pred n) ctx t pat
326 | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
327 let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
328 (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
329 | _, _ -> [], k ~context:ctx pat
335 (fun (_, name, ty) pat ->
337 let name,(capture_variables,rhs) =
338 match output_type with
339 `Term -> name, eat_branch leftno context ty pat
340 | `Pattern -> "_", ([], k ~context pat)
342 Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
343 ) constructors patterns
344 with Invalid_argument _ -> assert false
347 match output_type with
349 | `Term -> Some case_indty
351 idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
354 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
355 match Lazy.force status#interp_db.compiled32 term with
357 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
358 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
359 | Some (env, ctors, pid) ->
366 (match term with NCic.Const nref -> nref | _ -> assert false)
367 (NotationPt.Ident ("dummy",None))
370 Ast.AttributedTerm (`IdRef id, _) -> id
378 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
382 let _, symbol, args, _ =
384 find_level2_patterns32 status pid
385 with Not_found -> assert false
387 let ast = instantiate32 idrefs env symbol args in
388 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
391 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
392 let module K = Content in
394 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
397 (fun item (res,context) ->
399 | name,NCic.Decl t ->
401 (* We should call build_decl_item, but we have not computed *)
402 (* the inner-types ==> we always produce a declaration *)
404 { K.dec_name = (Some name);
406 K.dec_inductive = false;
408 K.dec_type = nast_of_cic ~context t
409 })::res,item::context
410 | name,NCic.Def (t,ty) ->
412 (* We should call build_def_item, but we have not computed *)
413 (* the inner-types ==> we always produce a declaration *)
415 { K.def_name = (Some name);
418 K.def_term = nast_of_cic ~context t;
419 K.def_type = nast_of_cic ~context ty
420 })::res,item::context
423 ("-1",i,context',nast_of_cic ~context ty)
426 let nmap_sequent status ~metasenv ~subst conjecture =
427 let module K = Content in
428 let ids_to_refs = Hashtbl.create 211 in
429 let register_ref = Hashtbl.add ids_to_refs in
430 nmap_sequent0 status ~idref:(idref register_ref) ~metasenv ~subst conjecture,
434 let object_prefix = "obj:";;
435 let declaration_prefix = "decl:";;
436 let definition_prefix = "def:";;
437 let inductive_prefix = "ind:";;
438 let joint_prefix = "joint:";;
442 Ast.AttributedTerm (`IdRef id, _) -> id
446 let gen_id prefix seed =
447 let res = prefix ^ string_of_int !seed in
452 let build_def_item seed context metasenv id n t ty =
453 let module K = Content in
456 let sort = Hashtbl.find ids_to_inner_sorts id in
459 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
465 { K.def_name = Some n;
466 K.def_id = gen_id definition_prefix seed;
473 Not_found -> assert false
476 let build_decl_item seed id n s =
477 let module K = Content in
481 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
482 with Not_found -> None
487 { K.dec_name = name_of n;
488 K.dec_id = gen_id declaration_prefix seed;
489 K.dec_inductive = false;
496 { K.dec_name = Some n;
497 K.dec_id = gen_id declaration_prefix seed;
498 K.dec_inductive = false;
504 let nmap_obj status (uri,_,metasenv,subst,kind) =
505 let module K = Content in
506 let ids_to_refs = Hashtbl.create 211 in
507 let register_ref = Hashtbl.add ids_to_refs in
508 let idref = idref register_ref in
510 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
515 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
516 (*CSC: used to be the previous line, that uses seed *)
517 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
519 let build_constructors seed l =
522 let ty = nast_of_cic ~context:[] ty in
523 { K.dec_name = Some n;
524 K.dec_id = gen_id declaration_prefix seed;
525 K.dec_inductive = false;
530 let build_inductive b seed =
532 let ty = nast_of_cic ~context:[] ty in
534 { K.inductive_id = gen_id inductive_prefix seed;
535 K.inductive_name = n;
536 K.inductive_kind = b;
537 K.inductive_type = ty;
538 K.inductive_constructors = build_constructors seed cl
541 let build_fixpoint b seed =
543 let t = nast_of_cic ~context:[] t in
544 let ty = nast_of_cic ~context:[] ty in
546 { K.def_id = gen_id inductive_prefix seed;
555 | NCic.Fixpoint (is_rec, ifl, _) ->
556 (gen_id object_prefix seed, conjectures,
558 { K.joint_id = gen_id joint_prefix seed;
561 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
563 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
565 | NCic.Inductive (is_ind, lno, itl, _) ->
566 (gen_id object_prefix seed, conjectures,
568 { K.joint_id = gen_id joint_prefix seed;
570 if is_ind then `Inductive lno else `CoInductive lno;
571 K.joint_defs = List.map (build_inductive is_ind seed) itl
573 | NCic.Constant (_,_,Some bo,ty,_) ->
574 let ty = nast_of_cic ~context:[] ty in
575 let bo = nast_of_cic ~context:[] bo in
576 (gen_id object_prefix seed, conjectures,
578 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
579 | NCic.Constant (_,_,None,ty,_) ->
580 let ty = nast_of_cic ~context:[] ty in
581 (gen_id object_prefix seed, conjectures,
583 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
584 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))