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