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