]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/cicNotationRew.ml
* generate list elements in correct order
[helm.git] / helm / ocaml / cic_notation / cicNotationRew.ml
1 (* Copyright (C) 2004-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 open Printf
27
28 type pattern_id = int
29 type interpretation_id = pattern_id
30 type pretty_printer_id = pattern_id
31
32 type term_info =
33   { sort: (Cic.id, CicNotationPt.sort_kind) Hashtbl.t;
34     uri: (Cic.id, string) Hashtbl.t;
35   }
36
37 let warning s = prerr_endline ("CicNotation WARNING: " ^ s)
38
39 let get_types uri =
40   let o,_ = CicEnvironment.get_obj CicUniv.empty_ugraph uri in
41     match o with
42       | Cic.InductiveDefinition (l,_,_,_) -> l 
43       | _ -> assert false
44
45 let name_of_inductive_type uri i = 
46   let types = get_types uri in
47   let (name, _, _, _) = try List.nth types i with Not_found -> assert false in
48   name
49
50   (* returns <name, type> pairs *)
51 let constructors_of_inductive_type uri i =
52   let types = get_types uri in
53   let (_, _, _, constructors) = 
54     try List.nth types i with Not_found -> assert false
55   in
56   constructors
57
58   (* returns name only *)
59 let constructor_of_inductive_type uri i j =
60   (try
61     fst (List.nth (constructors_of_inductive_type uri i) (j-1))
62   with Not_found -> assert false)
63
64 module Ast = CicNotationPt
65
66 let string_of_name = function
67   | Cic.Name s -> s
68   | Cic.Anonymous -> "_"
69
70 let ident_of_name n = Ast.Ident (string_of_name n, None)
71
72 let idref id t = Ast.AttributedTerm (`IdRef id, t)
73
74 let pp_ast0 t k =
75   prerr_endline "pp_ast0";
76   let rec aux t = CicNotationUtil.visit_ast ~special_k k t
77   and special_k = function
78     | Ast.AttributedTerm (attrs, t) -> Ast.AttributedTerm (attrs, aux t)
79     | _ -> assert false
80   in
81   aux t
82
83 let ast_of_acic0 term_info acic k =
84 (*   prerr_endline "ast_of_acic0"; *)
85   let k = k term_info in
86   let register_uri id uri = Hashtbl.add term_info.uri id uri in
87   let sort_of_id id =
88     try
89       Hashtbl.find term_info.sort id
90     with Not_found -> assert false
91   in
92   let aux_substs substs =
93     Some
94       (List.map
95         (fun (uri, annterm) -> (UriManager.name_of_uri uri, k annterm))
96         substs)
97   in
98   let aux_context context =
99     List.map
100       (function
101         | None -> None
102         | Some annterm -> Some (k annterm))
103       context
104   in
105   let aux = function
106     | Cic.ARel (id,_,_,b) -> idref id (Ast.Ident (b, None))
107     | Cic.AVar (id,uri,substs) ->
108         register_uri id (UriManager.string_of_uri uri);
109         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
110     | Cic.AMeta (id,n,l) -> idref id (Ast.Meta (n, aux_context l))
111     | Cic.ASort (id,Cic.Prop) -> idref id (Ast.Sort `Prop)
112     | Cic.ASort (id,Cic.Set) -> idref id (Ast.Sort `Set)
113     | Cic.ASort (id,Cic.Type _) -> idref id (Ast.Sort `Type)
114     | Cic.ASort (id,Cic.CProp) -> idref id (Ast.Sort `CProp)
115     | Cic.AImplicit _ -> assert false
116     | Cic.AProd (id,n,s,t) ->
117         let binder_kind =
118           match sort_of_id id with
119           | `Set | `Type -> `Pi
120           | `Prop | `CProp -> `Forall
121         in
122         idref id (Ast.Binder (binder_kind, (ident_of_name n, Some (k s)), k t))
123     | Cic.ACast (id,v,t) ->
124         idref id (Ast.Appl [idref id (Ast.Symbol ("cast", 0)); k v; k t])
125     | Cic.ALambda (id,n,s,t) ->
126         idref id (Ast.Binder (`Lambda, (ident_of_name n, Some (k s)), k t))
127     | Cic.ALetIn (id,n,s,t) ->
128         idref id (Ast.LetIn ((ident_of_name n, None), k s, k t))
129     | Cic.AAppl (aid,args) -> idref aid (Ast.Appl (List.map k args))
130     | Cic.AConst (id,uri,substs) ->
131         register_uri id (UriManager.string_of_uri uri);
132         idref id (Ast.Ident (UriManager.name_of_uri uri, aux_substs substs))
133     | Cic.AMutInd (id,uri,i,substs) as t ->
134         let name = name_of_inductive_type uri i in
135         let uri_str = UriManager.string_of_uri uri in
136         let puri_str =
137           uri_str ^ "#xpointer(1/" ^ (string_of_int (i + 1)) ^ ")"
138         in
139         register_uri id puri_str;
140         idref id (Ast.Ident (name, aux_substs substs))
141     | Cic.AMutConstruct (id,uri,i,j,substs) ->
142         let name = constructor_of_inductive_type uri i j in
143         let uri_str = UriManager.string_of_uri uri in
144         let puri_str = sprintf "%s#xpointer(1/%d/%d)" uri_str (i + 1) j in
145         register_uri id puri_str;
146         idref id (Ast.Ident (name, aux_substs substs))
147     | Cic.AMutCase (id,uri,typeno,ty,te,patterns) ->
148         let name = name_of_inductive_type uri typeno in
149         let constructors = constructors_of_inductive_type uri typeno in
150         let rec eat_branch ty pat =
151           match (ty, pat) with
152           | Cic.Prod (_, _, t), Cic.ALambda (_, name, s, t') ->
153               let (cv, rhs) = eat_branch t t' in
154               (ident_of_name name, Some (k s)) :: cv, rhs
155           | _, _ -> [], k pat
156         in
157         let patterns =
158           List.map2
159             (fun (name, ty) pat ->
160               let (capture_variables, rhs) = eat_branch ty pat in
161               ((name, capture_variables), rhs))
162             constructors patterns
163         in
164         idref id (Ast.Case (k te, Some name, Some (k ty), patterns))
165     | Cic.AFix (id, no, funs) -> 
166         let defs = 
167           List.map
168             (fun (_, n, decr_idx, ty, bo) ->
169               ((Ast.Ident (n, None), Some (k ty)), k bo, decr_idx))
170             funs
171         in
172         let name =
173           try
174             (match List.nth defs no with
175             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
176             | _ -> assert false)
177           with Not_found -> assert false
178         in
179         idref id (Ast.LetRec (`Inductive, defs, Ast.Ident (name, None)))
180     | Cic.ACoFix (id, no, funs) -> 
181         let defs = 
182           List.map
183             (fun (_, n, ty, bo) -> ((Ast.Ident (n, None), Some (k ty)), k bo, 0))
184             funs
185         in
186         let name =
187           try
188             (match List.nth defs no with
189             | (Ast.Ident (n, _), _), _, _ when n <> "_" -> n
190             | _ -> assert false)
191           with Not_found -> assert false
192         in
193         idref id (Ast.LetRec (`CoInductive, defs, Ast.Ident (name, None)))
194   in
195   aux acic
196
197   (* persistent state *)
198
199 let level1_patterns21 = Hashtbl.create 211
200 let level2_patterns32 = Hashtbl.create 211
201
202 let (compiled21: (CicNotationPt.term -> (CicNotationEnv.t * int) option)
203 option ref) =
204   ref None
205 let (compiled32: (Cic.annterm -> ((string * Cic.annterm) list * int) option)
206 option ref) =
207   ref None
208
209 let pattern21_matrix = ref []
210 let pattern32_matrix = ref []
211
212 let get_compiled21 () =
213   match !compiled21 with
214   | None -> assert false
215   | Some f -> f
216 let get_compiled32 () =
217   match !compiled32 with
218   | None -> assert false
219   | Some f -> f
220
221 let set_compiled21 f = compiled21 := Some f
222 let set_compiled32 f = compiled32 := Some f
223
224 let instantiate21 env precedence associativity l1 =
225   prerr_endline "instantiate21";
226   let boxify = function
227     | [t] -> t
228     | tl -> Ast.Layout (Ast.Box (Ast.H, tl))
229   in
230   let rec subst_singleton env t =
231     boxify (subst env t)
232   and subst env = function
233     | Ast.AttributedTerm (_, t) -> subst env t
234     | Ast.Variable var ->
235         let name, expected_ty = CicNotationEnv.declaration_of_var var in
236         let ty, value =
237           try
238             List.assoc name env
239           with Not_found -> assert false
240         in
241         assert (CicNotationEnv.well_typed ty value); (* INVARIANT *)
242         (* following assertion should be a conditional that makes this
243          * instantiation fail *)
244         assert (CicNotationEnv.well_typed expected_ty value);
245         [ CicNotationEnv.term_of_value value ]
246     | Ast.Magic m -> subst_magic env m
247     | Ast.Literal _ as t -> [ t ]
248     | Ast.Layout l -> [ Ast.Layout (subst_layout env l) ]
249     | t -> [ CicNotationUtil.visit_ast (subst_singleton env) t ]
250   and subst_magic env = function
251     | Ast.List0 (p, sep_opt)
252     | Ast.List1 (p, sep_opt) ->
253         let rec_decls = CicNotationEnv.declarations_of_term p in
254         let rec_values =
255           List.map (fun (n, _) -> CicNotationEnv.lookup_list env n) rec_decls
256         in
257         let values = CicNotationUtil.ncombine rec_values in
258         let sep =
259           match sep_opt with
260           | None -> []
261           | Some l -> [ CicNotationPt.Literal l ]
262         in
263         let rec instantiate_list acc = function
264           | [] -> List.rev acc
265           | value_set :: [] ->
266               let env = CicNotationEnv.combine rec_decls value_set in
267                 instantiate_list ((boxify (subst env p)) :: acc) []
268           | value_set :: tl ->
269               let env = CicNotationEnv.combine rec_decls value_set in
270               instantiate_list ((boxify (subst env p @ sep)) :: acc) tl
271         in
272         instantiate_list [] (List.rev values)
273     | Ast.Opt p ->
274         let opt_decls = CicNotationEnv.declarations_of_term p in
275         let env =
276           let rec build_env = function
277             | [] -> []
278             | (name, ty) :: tl ->
279                   (* assumption: if one of the value is None then all are *)
280                 (match CicNotationEnv.lookup_opt env name with
281                 | None -> raise Exit
282                 | Some v -> (name, (ty, v)) :: build_env tl)
283           in
284           try build_env opt_decls with Exit -> []
285         in
286           begin
287             match env with
288               | [] -> []
289               | _ -> subst env p
290           end
291     | _ -> assert false (* impossible *)
292   and subst_layout env = function
293     | Ast.Box (kind, tl) -> Ast.Box (kind, List.concat (List.map (subst env) tl))
294     | l -> CicNotationUtil.visit_layout (subst_singleton env) l
295   in
296     subst_singleton env l1
297
298 let rec pp_ast1 term = 
299   let rec pp_value = function
300     | CicNotationEnv.NumValue _ as v -> v
301     | CicNotationEnv.StringValue _ as v -> v
302     | CicNotationEnv.TermValue t -> CicNotationEnv.TermValue (pp_ast1 t)
303     | CicNotationEnv.OptValue None as v -> v
304     | CicNotationEnv.OptValue (Some v) -> 
305         CicNotationEnv.OptValue (Some (pp_value v))
306     | CicNotationEnv.ListValue vl ->
307         CicNotationEnv.ListValue (List.map pp_value vl)
308   in
309   let ast_env_of_env env =
310     List.map (fun (var, (ty, value)) -> (var, (ty, pp_value value))) env
311   in
312   match (get_compiled21 ()) term with
313   | None -> pp_ast0 term pp_ast1
314   | Some (env, pid) ->
315       let precedence, associativity, l1 =
316         try
317           Hashtbl.find level1_patterns21 pid
318         with Not_found -> assert false
319       in
320       instantiate21 (ast_env_of_env env) precedence associativity l1
321
322 let instantiate32 term_info env symbol args =
323   let rec instantiate_arg = function
324     | Ast.IdentArg (n, name) ->
325         let t = (try List.assoc name env with Not_found -> assert false) in
326         let rec count_lambda = function
327           | Ast.Binder (`Lambda, _, body) -> 1 + count_lambda body
328           | _ -> 0
329         in
330         let rec add_lambda t n =
331           if n > 0 then
332             let name = CicNotationUtil.fresh_name () in
333             Ast.Binder (`Lambda, (Ast.Ident (name, None), None),
334               Ast.Appl [add_lambda t (n - 1); Ast.Ident (name, None)])
335           else
336             t
337         in
338         add_lambda t (n - count_lambda t)
339   in
340   let args' = List.map instantiate_arg args in
341   Ast.Appl (Ast.Symbol (symbol, 0) :: args')
342
343 let rec ast_of_acic1 term_info annterm = 
344   match (get_compiled32 ()) annterm with
345   | None -> ast_of_acic0 term_info annterm ast_of_acic1
346   | Some (env, pid) -> 
347       let env' =
348         List.map (fun (name, term) -> (name, ast_of_acic1 term_info term)) env
349       in
350       let symbol, args =
351         try
352           Hashtbl.find level2_patterns32 pid
353         with Not_found -> assert false
354       in
355       instantiate32 term_info env' symbol args
356
357 let load_patterns32 t =
358   set_compiled32 (CicNotationMatcher.Matcher32.compiler t)
359
360 let load_patterns21 t =
361   set_compiled21 (CicNotationMatcher.Matcher21.compiler t)
362
363 let ast_of_acic id_to_sort annterm =
364   let term_info = { sort = id_to_sort; uri = Hashtbl.create 211 } in
365   let ast = ast_of_acic1 term_info annterm in
366   ast, term_info.uri
367
368 let pp_ast term = pp_ast1 term
369
370 let fresh_id =
371   let counter = ref ~-1 in
372   fun () ->
373     incr counter;
374     !counter
375
376 let add_interpretation (symbol, args) appl_pattern =
377   let id = fresh_id () in
378   Hashtbl.add level2_patterns32 id (symbol, args);
379   pattern32_matrix := (appl_pattern, id) :: !pattern32_matrix;
380   load_patterns32 !pattern32_matrix;
381   id
382
383 let add_pretty_printer ?precedence ?associativity l2 l1 =
384   let id = fresh_id () in
385   let l2' = CicNotationUtil.strip_attributes l2 in
386   Hashtbl.add level1_patterns21 id (precedence, associativity, l1);
387   pattern21_matrix := (l2', id) :: !pattern21_matrix;
388   load_patterns21 !pattern21_matrix;
389   id
390
391 exception Interpretation_not_found
392 exception Pretty_printer_not_found
393
394 let remove_interpretation id =
395   (try
396     Hashtbl.remove level2_patterns32 id;
397   with Not_found -> raise Interpretation_not_found);
398   pattern32_matrix := List.filter (fun (_, id') -> id <> id') !pattern32_matrix;
399   load_patterns32 !pattern32_matrix
400
401 let remove_pretty_printer id =
402   (try
403     Hashtbl.remove level1_patterns21 id;
404   with Not_found -> raise Pretty_printer_not_found);
405   pattern21_matrix := List.filter (fun (_, id') -> id <> id') !pattern21_matrix;
406   load_patterns21 !pattern21_matrix
407
408 let _ =
409   load_patterns21 [];
410   load_patterns32 []
411