]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_cic_content/nTermCicContent.ml
The substitution is now taken in account when printing sequents in the
[helm.git] / helm / software / 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 = CicNotationPt
31
32 let debug = false
33 let debug_print s = if debug then prerr_endline (Lazy.force s) else ()
34
35 (*
36 type interpretation_id = int
37
38 let idref id t = Ast.AttributedTerm (`IdRef id, t)
39
40 type term_info =
41   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
42     uri: (Cic.id, UriManager.uri) Hashtbl.t;
43   }
44
45 let get_types uri =
46   let o,_ = CicEnvironment.get_obj CicUniv.oblivion_ugraph uri in
47     match o with
48       | Cic.InductiveDefinition (l,_,lpsno,_) -> l, lpsno 
49       | _ -> assert false
50
51 let name_of_inductive_type uri i = 
52   let types, _ = get_types uri in
53   let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
54   name
55
56   (* returns <name, type> pairs *)
57 let constructors_of_inductive_type uri i =
58   let types, _ = get_types uri in
59   let (_, _, _, constructors) = 
60     try List.nth types i with Not_found -> assert false
61   in
62   constructors
63
64   (* returns name only *)
65 let constructor_of_inductive_type uri i j =
66   (try
67     fst (List.nth (constructors_of_inductive_type uri i) (j-1))
68   with Not_found -> assert false)
69
70   (* returns the number of left parameters *)
71 let left_params_no_of_inductive_type uri =
72    snd (get_types uri)
73 *)
74
75 (* CODICE c&p da NCicPp *)
76 let r2s pp_fix_name r = 
77   try
78     match r with
79     | NReference.Ref (u,NReference.Ind (_,i,_)) -> 
80         (match NCicLibrary.get_obj u with
81         | _,_,_,_, NCic.Inductive (_,_,itl,_) ->
82             let _,name,_,_ = List.nth itl i in name
83         | _ -> assert false)
84     | NReference.Ref (u,NReference.Con (i,j,_)) -> 
85         (match NCicLibrary.get_obj u with
86         | _,_,_,_, NCic.Inductive (_,_,itl,_) ->
87             let _,_,_,cl = List.nth itl i in
88             let _,name,_ = List.nth cl (j-1) in name
89         | _ -> assert false)
90     | NReference.Ref (u,(NReference.Decl | NReference.Def _)) -> 
91         (match NCicLibrary.get_obj u with
92         | _,_,_,_, NCic.Constant (_,name,_,_,_) -> name
93         | _ -> assert false)
94     | NReference.Ref (u,(NReference.Fix (i,_,_)|NReference.CoFix i)) ->
95         (match NCicLibrary.get_obj u with
96         | _,_,_,_, NCic.Fixpoint (_,fl,_) -> 
97             if pp_fix_name then
98               let _,name,_,_,_ = List.nth fl i in name
99             else 
100               NUri.name_of_uri u ^"("^ string_of_int i ^ ")"
101         | _ -> assert false)
102   with NCicLibrary.ObjectNotFound _ -> NReference.string_of_reference r
103 ;;
104
105 let nast_of_cic ~subst =
106   let rec k = function
107     | NCic.Rel n -> Ast.Ident ("-" ^ string_of_int n, None)
108     | NCic.Const r -> Ast.Ident (r2s true r, None)
109     | NCic.Meta (n,lc) when List.mem_assoc n subst -> 
110         let _,_,t,_ = List.assoc n subst in
111          k (*ctx*) (NCicSubstitution.subst_meta lc t)
112     | NCic.Meta (n,l) -> Ast.Meta (n, [](*aux_context l*))
113     | NCic.Sort NCic.Prop -> Ast.Sort `Prop
114     | NCic.Sort NCic.Type _ -> Ast.Sort `Set
115     | NCic.Implicit `Hole -> Ast.UserInput
116     | NCic.Implicit _ -> Ast.Implicit
117     | NCic.Prod (n,s,t) ->
118         let binder_kind = `Forall in
119          Ast.Binder (binder_kind, (Ast.Ident (n,None), Some (k s)), k t)
120     | NCic.Lambda (n,s,t) ->
121         Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k s)), k t)
122     | NCic.LetIn (n,s,ty,t) ->
123         Ast.LetIn ((Ast.Ident (n,None), Some (k ty)), k s, k t)
124     | NCic.Appl (NCic.Meta (n,lc) :: args) when List.mem_assoc n subst -> 
125        let _,_,t,_ = List.assoc n subst in
126        let hd = NCicSubstitution.subst_meta lc t in
127         k (*ctx*)
128          (NCicReduction.head_beta_reduce ~upto:(List.length args)
129            (match hd with
130            | NCic.Appl l -> NCic.Appl (l@args)
131            | _ -> NCic.Appl (hd :: args)))
132     | NCic.Appl args -> Ast.Appl (List.map k args)
133     (*| NCic.AConst (id,uri,substs) ->
134         register_uri id uri;
135         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))*)
136     | NCic.Match (uri,ty,te,patterns) ->
137 (*
138         let name = NReference.name_of_reference uri in
139         let uri_str = UriManager.string_of_uri uri in
140         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
141         let ctor_puri j =
142           UriManager.uri_of_string
143             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
144         in
145         let case_indty = name, Some (UriManager.uri_of_string puri_str) in
146         let constructors = constructors_of_inductive_type uri typeno in
147         let lpsno = left_params_no_of_inductive_type uri in
148         let rec eat_branch n ty pat =
149           match (ty, pat) with
150           | NCic.Prod (_, _, t), _ when n > 0 -> eat_branch (pred n) t pat 
151           | NCic.Prod (_, _, t), NCic.ALambda (_, name, s, t') ->
152               let (cv, rhs) = eat_branch 0 t t' in
153               (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
154           | _, _ -> [], k pat
155         in
156         let j = ref 0 in
157         let patterns =
158           try
159             List.map2
160               (fun (name, ty) pat ->
161                 incr j;
162                 let name,(capture_variables,rhs) =
163                  match output_type with
164                     `Term -> name, eat_branch lpsno ty pat
165                   | `Pattern -> "_", ([], k pat)
166                 in
167                  Ast.Pattern (name, Some (ctor_puri !j), capture_variables), rhs
168               ) constructors patterns
169           with Invalid_argument _ -> assert false
170         in
171         let indty =
172          match output_type with
173             `Pattern -> None
174           | `Term -> Some case_indty
175         in
176         idref id (Ast.Case (k te, indty, Some (k ty), patterns))
177 *) Ast.Ident ("Un case",None)
178   in
179    k
180 ;;
181
182 let nmap_sequent ~subst (i,(n,context,ty):int * NCic.conjecture) =
183  let module K = Content in
184  let context' =
185   List.map
186    (function
187      | name,NCic.Decl t ->
188          Some
189           (* We should call build_decl_item, but we have not computed *)
190           (* the inner-types ==> we always produce a declaration      *)
191           (`Declaration
192             { K.dec_name = (Some name);
193               K.dec_id = "-1"; 
194               K.dec_inductive = false;
195               K.dec_aref = "-1";
196               K.dec_type = t
197             })
198      | name,NCic.Def (t,ty) ->
199          Some
200           (* We should call build_def_item, but we have not computed *)
201           (* the inner-types ==> we always produce a declaration     *)
202           (`Definition
203              { K.def_name = (Some name);
204                K.def_id = "-1"; 
205                K.def_aref = "-1";
206                K.def_term = t;
207                K.def_type = ty
208              })
209    ) context
210  in
211   "-1",i,context',ty
212 ;;
213
214 (*
215   (* persistent state *)
216
217 let initial_level2_patterns32 () = Hashtbl.create 211
218 let initial_interpretations () = Hashtbl.create 211
219
220 let level2_patterns32 = ref (initial_level2_patterns32 ())
221 (* symb -> id list ref *)
222 let interpretations = ref (initial_interpretations ())
223 let compiled32 = ref None
224 let pattern32_matrix = ref []
225 let counter = ref ~-1 
226
227 let stack = ref []
228
229 let push () =
230  stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
231  counter := ~-1;
232  level2_patterns32 := initial_level2_patterns32 ();
233  interpretations := initial_interpretations ();
234  compiled32 := None;
235  pattern32_matrix := []
236 ;;
237
238 let pop () =
239  match !stack with
240     [] -> assert false
241   | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
242    stack := old;
243    counter := ocounter;
244    level2_patterns32 := olevel2_patterns32;
245    interpretations := ointerpretations;
246    compiled32 := ocompiled32;
247    pattern32_matrix := opattern32_matrix
248 ;;
249
250 let get_compiled32 () =
251   match !compiled32 with
252   | None -> assert false
253   | Some f -> Lazy.force f
254
255 let set_compiled32 f = compiled32 := Some f
256
257 let add_idrefs =
258   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
259
260 let instantiate32 term_info idrefs env symbol args =
261   let rec instantiate_arg = function
262     | Ast.IdentArg (n, name) ->
263         let t = 
264           try List.assoc name env 
265           with Not_found -> prerr_endline ("name not found in env: "^name);
266                             assert false
267         in
268         let rec count_lambda = function
269           | Ast.AttributedTerm (_, t) -> count_lambda t
270           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
271           | _ -> 0
272         in
273         let rec add_lambda t n =
274           if n > 0 then
275             let name = CicNotationUtil.fresh_name () in
276             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
277               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
278           else
279             t
280         in
281         add_lambda t (n - count_lambda t)
282   in
283   let head =
284     let symbol = Ast.Symbol (symbol, 0) in
285     add_idrefs idrefs symbol
286   in
287   if args = [] then head
288   else Ast.Appl (head :: List.map instantiate_arg args)
289
290 let rec ast_of_acic1 ~output_type term_info annterm = 
291   let id_to_uris = term_info.uri in
292   let register_uri id uri = Hashtbl.add id_to_uris id uri in
293   match (get_compiled32 ()) annterm with
294   | None ->
295      ast_of_acic0 ~output_type term_info annterm (ast_of_acic1 ~output_type)
296   | Some (env, ctors, pid) -> 
297       let idrefs =
298         List.map
299           (fun annterm ->
300             let idref = CicUtil.id_of_annterm annterm in
301             (try
302               register_uri idref
303                 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
304             with Invalid_argument _ -> ());
305             idref)
306           ctors
307       in
308       let env' =
309        List.map
310         (fun (name, term) -> name, ast_of_acic1 ~output_type term_info term) env
311       in
312       let _, symbol, args, _ =
313         try
314           Hashtbl.find !level2_patterns32 pid
315         with Not_found -> assert false
316       in
317       let ast = instantiate32 term_info idrefs env' symbol args in
318       Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
319
320 let load_patterns32 t =
321   let t =
322     HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
323   in
324   set_compiled32 (lazy (Acic2astMatcher.Matcher32.compiler t))
325
326 let ast_of_acic ~output_type id_to_sort annterm =
327   debug_print (lazy ("ast_of_acic <- "
328     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
329   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
330   let ast = ast_of_acic1 ~output_type term_info annterm in
331   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
332   ast, term_info.uri
333
334 let fresh_id =
335   fun () ->
336     incr counter;
337     !counter
338
339 let add_interpretation dsc (symbol, args) appl_pattern =
340   let id = fresh_id () in
341   Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
342   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
343   load_patterns32 !pattern32_matrix;
344   (try
345     let ids = Hashtbl.find !interpretations symbol in
346     ids := id :: !ids
347   with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
348   id
349
350 let get_all_interpretations () =
351   List.map
352     (function (_, _, id) ->
353       let (dsc, _, _, _) =
354         try
355           Hashtbl.find !level2_patterns32 id
356         with Not_found -> assert false
357       in
358       (id, dsc))
359     !pattern32_matrix
360
361 let get_active_interpretations () =
362   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
363     !pattern32_matrix
364
365 let set_active_interpretations ids =
366   let pattern32_matrix' =
367     List.map
368       (function 
369         | (_, ap, id) when List.mem id ids -> (true, ap, id)
370         | (_, ap, id) -> (false, ap, id))
371       !pattern32_matrix
372   in
373   pattern32_matrix := pattern32_matrix';
374   load_patterns32 !pattern32_matrix
375
376 exception Interpretation_not_found
377
378 let lookup_interpretations symbol =
379   try
380    HExtlib.list_uniq
381     (List.sort Pervasives.compare
382      (List.map
383       (fun id ->
384         let (dsc, _, args, appl_pattern) =
385           try
386             Hashtbl.find !level2_patterns32 id
387           with Not_found -> assert false 
388         in
389         dsc, args, appl_pattern)
390       !(Hashtbl.find !interpretations symbol)))
391   with Not_found -> raise Interpretation_not_found
392
393 let remove_interpretation id =
394   (try
395     let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
396     let ids = Hashtbl.find !interpretations symbol in
397     ids := List.filter ((<>) id) !ids;
398     Hashtbl.remove !level2_patterns32 id;
399   with Not_found -> raise Interpretation_not_found);
400   pattern32_matrix :=
401     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
402   load_patterns32 !pattern32_matrix
403
404 let _ = load_patterns32 []
405
406 let instantiate_appl_pattern 
407   ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern 
408 =
409   let lookup name =
410     try List.assoc name env
411     with Not_found ->
412       prerr_endline (sprintf "Name %s not found" name);
413       assert false
414   in
415   let rec aux = function
416     | Ast.UriPattern uri -> term_of_uri uri
417     | Ast.ImplicitPattern -> mk_implicit false
418     | Ast.VarPattern name -> lookup name
419     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
420   in
421   aux appl_pattern
422 *)