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