]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_cic_content/nTermCicContent.ml
nasty change in the lexer/parser:
[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_cic ~idref ~output_type ~subst ~context =
59   let rec k ctx = function
60     | NCic.Rel n ->
61        (try 
62          let name,_ = List.nth ctx (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 ctx),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 ctx (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 ctx (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 ctx s)),
94           k ((n,NCic.Decl s)::ctx) t))
95     | NCic.Lambda (n,s,t) ->
96         idref (Ast.Binder (`Lambda,(Ast.Ident (n,None), Some (k ctx s)),
97          k ((n,NCic.Decl s)::ctx) t))
98     | NCic.LetIn (n,s,ty,t) ->
99         idref (Ast.LetIn ((Ast.Ident (n,None), Some (k ctx ty)), k ctx s,
100          k ((n,NCic.Decl s)::ctx) 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 ctx
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 ctx) 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 ctx s)) :: cv, rhs
134           | _, _ -> [], k ctx 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 ctx ty pat
145                   | `Pattern -> "_", ([], k ctx 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 ctx te, indty, Some (k ctx outty), patterns))
157   in
158    k context
159 ;;
160
161 let nmap_sequent ~subst (i,(n,context,ty):int * NCic.conjecture) =
162  let module K = Content in
163  let nast_of_cic = nast_of_cic ~idref:(idref ()) ~output_type:`Term ~subst in
164  let context',_ =
165   List.fold_right
166    (fun item (res,context) ->
167      match item with
168       | name,NCic.Decl t ->
169          Some
170           (* We should call build_decl_item, but we have not computed *)
171           (* the inner-types ==> we always produce a declaration      *)
172           (`Declaration
173             { K.dec_name = (Some name);
174               K.dec_id = "-1"; 
175               K.dec_inductive = false;
176               K.dec_aref = "-1";
177               K.dec_type = nast_of_cic ~context t
178             })::res,item::context
179       | name,NCic.Def (t,ty) ->
180          Some
181           (* We should call build_def_item, but we have not computed *)
182           (* the inner-types ==> we always produce a declaration     *)
183           (`Definition
184              { K.def_name = (Some name);
185                K.def_id = "-1"; 
186                K.def_aref = "-1";
187                K.def_term = nast_of_cic ~context t;
188                K.def_type = nast_of_cic ~context ty
189              })::res,item::context
190    ) context ([],[])
191  in
192   "-1",i,context',nast_of_cic ~context ty
193 ;;
194
195 (*
196   (* persistent state *)
197
198 let initial_level2_patterns32 () = Hashtbl.create 211
199 let initial_interpretations () = Hashtbl.create 211
200
201 let level2_patterns32 = ref (initial_level2_patterns32 ())
202 (* symb -> id list ref *)
203 let interpretations = ref (initial_interpretations ())
204 let compiled32 = ref None
205 let pattern32_matrix = ref []
206 let counter = ref ~-1 
207
208 let stack = ref []
209
210 let push () =
211  stack := (!counter,!level2_patterns32,!interpretations,!compiled32,!pattern32_matrix)::!stack;
212  counter := ~-1;
213  level2_patterns32 := initial_level2_patterns32 ();
214  interpretations := initial_interpretations ();
215  compiled32 := None;
216  pattern32_matrix := []
217 ;;
218
219 let pop () =
220  match !stack with
221     [] -> assert false
222   | (ocounter,olevel2_patterns32,ointerpretations,ocompiled32,opattern32_matrix)::old ->
223    stack := old;
224    counter := ocounter;
225    level2_patterns32 := olevel2_patterns32;
226    interpretations := ointerpretations;
227    compiled32 := ocompiled32;
228    pattern32_matrix := opattern32_matrix
229 ;;
230
231 let get_compiled32 () =
232   match !compiled32 with
233   | None -> assert false
234   | Some f -> Lazy.force f
235
236 let set_compiled32 f = compiled32 := Some f
237
238 let add_idrefs =
239   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
240
241 let instantiate32 term_info idrefs env symbol args =
242   let rec instantiate_arg = function
243     | Ast.IdentArg (n, name) ->
244         let t = 
245           try List.assoc name env 
246           with Not_found -> prerr_endline ("name not found in env: "^name);
247                             assert false
248         in
249         let rec count_lambda = function
250           | Ast.AttributedTerm (_, t) -> count_lambda t
251           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
252           | _ -> 0
253         in
254         let rec add_lambda t n =
255           if n > 0 then
256             let name = CicNotationUtil.fresh_name () in
257             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
258               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
259           else
260             t
261         in
262         add_lambda t (n - count_lambda t)
263   in
264   let head =
265     let symbol = Ast.Symbol (symbol, 0) in
266     add_idrefs idrefs symbol
267   in
268   if args = [] then head
269   else Ast.Appl (head :: List.map instantiate_arg args)
270
271 let rec ast_of_acic1 ~output_type term_info annterm = 
272   let id_to_uris = term_info.uri in
273   let register_uri id uri = Hashtbl.add id_to_uris id uri in
274   match (get_compiled32 ()) annterm with
275   | None ->
276      ast_of_acic0 ~output_type term_info annterm (ast_of_acic1 ~output_type)
277   | Some (env, ctors, pid) -> 
278       let idrefs =
279         List.map
280           (fun annterm ->
281             let idref = CicUtil.id_of_annterm annterm in
282             (try
283               register_uri idref
284                 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
285             with Invalid_argument _ -> ());
286             idref)
287           ctors
288       in
289       let env' =
290        List.map
291         (fun (name, term) -> name, ast_of_acic1 ~output_type term_info term) env
292       in
293       let _, symbol, args, _ =
294         try
295           Hashtbl.find !level2_patterns32 pid
296         with Not_found -> assert false
297       in
298       let ast = instantiate32 term_info idrefs env' symbol args in
299       Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
300
301 let load_patterns32 t =
302   let t =
303     HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
304   in
305   set_compiled32 (lazy (Acic2astMatcher.Matcher32.compiler t))
306
307 let ast_of_acic ~output_type id_to_sort annterm =
308   debug_print (lazy ("ast_of_acic <- "
309     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
310   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
311   let ast = ast_of_acic1 ~output_type term_info annterm in
312   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
313   ast, term_info.uri
314
315 let fresh_id =
316   fun () ->
317     incr counter;
318     !counter
319
320 let add_interpretation dsc (symbol, args) appl_pattern =
321   let id = fresh_id () in
322   Hashtbl.add !level2_patterns32 id (dsc, symbol, args, appl_pattern);
323   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
324   load_patterns32 !pattern32_matrix;
325   (try
326     let ids = Hashtbl.find !interpretations symbol in
327     ids := id :: !ids
328   with Not_found -> Hashtbl.add !interpretations symbol (ref [id]));
329   id
330
331 let get_all_interpretations () =
332   List.map
333     (function (_, _, id) ->
334       let (dsc, _, _, _) =
335         try
336           Hashtbl.find !level2_patterns32 id
337         with Not_found -> assert false
338       in
339       (id, dsc))
340     !pattern32_matrix
341
342 let get_active_interpretations () =
343   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
344     !pattern32_matrix
345
346 let set_active_interpretations ids =
347   let pattern32_matrix' =
348     List.map
349       (function 
350         | (_, ap, id) when List.mem id ids -> (true, ap, id)
351         | (_, ap, id) -> (false, ap, id))
352       !pattern32_matrix
353   in
354   pattern32_matrix := pattern32_matrix';
355   load_patterns32 !pattern32_matrix
356
357 exception Interpretation_not_found
358
359 let lookup_interpretations symbol =
360   try
361    HExtlib.list_uniq
362     (List.sort Pervasives.compare
363      (List.map
364       (fun id ->
365         let (dsc, _, args, appl_pattern) =
366           try
367             Hashtbl.find !level2_patterns32 id
368           with Not_found -> assert false 
369         in
370         dsc, args, appl_pattern)
371       !(Hashtbl.find !interpretations symbol)))
372   with Not_found -> raise Interpretation_not_found
373
374 let remove_interpretation id =
375   (try
376     let dsc, symbol, _, _ = Hashtbl.find !level2_patterns32 id in
377     let ids = Hashtbl.find !interpretations symbol in
378     ids := List.filter ((<>) id) !ids;
379     Hashtbl.remove !level2_patterns32 id;
380   with Not_found -> raise Interpretation_not_found);
381   pattern32_matrix :=
382     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
383   load_patterns32 !pattern32_matrix
384
385 let _ = load_patterns32 []
386
387 let instantiate_appl_pattern 
388   ~mk_appl ~mk_implicit ~term_of_uri env appl_pattern 
389 =
390   let lookup name =
391     try List.assoc name env
392     with Not_found ->
393       prerr_endline (sprintf "Name %s not found" name);
394       assert false
395   in
396   let rec aux = function
397     | Ast.UriPattern uri -> term_of_uri uri
398     | Ast.ImplicitPattern -> mk_implicit false
399     | Ast.VarPattern name -> lookup name
400     | Ast.ApplPattern terms -> mk_appl (List.map aux terms)
401   in
402   aux appl_pattern
403 *)