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