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