]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/acic_content/termAcicContent.ml
test branch
[helm.git] / helm / ocaml / acic_content / termAcicContent.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$ *)
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 type interpretation_id = int
36
37 let idref id t = Ast.AttributedTerm (`IdRef id, t)
38
39 type term_info =
40   { sort: (Cic.id, Ast.sort_kind) Hashtbl.t;
41     uri: (Cic.id, UriManager.uri) Hashtbl.t;
42   }
43
44 let get_types uri =
45   let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
46     match o with
47       | Cic.InductiveDefinition (l,_,_,_) -> l 
48       | _ -> assert false
49
50 let name_of_inductive_type uri i = 
51   let types = get_types uri in
52   let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
53   name
54
55   (* returns <name, type> pairs *)
56 let constructors_of_inductive_type uri i =
57   let types = get_types uri in
58   let (_, _, _, constructors) = 
59     try List.nth types i with Not_found -> assert false
60   in
61   constructors
62
63   (* returns name only *)
64 let constructor_of_inductive_type uri i j =
65   (try
66     fst (List.nth (constructors_of_inductive_type uri i) (j-1))
67   with Not_found -> assert false)
68
69 let ast_of_acic0 term_info acic k =
70   let k = k term_info in
71   let id_to_uris = term_info.uri in
72   let register_uri id uri = Hashtbl.add id_to_uris id uri in
73   let sort_of_id id =
74     try
75       Hashtbl.find term_info.sort id
76     with Not_found ->
77       prerr_endline (sprintf "warning: sort of id %s not found, using Type" id);
78       `Type (CicUniv.fresh ())
79   in
80   let aux_substs substs =
81     Some
82       (List.map
83         (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
84         substs)
85   in
86   let aux_context context =
87     List.map
88       (function
89         | None -> None
90         | Some annterm -> Some (k annterm))
91       context
92   in
93   let aux = function
94     | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
95     | Cic.AVar (id,uri,substs) ->
96         register_uri id uri;
97         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
98     | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
99     | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
100     | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
101     | Cic.ASort (id,Cic.Type u) -> idref id (Ast.Sort (`Type u))
102     | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
103     | Cic.AImplicit (id, Some `Hole) -> idref id Ast.UserInput
104     | Cic.AImplicit (id, _) -> idref id Ast.Implicit
105     | Cic.AProd (id,n,s,t) ->
106         let binder_kind =
107           match sort_of_id id with
108           | `Set | `Type _ -> `Pi
109           | `Prop | `CProp -> `Forall
110         in
111         idref id (Ast.Binder (binder_kind,
112           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
113     | Cic.ACast (id,v,t) -> idref id (Ast.Cast (k v, k t))
114     | Cic.ALambda (id,n,s,t) ->
115         idref id (Ast.Binder (`Lambda,
116           (CicNotationUtil.name_of_cic_name n, Some (k s)), k t))
117     | Cic.ALetIn (id,n,s,t) ->
118         idref id (Ast.LetIn ((CicNotationUtil.name_of_cic_name n, None),
119           k s, k t))
120     | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
121     | Cic.AConst (id,uri,substs) ->
122         register_uri id uri;
123         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
124     | Cic.AMutInd (id,uri,i,substs) ->
125         let name = name_of_inductive_type uri i in
126         let uri_str = UriManager.string_of_uri uri in
127         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
128         register_uri id (UriManager.uri_of_string puri_str);
129         idref id (Ast.Ident (name, aux_substs substs))
130     | Cic.AMutConstruct (id,uri,i,j,substs) ->
131         let name = constructor_of_inductive_type uri i j in
132         let uri_str = UriManager.string_of_uri uri in
133         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
134         register_uri id (UriManager.uri_of_string puri_str);
135         idref id (Ast.Ident (name, aux_substs substs))
136     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
137         let name = name_of_inductive_type uri typeno in
138         let uri_str = UriManager.string_of_uri uri in
139         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
140         let ctor_puri j =
141           UriManager.uri_of_string
142             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
143         in
144         let case_indty = name, Some (UriManager.uri_of_string puri_str) in
145         let constructors = constructors_of_inductive_type uri typeno in
146         let rec eat_branch ty pat =
147           match (ty, pat) with
148           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
149               let (cv, rhs) = eat_branch t t' in
150               (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
151           | _, _ -> [], k pat
152         in
153         let j = ref 0 in
154         let patterns =
155           try
156             List.map2
157               (fun (name, ty) pat ->
158                 incr j;
159                 let (capture_variables, rhs) = eat_branch ty pat in
160                 ((name, Some (ctor_puri !j), capture_variables), rhs))
161               constructors patterns
162           with Invalid_argument _ -> assert false
163         in
164         idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
165     | Cic.AFix (id, no, funs) -> 
166         let defs = 
167           List.map
168             (fun (_, n, decr_idx, ty, bo) ->
169               ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
170             funs
171         in
172         let name =
173           try
174             (match List.nth defs no with
175             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
176             | _ -> assert false)
177           with Not_found -> assert false
178         in
179         idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
180     | Cic.ACoFix (id, no, funs) -> 
181         let defs = 
182           List.map
183             (fun (_, n, ty, bo) ->
184               ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
185             funs
186         in
187         let name =
188           try
189             (match List.nth defs no with
190             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
191             | _ -> assert false)
192           with Not_found -> assert false
193         in
194         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
195   in
196   aux acic
197
198   (* persistent state *)
199
200 let level2_patterns32 = Hashtbl.create 211
201 let interpretations = Hashtbl.create 211  (* symb -> id list ref *)
202
203 let compiled32 = ref None
204 let pattern32_matrix = ref []
205
206 let get_compiled32 () =
207   match !compiled32 with
208   | None -> assert false
209   | Some f -> Lazy.force f
210
211 let set_compiled32 f = compiled32 := Some f
212
213 let add_idrefs =
214   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
215
216 let instantiate32 term_info idrefs env symbol args =
217   let rec instantiate_arg = function
218     | Ast.IdentArg (n, name) ->
219         let t = (try List.assoc name env with Not_found -> assert false) in
220         let rec count_lambda = function
221           | Ast.AttributedTerm (_, t) -> count_lambda t
222           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
223           | _ -> 0
224         in
225         let rec add_lambda t n =
226           if n > 0 then
227             let name = CicNotationUtil.fresh_name () in
228             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
229               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
230           else
231             t
232         in
233         add_lambda t (n - count_lambda t)
234   in
235   let head =
236     let symbol = Ast.Symbol (symbol, 0) in
237     add_idrefs idrefs symbol
238   in
239   if args = [] then head
240   else Ast.Appl (head :: List.map instantiate_arg args)
241
242 let rec ast_of_acic1 term_info annterm = 
243   let id_to_uris = term_info.uri in
244   let register_uri id uri = Hashtbl.add id_to_uris id uri in
245   match (get_compiled32 ()) annterm with
246   | None -> ast_of_acic0 term_info annterm ast_of_acic1
247   | Some (env, ctors, pid) -> 
248       let idrefs =
249         List.map
250           (fun annterm ->
251             let idref = CicUtil.id_of_annterm annterm in
252             (try
253               register_uri idref
254                 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
255             with Invalid_argument _ -> ());
256             idref)
257           ctors
258       in
259       let env' =
260         List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
261       in
262       let _, symbol, args, _ =
263         try
264           Hashtbl.find level2_patterns32 pid
265         with Not_found -> assert false
266       in
267       let ast = instantiate32 term_info idrefs env' symbol args in
268       Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
269
270 let load_patterns32 t =
271   let t =
272     HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
273   in
274   set_compiled32 (lazy (Acic2astMatcher.Matcher32.compiler t))
275
276 let ast_of_acic id_to_sort annterm =
277   debug_print (lazy ("ast_of_acic <- "
278     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
279   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
280   let ast = ast_of_acic1 term_info annterm in
281   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
282   ast, term_info.uri
283
284 let fresh_id =
285   let counter = ref ~-1 in
286   fun () ->
287     incr counter;
288     !counter
289
290 let add_interpretation dsc (symbol, args) appl_pattern =
291   let id = fresh_id () in
292   Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern);
293   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
294   load_patterns32 !pattern32_matrix;
295   (try
296     let ids = Hashtbl.find interpretations symbol in
297     ids := id :: !ids
298   with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
299   id
300
301 let get_all_interpretations () =
302   List.map
303     (function (_, _, id) ->
304       let (dsc, _, _, _) =
305         try
306           Hashtbl.find level2_patterns32 id
307         with Not_found -> assert false
308       in
309       (id, dsc))
310     !pattern32_matrix
311
312 let get_active_interpretations () =
313   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
314     !pattern32_matrix
315
316 let set_active_interpretations ids =
317   let pattern32_matrix' =
318     List.map
319       (function 
320         | (_, ap, id) when List.mem id ids -> (true, ap, id)
321         | (_, ap, id) -> (false, ap, id))
322       !pattern32_matrix
323   in
324   pattern32_matrix := pattern32_matrix';
325   load_patterns32 !pattern32_matrix
326
327 exception Interpretation_not_found
328
329 let lookup_interpretations symbol =
330   try
331    HExtlib.list_uniq
332     (List.sort Pervasives.compare
333      (List.map
334       (fun id ->
335         let (dsc, _, args, appl_pattern) =
336           try
337             Hashtbl.find level2_patterns32 id
338           with Not_found -> assert false 
339         in
340         dsc, args, appl_pattern)
341       !(Hashtbl.find interpretations symbol)))
342   with Not_found -> raise Interpretation_not_found
343
344 let remove_interpretation id =
345   (try
346     let _, symbol, _, _ = Hashtbl.find level2_patterns32 id in
347     let ids = Hashtbl.find interpretations symbol in
348     ids := List.filter ((<>) id) !ids;
349     Hashtbl.remove level2_patterns32 id;
350   with Not_found -> raise Interpretation_not_found);
351   pattern32_matrix :=
352     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
353   load_patterns32 !pattern32_matrix
354
355 let _ = load_patterns32 []
356
357 let instantiate_appl_pattern env appl_pattern =
358   let lookup name =
359     try List.assoc name env
360     with Not_found ->
361       prerr_endline (sprintf "Name %s not found" name);
362       assert false
363   in
364   let rec aux = function
365     | Ast.UriPattern uri -> CicUtil.term_of_uri uri
366     | Ast.ImplicitPattern -> Cic.Implicit None
367     | Ast.VarPattern name -> lookup name
368     | Ast.ApplPattern terms -> Cic.Appl (List.map aux terms)
369   in
370   aux appl_pattern
371