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