]> matita.cs.unibo.it Git - helm.git/blob - components/acic_content/termAcicContent.ml
Huge commit:
[helm.git] / 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        let last_n n l =
125          let rec aux =
126           function
127              [] -> assert false
128            | [_] as l -> l,1
129            | he::tl ->
130               let (res,len) as res' = aux tl in
131                if len < n then
132                 he::res,len + 1
133                else
134                 res'
135          in
136           match fst (aux l) with
137              [] -> assert false
138            | [t] -> t
139            | Ast.AttributedTerm (_,(Ast.Appl l))::tl -> 
140                idref aid (Ast.Appl (l@tl))
141            | l -> idref aid (Ast.Appl l)
142        in
143        let deannot_he = Deannotate.deannotate_term he in
144        if CoercDb.is_a_coercion' deannot_he && !Acic2content.hide_coercions
145        then
146          match CoercDb.is_a_coercion_to_funclass deannot_he with
147          | None -> idref aid (last_n 1 (List.map k tl))
148          | Some i -> idref aid (last_n (i+1) (List.map k tl))
149        else
150         idref aid (Ast.Appl (List.map k args))
151     | Cic.AAppl (aid,args) ->
152         idref aid (Ast.Appl (List.map k args))
153     | Cic.AConst (id,uri,substs) ->
154         register_uri id uri;
155         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
156     | Cic.AMutInd (id,uri,i,substs) ->
157         let name = name_of_inductive_type uri i in
158         let uri_str = UriManager.string_of_uri uri in
159         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (i+1) in
160         register_uri id (UriManager.uri_of_string puri_str);
161         idref id (Ast.Ident (name, aux_substs substs))
162     | Cic.AMutConstruct (id,uri,i,j,substs) ->
163         let name = constructor_of_inductive_type uri i j in
164         let uri_str = UriManager.string_of_uri uri in
165         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
166         register_uri id (UriManager.uri_of_string puri_str);
167         idref id (Ast.Ident (name, aux_substs substs))
168     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
169         let name = name_of_inductive_type uri typeno in
170         let uri_str = UriManager.string_of_uri uri in
171         let puri_str = sprintf "%s#xpointer(1/%d)" uri_str (typeno+1) in
172         let ctor_puri j =
173           UriManager.uri_of_string
174             (sprintf "%s#xpointer(1/%d/%d)" uri_str (typeno+1) j)
175         in
176         let case_indty = name, Some (UriManager.uri_of_string puri_str) in
177         let constructors = constructors_of_inductive_type uri typeno in
178         let rec eat_branch ty pat =
179           match (ty, pat) with
180           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
181               let (cv, rhs) = eat_branch t t' in
182               (CicNotationUtil.name_of_cic_name name, Some (k s)) :: cv, rhs
183           | _, _ -> [], k pat
184         in
185         let j = ref 0 in
186         let patterns =
187           try
188             List.map2
189               (fun (name, ty) pat ->
190                 incr j;
191                 let (capture_variables, rhs) = eat_branch ty pat in
192                 ((name, Some (ctor_puri !j), capture_variables), rhs))
193               constructors patterns
194           with Invalid_argument _ -> assert false
195         in
196         idref id (Ast.Case (k te, Some case_indty, Some (k ty), patterns))
197     | Cic.AFix (id, no, funs) -> 
198         let defs = 
199           List.map
200             (fun (_, n, decr_idx, ty, bo) ->
201               let params,bo =
202                let rec aux =
203                 function
204                    Cic.ALambda (_,name,so,ta) ->
205                     let params,rest = aux ta in
206                      (CicNotationUtil.name_of_cic_name name,Some (k so))::
207                       params, rest
208                  | t -> [],t
209                in
210                 aux bo
211               in
212               let ty =
213                let rec eat_pis =
214                 function
215                    0,ty -> ty
216                  | n,Cic.AProd (_,_,_,ta) -> eat_pis (n - 1,ta)
217                  | n,ty ->
218                     (* I should do a whd here, but I have no context *)
219                     assert false
220                in
221                 eat_pis ((List.length params),ty)
222               in
223                (params,(Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
224             funs
225         in
226         let name =
227           try
228             (match List.nth defs no with
229             | _, (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
230             | _ -> assert false)
231           with Not_found -> assert false
232         in
233          idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
234     | Cic.ACoFix (id, no, funs) -> 
235         let defs = 
236           List.map
237             (fun (_, n, ty, bo) ->
238               let params,bo =
239                let rec aux =
240                 function
241                    Cic.ALambda (_,name,so,ta) ->
242                     let params,rest = aux ta in
243                      (CicNotationUtil.name_of_cic_name name,Some (k so))::
244                       params, rest
245                  | t -> [],t
246                in
247                 aux bo
248               in
249               let ty =
250                let rec eat_pis =
251                 function
252                    0,ty -> ty
253                  | n,Cic.AProd (_,_,_,ta) -> eat_pis (n - 1,ta)
254                  | n,ty ->
255                     (* I should do a whd here, but I have no context *)
256                     assert false
257                in
258                 eat_pis ((List.length params),ty)
259               in
260                (params,(Ast.Ident (n, None), Some (k ty)), k bo, 0))
261             funs
262         in
263         let name =
264           try
265             (match List.nth defs no with
266             | _, (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
267             | _ -> assert false)
268           with Not_found -> assert false
269         in
270         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
271   in
272   aux acic
273
274   (* persistent state *)
275
276 let level2_patterns32 = Hashtbl.create 211
277 let interpretations = Hashtbl.create 211  (* symb -> id list ref *)
278
279 let compiled32 = ref None
280 let pattern32_matrix = ref []
281
282 let get_compiled32 () =
283   match !compiled32 with
284   | None -> assert false
285   | Some f -> Lazy.force f
286
287 let set_compiled32 f = compiled32 := Some f
288
289 let add_idrefs =
290   List.fold_right (fun idref t -> Ast.AttributedTerm (`IdRef idref, t))
291
292 let instantiate32 term_info idrefs env symbol args =
293   let rec instantiate_arg = function
294     | Ast.IdentArg (n, name) ->
295         let t = (try List.assoc name env with Not_found -> assert false) in
296         let rec count_lambda = function
297           | Ast.AttributedTerm (_, t) -> count_lambda t
298           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
299           | _ -> 0
300         in
301         let rec add_lambda t n =
302           if n > 0 then
303             let name = CicNotationUtil.fresh_name () in
304             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
305               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
306           else
307             t
308         in
309         add_lambda t (n - count_lambda t)
310   in
311   let head =
312     let symbol = Ast.Symbol (symbol, 0) in
313     add_idrefs idrefs symbol
314   in
315   if args = [] then head
316   else Ast.Appl (head :: List.map instantiate_arg args)
317
318 let rec ast_of_acic1 term_info annterm = 
319   let id_to_uris = term_info.uri in
320   let register_uri id uri = Hashtbl.add id_to_uris id uri in
321   match (get_compiled32 ()) annterm with
322   | None -> ast_of_acic0 term_info annterm ast_of_acic1
323   | Some (env, ctors, pid) -> 
324       let idrefs =
325         List.map
326           (fun annterm ->
327             let idref = CicUtil.id_of_annterm annterm in
328             (try
329               register_uri idref
330                 (CicUtil.uri_of_term (Deannotate.deannotate_term annterm))
331             with Invalid_argument _ -> ());
332             idref)
333           ctors
334       in
335       let env' =
336         List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
337       in
338       let _, symbol, args, _ =
339         try
340           Hashtbl.find level2_patterns32 pid
341         with Not_found -> assert false
342       in
343       let ast = instantiate32 term_info idrefs env' symbol args in
344       Ast.AttributedTerm (`IdRef (CicUtil.id_of_annterm annterm), ast)
345
346 let load_patterns32 t =
347   let t =
348     HExtlib.filter_map (function (true, ap, id) -> Some (ap, id) | _ -> None) t
349   in
350   set_compiled32 (lazy (Acic2astMatcher.Matcher32.compiler t))
351
352 let ast_of_acic id_to_sort annterm =
353   debug_print (lazy ("ast_of_acic <- "
354     ^ CicPp.ppterm (Deannotate.deannotate_term annterm)));
355   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
356   let ast = ast_of_acic1 term_info annterm in
357   debug_print (lazy ("ast_of_acic -> " ^ CicNotationPp.pp_term ast));
358   ast, term_info.uri
359
360 let fresh_id =
361   let counter = ref ~-1 in
362   fun () ->
363     incr counter;
364     !counter
365
366 let add_interpretation dsc (symbol, args) appl_pattern =
367   let id = fresh_id () in
368   Hashtbl.add level2_patterns32 id (dsc, symbol, args, appl_pattern);
369   pattern32_matrix := (true, appl_pattern, id) :: !pattern32_matrix;
370   load_patterns32 !pattern32_matrix;
371   (try
372     let ids = Hashtbl.find interpretations symbol in
373     ids := id :: !ids
374   with Not_found -> Hashtbl.add interpretations symbol (ref [id]));
375   id
376
377 let get_all_interpretations () =
378   List.map
379     (function (_, _, id) ->
380       let (dsc, _, _, _) =
381         try
382           Hashtbl.find level2_patterns32 id
383         with Not_found -> assert false
384       in
385       (id, dsc))
386     !pattern32_matrix
387
388 let get_active_interpretations () =
389   HExtlib.filter_map (function (true, _, id) -> Some id | _ -> None)
390     !pattern32_matrix
391
392 let set_active_interpretations ids =
393   let pattern32_matrix' =
394     List.map
395       (function 
396         | (_, ap, id) when List.mem id ids -> (true, ap, id)
397         | (_, ap, id) -> (false, ap, id))
398       !pattern32_matrix
399   in
400   pattern32_matrix := pattern32_matrix';
401   load_patterns32 !pattern32_matrix
402
403 exception Interpretation_not_found
404
405 let lookup_interpretations symbol =
406   try
407    HExtlib.list_uniq
408     (List.sort Pervasives.compare
409      (List.map
410       (fun id ->
411         let (dsc, _, args, appl_pattern) =
412           try
413             Hashtbl.find level2_patterns32 id
414           with Not_found -> assert false 
415         in
416         dsc, args, appl_pattern)
417       !(Hashtbl.find interpretations symbol)))
418   with Not_found -> raise Interpretation_not_found
419
420 let remove_interpretation id =
421   (try
422     let _, symbol, _, _ = Hashtbl.find level2_patterns32 id in
423     let ids = Hashtbl.find interpretations symbol in
424     ids := List.filter ((<>) id) !ids;
425     Hashtbl.remove level2_patterns32 id;
426   with Not_found -> raise Interpretation_not_found);
427   pattern32_matrix :=
428     List.filter (fun (_, _, id') -> id <> id') !pattern32_matrix;
429   load_patterns32 !pattern32_matrix
430
431 let _ = load_patterns32 []
432
433 let instantiate_appl_pattern env appl_pattern =
434   let lookup name =
435     try List.assoc name env
436     with Not_found ->
437       prerr_endline (sprintf "Name %s not found" name);
438       assert false
439   in
440   let rec aux = function
441     | Ast.UriPattern uri -> CicUtil.term_of_uri uri
442     | Ast.ImplicitPattern -> Cic.Implicit None
443     | Ast.VarPattern name -> lookup name
444     | Ast.ApplPattern terms -> Cic.Appl (List.map aux terms)
445   in
446   aux appl_pattern
447