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