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