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, `Ambiguous), None),
126 Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, `Ambiguous)])
130 add_lambda t (n - count_lambda t)
133 let symbol = Ast.Symbol (symbol, None) 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,`Ambiguous))
240 with Failure "nth" | Invalid_argument "List.nth" ->
241 idref (Ast.Ident ("-" ^ string_of_int (n - List.length
242 context),`Ambiguous)))
243 | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s status true r, `Ambiguous))
244 | NCic.Meta (n,lc) when List.mem_assoc n subst ->
245 let _,_,t,_ = List.assoc n subst in
246 k ~context (NCicSubstitution.subst_meta status lc t)
247 | NCic.Meta (n,(s,l)) ->
248 (* CSC: qua non dovremmo espandere *)
249 let l = NCicUtils.expand_local_context l in
251 (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift status s x))) l))
252 | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
253 | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
254 | NCic.Sort NCic.Type ((`Type,u)::_) ->
255 idref(Ast.Sort (`NType (level_of_uri u)))
256 | NCic.Sort NCic.Type ((`CProp,u)::_) ->
257 idref(Ast.Sort (`NCProp (level_of_uri u)))
258 | NCic.Sort NCic.Type ((`Succ,u)::_) ->
259 idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
260 | NCic.Implicit `Hole -> idref (Ast.UserInput)
261 | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
262 | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
263 | NCic.Prod (n,s,t) ->
264 let n = if n.[0] = '_' then "_" else n in
265 let binder_kind = `Forall in
266 idref (Ast.Binder (binder_kind, (Ast.Ident (n,`Ambiguous), Some (k ~context s)),
267 k ~context:((n,NCic.Decl s)::context) t))
268 | NCic.Lambda (n,s,t) ->
269 idref (Ast.Binder (`Lambda,(Ast.Ident (n,`Ambiguous), Some (k ~context s)),
270 k ~context:((n,NCic.Decl s)::context) t))
271 | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
272 idref (Ast.Cast (k ~context ty, k ~context s))
273 | NCic.LetIn (n,s,ty,t) ->
274 idref (Ast.LetIn ((Ast.Ident (n,`Ambiguous), Some (k ~context s)), k ~context
275 ty, k ~context:((n,NCic.Decl s)::context) t))
276 | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst ->
277 let _,_,t,_ = List.assoc n subst in
278 let hd = NCicSubstitution.subst_meta status lc t in
280 (NCicReduction.head_beta_reduce status ~upto:(List.length args)
282 | NCic.Appl l -> NCic.Appl (l@args)
283 | _ -> NCic.Appl (hd :: args)))
284 | NCic.Appl args as t ->
285 (match destroy_nat t with
286 | Some n -> idref (Ast.Num (string_of_int n, None))
289 if not !hide_coercions then args
292 NCicCoercion.match_coercion status ~metasenv ~context ~subst t
295 | Some (_,sats,cpos) ->
296 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
297 argomenti da saltare, come prima! *)
298 if cpos < List.length args - 1 then
299 List.nth args (cpos + 1) ::
300 try snd (HExtlib.split_nth (cpos+sats+2) args)
306 [arg] -> idref (k ~context arg)
307 | _ -> idref (Ast.Appl (List.map (k ~context) args))))
308 | 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,`Ambiguous), 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))
357 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
358 match Lazy.force status#interp_db.compiled32 term with
360 nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
361 (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term
362 | Some (env, ctors, pid) ->
369 (match term with NCic.Const nref -> nref | _ -> assert false)
370 (NotationPt.Ident ("dummy",`Ambiguous))
373 Ast.AttributedTerm (`IdRef id, _) -> id
381 nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
385 let _, symbol, args, _ =
387 find_level2_patterns32 status pid
388 with Not_found -> assert false
390 let ast = instantiate32 idrefs env symbol args in
391 idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
394 let nmap_context0 status ~idref ~metasenv ~subst context =
395 let module K = Content in
397 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst
401 (fun item (res,context) ->
403 | name,NCic.Decl t ->
405 (* We should call build_decl_item, but we have not computed *)
406 (* the inner-types ==> we always produce a declaration *)
408 { K.dec_name = (Some name);
410 K.dec_inductive = false;
412 K.dec_type = nast_of_cic ~context t
413 })::res,item::context
414 | name,NCic.Def (t,ty) ->
416 (* We should call build_def_item, but we have not computed *)
417 (* the inner-types ==> we always produce a declaration *)
419 { K.def_name = (Some name);
422 K.def_term = nast_of_cic ~context t;
423 K.def_type = nast_of_cic ~context ty
424 })::res,item::context
428 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
429 let module K = Content in
431 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
432 let context' = nmap_context0 status ~idref ~metasenv ~subst context in
433 ("-1",i,context',nast_of_cic ~context ty)
436 let object_prefix = "obj:";;
437 let declaration_prefix = "decl:";;
438 let definition_prefix = "def:";;
439 let inductive_prefix = "ind:";;
440 let joint_prefix = "joint:";;
444 Ast.AttributedTerm (`IdRef id, _) -> id
448 let gen_id prefix seed =
449 let res = prefix ^ string_of_int !seed in
454 let build_def_item seed context metasenv id n t ty =
455 let module K = Content in
458 let sort = Hashtbl.find ids_to_inner_sorts id in
461 (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts ~ids_to_inner_types t)
467 { K.def_name = Some n;
468 K.def_id = gen_id definition_prefix seed;
475 Not_found -> assert false
478 let build_decl_item seed id n s =
479 let module K = Content in
483 Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
484 with Not_found -> None
489 { K.dec_name = name_of n;
490 K.dec_id = gen_id declaration_prefix seed;
491 K.dec_inductive = false;
498 { K.dec_name = Some n;
499 K.dec_id = gen_id declaration_prefix seed;
500 K.dec_inductive = false;
506 let nmap_obj0 status ~idref (uri,_,metasenv,subst,kind) =
507 let module K = Content in
509 nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
514 | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
515 (*CSC: used to be the previous line, that uses seed *)
516 Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
518 let build_constructors seed l =
521 let ty = nast_of_cic ~context:[] ty in
522 { K.dec_name = Some n;
523 K.dec_id = gen_id declaration_prefix seed;
524 K.dec_inductive = false;
529 let build_inductive b seed =
531 let ty = nast_of_cic ~context:[] ty in
533 { K.inductive_id = gen_id inductive_prefix seed;
534 K.inductive_name = n;
535 K.inductive_kind = b;
536 K.inductive_type = ty;
537 K.inductive_constructors = build_constructors seed cl
540 let build_fixpoint b seed =
542 let t = nast_of_cic ~context:[] t in
543 let ty = nast_of_cic ~context:[] ty in
545 { K.def_id = gen_id inductive_prefix seed;
553 | NCic.Fixpoint (is_rec, ifl, _) ->
554 (gen_id object_prefix seed, conjectures,
556 { K.joint_id = gen_id joint_prefix seed;
559 `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
561 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
563 | NCic.Inductive (is_ind, lno, itl, _) ->
564 (gen_id object_prefix seed, conjectures,
566 { K.joint_id = gen_id joint_prefix seed;
568 if is_ind then `Inductive lno else `CoInductive lno;
569 K.joint_defs = List.map (build_inductive is_ind seed) itl
571 | NCic.Constant (_,_,Some bo,ty,_) ->
572 let ty = nast_of_cic ~context:[] ty in
573 let bo = nast_of_cic ~context:[] bo in
574 (gen_id object_prefix seed, conjectures,
576 build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
577 | NCic.Constant (_,_,None,ty,_) ->
578 let ty = nast_of_cic ~context:[] ty in
579 (gen_id object_prefix seed, conjectures,
581 (*CSC: ??? get_id ty here used to be the id of the axiom! *)
582 build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
585 let with_idrefs foo status obj =
586 let ids_to_refs = Hashtbl.create 211 in
587 let register_ref = Hashtbl.add ids_to_refs in
588 foo status ~idref:(idref register_ref) obj, ids_to_refs
591 let nmap_obj status = with_idrefs nmap_obj0 status
593 let nmap_sequent status ~metasenv ~subst =
594 with_idrefs (nmap_sequent0 ~metasenv ~subst) status
596 let nmap_term status ~metasenv ~subst ~context =
597 with_idrefs (nast_of_cic1 ~output_type:`Term ~metasenv ~subst ~context) status
599 let nmap_context status ~metasenv ~subst =
600 with_idrefs (nmap_context0 ~metasenv ~subst) status