]> matita.cs.unibo.it Git - helm.git/blob - matita/components/ng_cic_content/nTermCicContent.ml
urimanager removed
[helm.git] / matita / components / ng_cic_content / nTermCicContent.ml
1 (* Copyright (C) 2005, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id: termAcicContent.ml 9304 2008-12-05 23:12:39Z sacerdot $ *)
27
28 open Printf
29
30 module Ast = NotationPt
31
32 let debug = false
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
34
35 type id = string
36
37 let hide_coercions = ref true;;
38
39 (*
40 type interpretation_id = int
41
42 type term_info =
43   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
44     uri: (Cic.id, UriManager.uri) Hashtbl.t;
45   }
46 *)
47
48 let idref register_ref =
49  let id = ref 0 in
50   fun ?reference t ->
51    incr id;
52    let id = "i" ^ string_of_int !id in
53     (match reference with None -> () | Some r -> register_ref id r);
54     Ast.AttributedTerm (`IdRef id, t)
55 ;;
56
57 let level_of_uri u = 
58   let name = NUri.name_of_uri u in
59   assert(String.length name > String.length "Type");
60   String.sub name 4 (String.length name - 4)
61 ;;
62
63 let destroy_nat =
64   let is_nat_URI = NUri.eq (NUri.uri_of_string
65   "cic:/matita/ng/arithmetics/nat/nat.ind") in
66   let is_zero = function
67     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 1, 0))) when
68        is_nat_URI uri -> true
69     | _ -> false
70   in
71   let is_succ = function
72     | NCic.Const (NReference.Ref (uri, NReference.Con (0, 2, 0))) when
73        is_nat_URI uri -> true
74     | _ -> false
75   in
76   let rec aux acc = function
77     | NCic.Appl [he ; tl] when is_succ he -> aux (acc + 1) tl
78     | t when is_zero t -> Some acc
79     | _ -> None
80   in
81    aux 0
82
83 (* CODICE c&p da NCicPp *)
84 let nast_of_cic0 status
85  ~(idref:
86     ?reference:NReference.reference -> NotationPt.term -> NotationPt.term)
87  ~output_type ~metasenv ~subst k ~context =
88   function
89     | NCic.Rel n ->
90        (try 
91          let name,_ = List.nth context (n-1) in
92          let name = if name = "_" then "__"^string_of_int n else name in
93           idref (Ast.Ident (name,None))
94         with Failure "nth" | Invalid_argument "List.nth" -> 
95          idref (Ast.Ident ("-" ^ string_of_int (n - List.length context),None)))
96     | NCic.Const r -> idref ~reference:r (Ast.Ident (NCicPp.r2s true r, None))
97     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
98         let _,_,t,_ = List.assoc n subst in
99          k ~context (NCicSubstitution.subst_meta lc t)
100     | NCic.Meta (n,(s,l)) ->
101        (* CSC: qua non dovremmo espandere *)
102        let l = NCicUtils.expand_local_context l in
103         idref (Ast.Meta
104          (n, List.map (fun x -> Some (k ~context (NCicSubstitution.lift s x))) l))
105     | NCic.Sort NCic.Prop -> idref (Ast.Sort `Prop)
106     | NCic.Sort NCic.Type [] -> idref (Ast.Sort `Set)
107     | NCic.Sort NCic.Type ((`Type,u)::_) -> 
108               idref(Ast.Sort (`NType (level_of_uri u)))
109     | NCic.Sort NCic.Type ((`CProp,u)::_) -> 
110               idref(Ast.Sort (`NCProp (level_of_uri u)))
111     | NCic.Sort NCic.Type ((`Succ,u)::_) -> 
112               idref(Ast.Sort (`NType (level_of_uri u ^ "+1")))
113     | NCic.Implicit `Hole -> idref (Ast.UserInput)
114     | NCic.Implicit `Vector -> idref (Ast.Implicit `Vector)
115     | NCic.Implicit _ -> idref (Ast.Implicit `JustOne)
116     | NCic.Prod (n,s,t) ->
117         let n = if n.[0] = '_' then "_" else n in
118         let binder_kind = `Forall in
119          idref (Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k ~context s)),
120           k ~context:((n,NCic.Decl s)::context) t))
121     | NCic.Lambda (n,s,t) ->
122         idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ~context s)),
123          k ~context:((n,NCic.Decl s)::context) t))
124     | NCic.LetIn (n,s,ty,NCic.Rel 1) ->
125         idref (Ast.Cast (k ~context ty, k ~context s))
126     | NCic.LetIn (n,s,ty,t) ->
127         idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ~context s)), k ~context
128           ty, k ~context:((n,NCic.Decl s)::context) t))
129     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
130        let _,_,t,_ = List.assoc n subst in
131        let hd = NCicSubstitution.subst_meta lc t in
132         k ~context
133          (NCicReduction.head_beta_reduce ~upto:(List.length args)
134            (match hd with
135            | NCic.Appl l -> NCic.Appl (l@args)
136            | _ -> NCic.Appl (hd :: args)))
137     | NCic.Appl args as t ->
138        (match destroy_nat t with
139          | Some n -> idref (Ast.Num (string_of_int n, -1))
140          | None ->
141             let args =
142              if not !hide_coercions then args
143              else
144               match
145                NCicCoercion.match_coercion status ~metasenv ~context ~subst t
146               with
147                | None -> args
148                | Some (_,sats,cpos) -> 
149 (* CSC: sats e' il numero di pi, ma non so cosa farmene! voglio il numero di
150    argomenti da saltare, come prima! *)
151                   if cpos < List.length args - 1 then
152                    List.nth args (cpos + 1) ::
153                     try snd (HExtlib.split_nth (cpos+sats+2) args)
154                     with Failure _->[]
155                   else
156                    args
157             in
158              (match args with
159                  [arg] -> idref (k ~context arg)
160                | _ -> idref (Ast.Appl (List.map (k ~context) args))))
161     | NCic.Match (NReference.Ref (uri,_) as r,outty,te,patterns) ->
162         let name = NUri.name_of_uri uri in
163 (* CSC
164         let uri_str = UriManager.string_of_uri uri in
165         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
166         let ctor_puri j =
167           UriManager.uri_of_string
168             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
169         in
170 *)
171         let case_indty =
172          name, None(*CSC Some (UriManager.uri_of_string puri_str)*) in
173         let constructors, leftno =
174          let _,leftno,tys,_,n = NCicEnvironment.get_checked_indtys r in
175          let _,_,_,cl  = List.nth tys n in
176           cl,leftno
177         in
178         let rec eat_branch n ctx ty pat =
179           match (ty, pat) with
180           | NCic.Prod (name, s, t), _ when n > 0 ->
181              eat_branch (pred n) ctx t pat 
182           | NCic.Prod (_, _, t), NCic.Lambda (name, s, t') ->
183               let cv, rhs = eat_branch 0 ((name,NCic.Decl s)::ctx) t t' in
184               (Ast.Ident (name,None), Some (k ~context:ctx s)) :: cv, rhs
185           | _, _ -> [], k ~context:ctx pat
186         in
187         let j = ref 0 in
188         let patterns =
189           try
190             List.map2
191               (fun (_, name, ty) pat ->
192                 incr j;
193                 let name,(capture_variables,rhs) =
194                  match output_type with
195                     `Term -> name, eat_branch leftno context ty pat
196                   | `Pattern -> "_", ([], k ~context pat)
197                 in
198                  Ast.Pattern (name, None(*CSC Some (ctor_puri !j)*), capture_variables), rhs
199               ) constructors patterns
200           with Invalid_argument _ -> assert false
201         in
202         let indty =
203          match output_type with
204             `Pattern -> None
205           | `Term -> Some case_indty
206         in
207          idref (Ast.Case (k ~context te, indty, Some (k ~context outty), patterns))
208 ;;
209
210   (* persistent state *)
211
212 (*
213 let initial_level2_patterns32 () = Hashtbl.create 211
214 let initial_interpretations () = Hashtbl.create 211
215
216 let level2_patterns32 = ref (initial_level2_patterns32 ())
217 (* symb -> id list ref *)
218 let interpretations = ref (initial_interpretations ())
219 *)
220 let compiled32 = ref None
221 (*
222 let pattern32_matrix = ref []
223 let counter = ref ~-1 
224
225 let stack = ref []
226
227 let push () =
228  stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
229  counter := ~-1;
230  level2_patterns32 := initial_level2_patterns32 ();
231  interpretations := initial_interpretations ();
232  compiled32 := None;
233  pattern32_matrix := []
234 ;;
235
236 let pop () =
237  match !stack with
238     [] -> assert false
239   | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
240    stack := old;
241    counter := ocounter;
242    level2_patterns32 := olevel2_patterns32;
243    interpretations := ointerpretations;
244    compiled32 := ocompiled32;
245    pattern32_matrix := opattern32_matrix
246 ;;
247 *)
248
249 let get_compiled32 () =
250   match !compiled32 with
251   | None -> assert false
252   | Some f -> Lazy.force f
253
254 let set_compiled32 f = compiled32 := Some f
255
256 let add_idrefs =
257   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
258
259 let instantiate32 idrefs env symbol args =
260   let rec instantiate_arg = function
261     | Ast.IdentArg (n, name) ->
262         let t = 
263           try List.assoc name env 
264           with Not_found -> prerr_endline ("name not found in env: "^name);
265                             assert false
266         in
267         let rec count_lambda = function
268           | Ast.AttributedTerm (_, t) -> count_lambda t
269           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
270           | _ -> 0
271         in
272         let rec add_lambda t n =
273           if n > 0 then
274             let name = NotationUtil.fresh_name () in
275             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
276               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
277           else
278             t
279         in
280         add_lambda t (n - count_lambda t)
281   in
282   let head =
283     let symbol = Ast.Symbol (symbol, 0) in
284     add_idrefs idrefs symbol
285   in
286   if args = [] then head
287   else Ast.Appl (head :: List.map instantiate_arg args)
288
289 let rec nast_of_cic1 status ~idref ~output_type ~metasenv ~subst ~context term =
290   match (get_compiled32 ()) term with
291   | None ->
292      nast_of_cic0 status ~idref ~output_type ~metasenv ~subst
293       (nast_of_cic1 status ~idref ~output_type ~metasenv ~subst) ~context term 
294   | Some (env, ctors, pid) -> 
295       let idrefs =
296        List.map
297         (fun term ->
298           let attrterm =
299            idref
300             ~reference:
301               (match term with NCic.Const nref -> nref | _ -> assert false)
302            (NotationPt.Ident ("dummy",None))
303           in
304            match attrterm with
305               Ast.AttributedTerm (`IdRef id, _) -> id
306             | _ -> assert false
307         ) ctors
308       in
309       let env =
310        List.map
311         (fun (name, term) ->
312           name,
313            nast_of_cic1 status ~idref ~output_type ~subst ~metasenv ~context
314             term
315         ) env
316       in
317       let _, symbol, args, _ =
318         try
319           Interpretations.find_level2_patterns32 pid
320         with Not_found -> assert false
321       in
322       let ast = instantiate32 idrefs env symbol args in
323       idref ast (*Ast.AttributedTerm (`IdRef (idref term), ast)*)
324 ;;
325
326 let load_patterns32 t =
327  let t =
328   HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
329  in
330   set_compiled32 (lazy (Ncic2astMatcher.Matcher32.compiler t))
331 in
332  Interpretations.add_load_patterns32 load_patterns32;
333  Interpretations.init ()
334 ;;
335
336 (*
337 let fresh_id =
338   fun () ->
339     incr counter;
340     !counter
341
342 let add_interpretation dsc (symbol, args) appl_pattern =
343   let id = fresh_id () in
344   Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
345   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
346   load_patterns32 !pattern32_matrix;
347   (try
348     let ids = Hashtbl.find !interpretations symbol in
349     ids := id :: !ids
350   with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
351   id
352
353 let get_all_interpretations () =
354   List.map
355     (function (_, _, id) ->
356       let (dsc, _, _, _) =
357         try
358           Hashtbl.find !level2_patterns32 id
359         with Not_found -> assert false
360       in
361       (id, dsc))
362     !pattern32_matrix
363
364 let get_active_interpretations () =
365   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
366     !pattern32_matrix
367
368 let set_active_interpretations ids =
369   let pattern32_matrix' =
370     List.map
371       (function 
372         | (_, ap, id) when List.mem id ids -> (true, ap, id)
373         | (_, ap, id) -> (false, ap, id))
374       !pattern32_matrix
375   in
376   pattern32_matrix := pattern32_matrix';
377   load_patterns32 !pattern32_matrix
378
379 exception Interpretation_not_found
380
381 let lookup_interpretations symbol =
382   try
383    HExtlib.list_uniq
384     (List.sort Pervasives.compare
385      (List.map
386       (fun id ->
387         let (dsc, _, args, appl_pattern) =
388           try
389             Hashtbl.find !level2_patterns32 id
390           with Not_found -> assert false 
391         in
392         dsc, args, appl_pattern)
393       !(Hashtbl.find !interpretations symbol)))
394   with Not_found -> raise Interpretation_not_found
395
396 let remove_interpretation id =
397   (try
398     let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
399     let ids = Hashtbl.find !interpretations symbol in
400     ids := List.filter ((<>) id) !ids;
401     Hashtbl.remove !level2_patterns32 id;
402   with Not_found -> raise Interpretation_not_found);
403   pattern32_matrix :=
404     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
405   load_patterns32 !pattern32_matrix
406
407 let _ = load_patterns32 []
408
409 let instantiate_appl_pattern 
410   ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern 
411 =
412   let lookup name =
413     try List.assoc name env
414     with Not_found ->
415       prerr_endline (sprintf "Name %s not found" name);
416       assert false
417   in
418   let rec aux = function
419     | Ast.UriPattern uri -> term_of_uri uri
420     | Ast.ImplicitPattern -> mk_implicit false
421     | Ast.VarPattern name -> lookup name
422     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
423   in
424   aux appl_pattern
425 *)
426
427 let nmap_sequent0 status ~idref ~metasenv ~subst (i,(n,context,ty)) =
428  let module K = Content in
429  let nast_of_cic =
430   nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
431  let context',_ =
432   List.fold_right
433    (fun item (res,context) ->
434      match item with
435       | name,NCic.Decl t ->
436          Some
437           (* We should call build_decl_item, but we have not computed *)
438           (* the inner-types ==> we always produce a declaration      *)
439           (`Declaration
440             { K.dec_name = (Some name);
441               K.dec_id = "-1"; 
442               K.dec_inductive = false;
443               K.dec_aref = "-1";
444               K.dec_type = nast_of_cic ~context t
445             })::res,item::context
446       | name,NCic.Def (t,ty) ->
447          Some
448           (* We should call build_def_item, but we have not computed *)
449           (* the inner-types ==> we always produce a declaration     *)
450           (`Definition
451              { K.def_name = (Some name);
452                K.def_id = "-1"; 
453                K.def_aref = "-1";
454                K.def_term = nast_of_cic ~context t;
455                K.def_type = nast_of_cic ~context ty
456              })::res,item::context
457    ) context ([],[])
458  in
459   ("-1",i,context',nast_of_cic ~context ty)
460 ;;
461
462 let nmap_sequent status ~metasenv ~subst conjecture =
463  let module K = Content in
464  let ids_to_refs = Hashtbl.create 211 in
465  let register_ref = Hashtbl.add ids_to_refs in
466   nmap_sequent0 status ~idref:(idref register_ref) ~metasenv ~subst conjecture,
467   ids_to_refs
468 ;;
469
470 let object_prefix = "obj:";;
471 let declaration_prefix = "decl:";;
472 let definition_prefix = "def:";;
473 let inductive_prefix = "ind:";;
474 let joint_prefix = "joint:";;
475
476 let get_id =
477  function
478     Ast.AttributedTerm (`IdRef id, _) -> id
479   | _ -> assert false
480 ;;
481
482 let gen_id prefix seed =
483  let res = prefix ^ string_of_int !seed in
484   incr seed ;
485   res
486 ;;
487
488 let build_def_item seed context metasenv id n t ty =
489  let module K = Content in
490 (*
491   try
492    let sort = Hashtbl.find ids_to_inner_sorts id in
493    if sort = `Prop then
494        (let p = 
495         (acic2content seed context metasenv ?name:(name_of n) ~ids_to_inner_sorts  ~ids_to_inner_types t)
496        in 
497         `Proof p;)
498    else 
499 *)
500       `Definition
501         { K.def_name = Some n;
502           K.def_id = gen_id definition_prefix seed; 
503           K.def_aref = id;
504           K.def_term = t;
505           K.def_type = ty
506         }
507 (*
508   with
509    Not_found -> assert false
510 *)
511
512 let build_decl_item seed id n s =
513  let module K = Content in
514 (*
515  let sort =
516    try
517     Some (Hashtbl.find ids_to_inner_sorts (Cic2acic.source_id_of_id id))
518    with Not_found -> None
519  in
520  match sort with
521  | Some `Prop ->
522     `Hypothesis
523       { K.dec_name = name_of n;
524         K.dec_id = gen_id declaration_prefix seed; 
525         K.dec_inductive = false;
526         K.dec_aref = id;
527         K.dec_type = s
528       }
529  | _ ->
530 *)
531     `Declaration
532       { K.dec_name = Some n;
533         K.dec_id = gen_id declaration_prefix seed; 
534         K.dec_inductive = false;
535         K.dec_aref = id;
536         K.dec_type = s
537       }
538 ;;
539
540 let nmap_obj status (uri,_,metasenv,subst,kind) =
541   let module K = Content in
542   let ids_to_refs = Hashtbl.create 211 in
543   let register_ref = Hashtbl.add ids_to_refs in
544   let idref = idref register_ref in
545   let nast_of_cic =
546    nast_of_cic1 status ~idref ~output_type:`Term ~metasenv ~subst in
547   let seed = ref 0 in
548   let conjectures =
549    match metasenv with
550       [] -> None
551     | _ -> (*Some (List.map (map_conjectures seed) metasenv)*)
552       (*CSC: used to be the previous line, that uses seed *)
553       Some (List.map (nmap_sequent0 status ~idref ~metasenv ~subst) metasenv)
554   in
555 let  build_constructors seed l =
556       List.map 
557        (fun (_,n,ty) ->
558            let ty = nast_of_cic ~context:[] ty in
559            { K.dec_name = Some n;
560              K.dec_id = gen_id declaration_prefix seed;
561              K.dec_inductive = false;
562              K.dec_aref = "";
563              K.dec_type = ty
564            }) l
565 in
566 let build_inductive b seed = 
567       fun (_,n,ty,cl) ->
568         let ty = nast_of_cic ~context:[] ty in
569         `Inductive
570           { K.inductive_id = gen_id inductive_prefix seed;
571             K.inductive_name = n;
572             K.inductive_kind = b;
573             K.inductive_type = ty;
574             K.inductive_constructors = build_constructors seed cl
575            }
576 in
577 let build_fixpoint b seed = 
578       fun (_,n,_,ty,t) ->
579         let t = nast_of_cic ~context:[] t in
580         let ty = nast_of_cic ~context:[] ty in
581         `Definition
582           { K.def_id = gen_id inductive_prefix seed;
583             K.def_name = Some n;
584             K.def_aref = "";
585             K.def_type = ty;
586             K.def_term = t;
587            }
588 in
589   let res =
590    match kind with
591     | NCic.Fixpoint (is_rec, ifl, _) -> 
592          (gen_id object_prefix seed, conjectures,
593             `Joint
594               { K.joint_id = gen_id joint_prefix seed;
595                 K.joint_kind = 
596                    if is_rec then 
597                         `Recursive (List.map (fun (_,_,i,_,_) -> i) ifl)
598                    else `CoRecursive;
599                 K.joint_defs = List.map (build_fixpoint is_rec seed) ifl
600               }) 
601     | NCic.Inductive (is_ind, lno, itl, _) ->
602          (gen_id object_prefix seed, conjectures,
603             `Joint
604               { K.joint_id = gen_id joint_prefix seed;
605                 K.joint_kind = 
606                    if is_ind then `Inductive lno else `CoInductive lno;
607                 K.joint_defs = List.map (build_inductive is_ind seed) itl
608               }) 
609     | NCic.Constant (_,_,Some bo,ty,_) ->
610        let ty = nast_of_cic ~context:[] ty in
611        let bo = nast_of_cic ~context:[] bo in
612         (gen_id object_prefix seed, conjectures,
613           `Def (K.Const,ty,
614             build_def_item seed [] [] (get_id bo) (NUri.name_of_uri uri) bo ty))
615     | NCic.Constant (_,_,None,ty,_) ->
616        let ty = nast_of_cic ~context:[] ty in
617          (gen_id object_prefix seed, conjectures,
618            `Decl (K.Const,
619              (*CSC: ??? get_id ty here used to be the id of the axiom! *)
620              build_decl_item seed (get_id ty) (NUri.name_of_uri uri) ty))
621  in
622   res,ids_to_refs
623 ;;