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