]> matita.cs.unibo.it Git - helm.git/blob - matita/components/content_pres/cicNotationParser.ml
1f83a64d57d9b6ff0bc3e09f46d4156d4f0e4c3d
[helm.git] / matita / components / content_pres / cicNotationParser.ml
1 (* Copyright (C) 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 (* $Id$ *)
27
28 open Printf
29
30 module Ast = NotationPt
31 module Env = NotationEnv
32
33 exception Parse_error of string
34 exception Level_not_found of int
35
36 let min_precedence = 0
37 let max_precedence = 100
38
39 type ('a,'b,'c,'d) grammars = {
40   level1_pattern: 'a Grammar.Entry.e;
41   level2_ast: 'b Grammar.Entry.e;
42   level2_ast_grammar : Grammar.g;
43   term: 'b Grammar.Entry.e;
44   let_defs: 'c Grammar.Entry.e;
45   protected_binder_vars: 'd Grammar.Entry.e;
46   level2_meta: 'b Grammar.Entry.e;
47 }
48
49 type checked_l1_pattern = CL1P of NotationPt.term * int
50
51 let refresh_uri_in_checked_l1_pattern (CL1P (t,n)) =
52  CL1P (NotationUtil.refresh_uri_in_term t, n)
53
54 type binding =
55   | NoBinding
56   | Binding of string * Env.value_type
57   | Env of (string * Env.value_type) list
58
59 type db = {
60   grammars: 
61     (int -> NotationPt.term, 
62     Ast.term,
63     (Ast.term Ast.capture_variable list *
64       Ast.term Ast.capture_variable * Ast.term * int) list, 
65     Ast.term list * Ast.term option) grammars;
66   keywords: string list;
67   items: (string * Ast.term * (NotationEnv.t -> Ast.location -> Ast.term)) list
68 }
69
70 let int_of_string s =
71   try
72     Pervasives.int_of_string s
73   with Failure _ ->
74     failwith (sprintf "Lexer failure: string_of_int \"%s\" failed" s)
75
76 (** {2 Grammar extension} *)
77
78 let level_of precedence =
79   if precedence < min_precedence || precedence > max_precedence then
80     raise (Level_not_found precedence);
81   string_of_int precedence 
82
83 let gram_symbol s = Gramext.Stoken ("SYMBOL", s)
84 let gram_ident s = Gramext.Stoken ("IDENT", s)
85 let gram_number s = Gramext.Stoken ("NUMBER", s)
86 let gram_keyword s = Gramext.Stoken ("", s)
87 let gram_term status = function
88   | Ast.Self _ -> Gramext.Sself
89   | Ast.Level precedence ->
90       Gramext.Snterml 
91         (Grammar.Entry.obj 
92           (status#notation_parser_db.grammars.term : 'a Grammar.Entry.e), 
93          level_of precedence)
94 ;;
95
96 let gram_of_literal =
97   function
98   | `Symbol s -> gram_symbol s
99   | `Keyword s -> gram_keyword s
100   | `Number s -> gram_number s
101
102 let make_action action bindings =
103   let rec aux (vl : NotationEnv.t) =
104     function
105       [] -> Gramext.action (fun (loc: Ast.location) -> action vl loc)
106     | NoBinding :: tl -> Gramext.action (fun _ -> aux vl tl)
107     (* LUCA: DEFCON 3 BEGIN *)
108     | Binding (name, Env.TermType l) :: tl ->
109         Gramext.action
110           (fun (v:Ast.term) ->
111             aux ((name, (Env.TermType l, Env.TermValue v))::vl) tl)
112     | Binding (name, Env.StringType) :: tl ->
113         Gramext.action
114           (fun (v:string) ->
115             aux ((name, (Env.StringType, Env.StringValue v)) :: vl) tl)
116     | Binding (name, Env.NumType) :: tl ->
117         Gramext.action
118           (fun (v:string) ->
119             aux ((name, (Env.NumType, Env.NumValue v)) :: vl) tl)
120     | Binding (name, Env.OptType t) :: tl ->
121         Gramext.action
122           (fun (v:'a option) ->
123             aux ((name, (Env.OptType t, Env.OptValue v)) :: vl) tl)
124     | Binding (name, Env.ListType t) :: tl ->
125         Gramext.action
126           (fun (v:'a list) ->
127             aux ((name, (Env.ListType t, Env.ListValue v)) :: vl) tl)
128     | Env _ :: tl ->
129         Gramext.action (fun (v:NotationEnv.t) -> aux (v @ vl) tl)
130     (* LUCA: DEFCON 3 END *)
131   in
132     aux [] (List.rev bindings)
133
134 let flatten_opt =
135   let rec aux acc =
136     function
137       [] -> List.rev acc
138     | NoBinding :: tl -> aux acc tl
139     | Env names :: tl -> aux (List.rev names @ acc) tl
140     | Binding (name, ty) :: tl -> aux ((name, ty) :: acc) tl
141   in
142   aux []
143
144   (* given a level 1 pattern computes the new RHS of "term" grammar entry *)
145 let extract_term_production status pattern =
146   let rec aux = function
147     | Ast.AttributedTerm (_, t) -> aux t
148     | Ast.Literal l -> aux_literal l
149     | Ast.Layout l -> aux_layout l
150     | Ast.Magic m -> aux_magic m
151     | Ast.Variable v -> aux_variable v
152     | t ->
153         prerr_endline (NotationPp.pp_term t);
154         assert false
155   and aux_literal =
156     function
157     | `Symbol s -> [NoBinding, gram_symbol s]
158     | `Keyword s ->
159         (* assumption: s will be registered as a keyword with the lexer *)
160         [NoBinding, gram_keyword s]
161     | `Number s -> [NoBinding, gram_number s]
162   and aux_layout = function
163     | Ast.Sub (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\sub "] @ aux p2
164     | Ast.Sup (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\sup "] @ aux p2
165     | Ast.Below (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\below "] @ aux p2
166     | Ast.Above (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\above "] @ aux p2
167     | Ast.Frac (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\frac "] @ aux p2
168     | Ast.InfRule (p1, p2, p3) -> [NoBinding, gram_symbol "\\infrule "] @ aux p1 @ aux p2 @ aux p3
169     | Ast.Atop (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\atop "] @ aux p2
170     | Ast.Over (p1, p2) -> aux p1 @ [NoBinding, gram_symbol "\\over "] @ aux p2
171     | Ast.Root (p1, p2) ->
172         [NoBinding, gram_symbol "\\root "] @ aux p2
173         @ [NoBinding, gram_symbol "\\of "] @ aux p1
174     | Ast.Sqrt p -> [NoBinding, gram_symbol "\\sqrt "] @ aux p
175     | Ast.Break -> []
176     | Ast.Box (_, pl) -> List.flatten (List.map aux pl)
177     | Ast.Group pl -> List.flatten (List.map aux pl)
178     | Ast.Mstyle (_,pl) -> List.flatten (List.map aux pl)
179     | Ast.Mpadded (_,pl) -> List.flatten (List.map aux pl)
180     | Ast.Maction l -> List.flatten (List.map aux l)
181   and aux_magic magic =
182     match magic with
183     | Ast.Opt p ->
184         let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
185         let action (env_opt : NotationEnv.t option) (loc : Ast.location) =
186           match env_opt with
187           | Some env -> List.map Env.opt_binding_some env
188           | None -> List.map Env.opt_binding_of_name p_names
189         in
190         [ Env (List.map Env.opt_declaration p_names),
191           Gramext.srules
192             [ [ Gramext.Sopt (Gramext.srules [ p_atoms, p_action ]) ],
193               Gramext.action action ] ]
194     | Ast.List0 (p, _)
195     | Ast.List1 (p, _) ->
196         let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
197         let action (env_list : NotationEnv.t list) (loc : Ast.location) =
198           NotationEnv.coalesce_env p_names env_list
199         in
200         let gram_of_list s =
201           match magic with
202           | Ast.List0 (_, None) -> Gramext.Slist0 s
203           | Ast.List1 (_, None) -> Gramext.Slist1 s
204           | Ast.List0 (_, Some l) -> Gramext.Slist0sep (s, gram_of_literal l)
205           | Ast.List1 (_, Some l) -> Gramext.Slist1sep (s, gram_of_literal l)
206           | _ -> assert false
207         in
208         [ Env (List.map Env.list_declaration p_names),
209           Gramext.srules
210             [ [ gram_of_list (Gramext.srules [ p_atoms, p_action ]) ],
211               Gramext.action action ] ]
212     | _ -> assert false
213   and aux_variable =
214     function
215     | Ast.NumVar s -> [Binding (s, Env.NumType), gram_number ""]
216     | Ast.TermVar (s,(Ast.Self level|Ast.Level level as lv)) -> 
217         [Binding (s, Env.TermType level), gram_term status lv]
218     | Ast.IdentVar s -> [Binding (s, Env.StringType), gram_ident ""]
219     | Ast.Ascription (p, s) -> assert false (* TODO *)
220     | Ast.FreshVar _ -> assert false
221   and inner_pattern p =
222     let p_bindings, p_atoms = List.split (aux p) in
223     let p_names = flatten_opt p_bindings in
224     let action =
225       make_action (fun (env : NotationEnv.t) (loc : Ast.location) -> env)
226         p_bindings
227     in
228     p_bindings, p_atoms, p_names, action
229   in
230   aux pattern
231
232 type rule_id = Grammar.token Gramext.g_symbol list
233
234 let compare_rule_id x y =
235   let rec aux = function
236     | [],[] -> 0
237     | [],_ -> ~-1
238     | _,[] -> 1
239     | ((s1::tl1) as x),((s2::tl2) as y) ->
240         if Gramext.eq_symbol s1 s2 then aux (tl1,tl2)
241         else Pervasives.compare x y 
242   in
243     aux (x,y)
244
245
246 let check_l1_pattern level1_pattern pponly level associativity =
247   let variables = ref 0 in
248   let symbols = ref 0 in
249   let rec aux = function
250     | Ast.AttributedTerm (att, t) -> Ast.AttributedTerm (att,aux t)
251     | Ast.Literal _ as l -> incr symbols; l
252     | Ast.Layout l -> Ast.Layout (aux_layout l)
253     | Ast.Magic m -> Ast.Magic (aux_magic m)
254     | Ast.Variable v -> (aux_variable v)
255     | t -> assert false
256   and aux_layout = function
257     | Ast.Sub (p1, p2)   -> let p1 = aux p1 in let p2 = aux p2 in Ast.Sub (p1, p2)
258     | Ast.Sup (p1, p2)   -> let p1 = aux p1 in let p2 = aux p2 in Ast.Sup (p1, p2)
259     | Ast.Below (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Below (p1, p2)
260     | Ast.Above (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Above (p1, p2)
261     | Ast.Frac (p1, p2)  -> let p1 = aux p1 in let p2 = aux p2 in Ast.Frac (p1, p2)
262     | Ast.InfRule (p1, p2, p3)  -> let p1 = aux p1 in let p2 = aux p2 in let p3 = aux p3 in Ast.InfRule (p1, p2, p3)
263     | Ast.Atop (p1, p2)  -> let p1 = aux p1 in let p2 = aux p2 in Ast.Atop (p1, p2)
264     | Ast.Over (p1, p2)  -> let p1 = aux p1 in let p2 = aux p2 in Ast.Over (p1, p2)
265     | Ast.Root (p1, p2)  -> let p1 = aux p1 in let p2 = aux p2 in Ast.Root (p1, p2)
266     | Ast.Sqrt p -> Ast.Sqrt (aux p)
267     | Ast.Break as t -> t 
268     | Ast.Box (b, pl) -> Ast.Box(b, List.map aux pl)
269     | Ast.Group pl -> Ast.Group (List.map aux pl)
270     | Ast.Mstyle (l,pl) -> Ast.Mstyle (l, List.map aux pl)
271     | Ast.Mpadded (l,pl) -> Ast.Mpadded (l, List.map aux pl)
272     | Ast.Maction l as t -> 
273         if not pponly then 
274         raise(Parse_error("Maction can be used only in output notations")) 
275         else t
276   and aux_magic magic =
277     match magic with
278     | Ast.Opt p -> Ast.Opt (aux p)
279     | Ast.List0 (p, x) -> Ast.List0 (aux p, x)
280     | Ast.List1 (p, x) -> Ast.List1 (aux p, x)
281     | _ -> assert false
282   and aux_variable =
283     function
284     | Ast.NumVar _ as t -> Ast.Variable t
285     | Ast.TermVar (s,Ast.Self _) when associativity <> Gramext.NonA -> 
286         incr variables; 
287         if !variables > 2 then
288           raise (Parse_error ("Exactly 2 variables must be specified in an "^
289           "associative notation"));
290         (match !variables, associativity with
291         | 1,Gramext.LeftA -> 
292              Ast.Variable (Ast.TermVar (s, Ast.Self level))
293         | 1,Gramext.RightA -> 
294              Ast.Variable (Ast.TermVar (s, Ast.Self (level+1)))
295         | 2,Gramext.LeftA ->
296              Ast.Variable (Ast.TermVar (s, Ast.Self (level+1)))
297         | 2,Gramext.RightA -> 
298              Ast.Variable (Ast.TermVar (s, Ast.Level (level-1)))
299         | _ -> assert false)
300     | Ast.TermVar (s,Ast.Level _) when associativity <> Gramext.NonA -> 
301           raise (Parse_error ("Variables can not be declared with a " ^ 
302             "precedence in an associative notation"))
303        (*avoid camlp5 divergence due to non-Sself recursion at the same level *)
304     | Ast.TermVar (s,Ast.Level l) when l<=level && !variables=0 && !symbols=0-> 
305        raise(Parse_error("Left recursive rule with precedence not greater " ^
306         "than " ^ string_of_int level ^ " is not allowed to avoid divergence"))
307     | Ast.TermVar _ as t -> incr variables; Ast.Variable t
308     | Ast.IdentVar _ as t -> Ast.Variable t
309     | Ast.Ascription _ -> assert false (* TODO *)
310     | Ast.FreshVar _ -> assert false
311   in
312   if associativity <> Gramext.NonA && level = min_precedence then
313     raise (Parse_error ("You can not specify an associative notation " ^
314     "at level "^string_of_int min_precedence ^ "; increase it"));
315   let cp = aux level1_pattern in
316 (*   prerr_endline ("checked_pattern: " ^ NotationPp.pp_term cp); *)
317   if !variables <> 2 && associativity <> Gramext.NonA then
318     raise (Parse_error ("Exactly 2 variables must be specified in an "^
319      "associative notation"));
320   CL1P (cp,level)
321 ;;
322
323 (** {2 Grammar} *)
324
325 let fold_cluster binder terms ty body =
326   List.fold_right
327     (fun term body -> Ast.Binder (binder, (term, ty), body))
328     terms body  (* terms are names: either Ident or FreshVar *)
329
330 let fold_exists terms ty body =
331   List.fold_right
332     (fun term body ->
333       let lambda = Ast.Binder (`Lambda, (term, ty), body) in
334       Ast.Appl [ Ast.Symbol ("exists", 0); lambda ])
335     terms body
336
337 let fold_binder binder pt_names body =
338   List.fold_right
339     (fun (names, ty) body -> fold_cluster binder names ty body)
340     pt_names body
341
342 let return_term loc term = Ast.AttributedTerm (`Loc loc, term)
343 let return_term_of_level loc term l = 
344   Ast.AttributedTerm (`Loc loc, term l)
345
346 (** {2 API implementation} *)
347
348 let exc_located_wrapper f =
349   try
350     f ()
351   with
352   | Stdpp.Exc_located (floc, Stream.Error msg) ->
353       raise (HExtlib.Localized (floc, Parse_error msg))
354   | Stdpp.Exc_located (floc, HExtlib.Localized (_,exn)) ->
355       raise (HExtlib.Localized (floc, (Parse_error (Printexc.to_string exn))))
356   | Stdpp.Exc_located (floc, exn) ->
357       raise (HExtlib.Localized (floc, (Parse_error (Printexc.to_string exn))))
358
359 let parse_level1_pattern grammars precedence lexbuf =
360   exc_located_wrapper
361     (fun () -> Grammar.Entry.parse grammars.level1_pattern (Obj.magic lexbuf) precedence)
362
363 let parse_level2_ast grammars lexbuf =
364   exc_located_wrapper
365     (fun () -> Grammar.Entry.parse grammars.level2_ast (Obj.magic lexbuf))
366
367 let parse_level2_meta grammars lexbuf =
368   exc_located_wrapper
369     (fun () -> Grammar.Entry.parse grammars.level2_meta (Obj.magic lexbuf))
370
371 let parse_term grammars lexbuf =
372   exc_located_wrapper
373     (fun () -> (Grammar.Entry.parse grammars.term (Obj.magic lexbuf)))
374
375   (* create empty precedence level for "term" *)
376 let initialize_grammars grammars =
377   let dummy_action =
378     Gramext.action (fun _ ->
379       failwith "internal error, lexer generated a dummy token")
380   in
381   (* Needed since campl4 on "delete_rule" remove the precedence level if it gets
382    * empty after the deletion. The lexer never generate the Stoken below. *)
383   let dummy_prod = [ [ Gramext.Stoken ("DUMMY", "") ], dummy_action ] in
384   let mk_level_list first last =
385     let rec aux acc = function
386       | i when i < first -> acc
387       | i ->
388           aux
389             ((Some (level_of i), Some Gramext.NonA, dummy_prod)
390              :: acc)
391             (i - 1)
392     in
393     aux [] last
394   in
395   Grammar.extend
396     [ Grammar.Entry.obj (grammars.term: 'a Grammar.Entry.e),
397       None,
398       mk_level_list min_precedence max_precedence ];
399 (* {{{ Grammar for concrete syntax patterns, notation level 1 *)
400   begin
401   let level1_pattern = grammars.level1_pattern in
402 EXTEND
403   GLOBAL: level1_pattern;
404
405   level1_pattern: [ 
406     [ p = l1_pattern; EOI -> fun l -> NotationUtil.boxify (p l) ] 
407   ];
408   l1_pattern: [ 
409     [ p = LIST1 l1_simple_pattern -> 
410         fun l -> List.map (fun x -> x l) p ] 
411   ];
412   literal: [
413     [ s = SYMBOL -> `Symbol s
414     | k = QKEYWORD -> `Keyword k
415     | n = NUMBER -> `Number n
416     ]
417   ];
418   sep:       [ [ "sep";      sep = literal -> sep ] ];
419   l1_magic_pattern: [
420     [ "list0"; p = l1_simple_pattern; sep = OPT sep -> 
421             fun l -> Ast.List0 (p l, sep)
422     | "list1"; p = l1_simple_pattern; sep = OPT sep -> 
423             fun l -> Ast.List1 (p l, sep)
424     | "opt";   p = l1_simple_pattern -> fun l -> Ast.Opt (p l)
425     ]
426   ];
427   l1_pattern_variable: [
428     [ "term"; precedence = NUMBER; id = IDENT -> 
429         Ast.TermVar (id, Ast.Level (int_of_string precedence))
430     | "number"; id = IDENT -> Ast.NumVar id
431     | "ident"; id = IDENT -> Ast.IdentVar id
432     ]
433   ];
434   mstyle: [ 
435     [ id = IDENT; 
436       v = [ IDENT | NUMBER | COLOR | FLOATWITHUNIT ] -> id, v]];
437   mpadded: [ 
438     [ id = IDENT; 
439       v = [ PERCENTAGE ] -> id, v]];
440   l1_simple_pattern:
441     [ "layout" LEFTA
442       [ p1 = SELF; SYMBOL "\\sub "; p2 = SELF ->
443           return_term_of_level loc 
444             (fun l -> Ast.Layout (Ast.Sub (p1 l, p2 l)))
445       | p1 = SELF; SYMBOL "\\sup "; p2 = SELF ->
446           return_term_of_level loc 
447             (fun l -> Ast.Layout (Ast.Sup (p1 l, p2 l)))
448       | p1 = SELF; SYMBOL "\\below "; p2 = SELF ->
449           return_term_of_level loc 
450             (fun l -> Ast.Layout (Ast.Below (p1 l, p2 l)))
451       | p1 = SELF; SYMBOL "\\above "; p2 = SELF ->
452           return_term_of_level loc 
453             (fun l -> Ast.Layout (Ast.Above (p1 l, p2 l)))
454       | p1 = SELF; SYMBOL "\\over "; p2 = SELF ->
455           return_term_of_level loc 
456             (fun l -> Ast.Layout (Ast.Over (p1 l, p2 l)))
457       | p1 = SELF; SYMBOL "\\atop "; p2 = SELF ->
458           return_term_of_level loc 
459             (fun l -> Ast.Layout (Ast.Atop (p1 l, p2 l)))
460       | p1 = SELF; SYMBOL "\\frac "; p2 = SELF ->
461           return_term_of_level loc 
462             (fun l -> Ast.Layout (Ast.Frac (p1 l, p2 l)))
463       | SYMBOL "\\infrule "; p1 = SELF; p2 = SELF; p3 = SELF ->
464           return_term_of_level loc 
465             (fun l -> Ast.Layout (Ast.InfRule (p1 l, p2 l, p3 l)))
466       | SYMBOL "\\sqrt "; p = SELF -> 
467           return_term_of_level loc (fun l -> Ast.Layout (Ast.Sqrt p l))
468       | SYMBOL "\\root "; index = SELF; SYMBOL "\\of "; arg = SELF ->
469           return_term_of_level loc 
470             (fun l -> Ast.Layout (Ast.Root (arg l, index l)))
471       | "hbox"; LPAREN; p = l1_pattern; RPAREN ->
472           return_term_of_level loc 
473             (fun l -> Ast.Layout (Ast.Box ((Ast.H, false, false), p l)))
474       | "vbox"; LPAREN; p = l1_pattern; RPAREN ->
475           return_term_of_level loc 
476             (fun l -> Ast.Layout (Ast.Box ((Ast.V, false, false), p l)))
477       | "hvbox"; LPAREN; p = l1_pattern; RPAREN ->
478           return_term_of_level loc 
479             (fun l -> Ast.Layout (Ast.Box ((Ast.HV, false, false), p l)))
480       | "hovbox"; LPAREN; p = l1_pattern; RPAREN ->
481           return_term_of_level loc 
482             (fun l -> Ast.Layout (Ast.Box ((Ast.HOV, false, false), p l)))
483       | "break" -> return_term_of_level loc (fun _ -> Ast.Layout Ast.Break)
484       | "mstyle"; m = LIST1 mstyle ; LPAREN; t = l1_pattern; RPAREN ->
485           return_term_of_level loc 
486             (fun l -> 
487                Ast.Layout (Ast.Mstyle (m, t l)))
488       | "mpadded"; m = LIST1 mpadded ; LPAREN; t = l1_pattern; RPAREN ->
489           return_term_of_level loc 
490             (fun l -> 
491                Ast.Layout (Ast.Mpadded (m, t l)))
492       | "maction"; m = LIST1 [ LPAREN; l = l1_pattern; RPAREN -> l ] ->
493            return_term_of_level loc 
494             (fun l -> Ast.Layout (Ast.Maction (List.map (fun x ->
495               NotationUtil.group (x l)) m)))
496       | LPAREN; p = l1_pattern; RPAREN ->
497           return_term_of_level loc (fun l -> NotationUtil.group (p l))
498       ]
499     | "simple" NONA
500       [ i = IDENT -> 
501          return_term_of_level loc 
502            (fun l -> Ast.Variable (Ast.TermVar (i,Ast.Self l)))
503       | m = l1_magic_pattern -> 
504              return_term_of_level loc (fun l -> Ast.Magic (m l))
505       | v = l1_pattern_variable -> 
506              return_term_of_level loc (fun _ -> Ast.Variable v)
507       | l = literal -> return_term_of_level loc (fun _ -> Ast.Literal l)
508       ]
509     ];
510   END
511   end;
512 (* }}} *)
513 (* {{{ Grammar for ast magics, notation level 2 *)
514   begin
515   let level2_meta = grammars.level2_meta in
516 EXTEND
517   GLOBAL: level2_meta;
518   l2_variable: [
519     [ "term"; precedence = NUMBER; id = IDENT -> 
520         Ast.TermVar (id,Ast.Level (int_of_string precedence))
521     | "number"; id = IDENT -> Ast.NumVar id
522     | "ident"; id = IDENT -> Ast.IdentVar id
523     | "fresh"; id = IDENT -> Ast.FreshVar id
524     | "anonymous" -> Ast.TermVar ("_",Ast.Self 0) (* is the level relevant?*)
525     | id = IDENT -> Ast.TermVar (id,Ast.Self 0)
526     ]
527   ];
528   l2_magic: [
529     [ "fold"; kind = [ "left" -> `Left | "right" -> `Right ];
530       base = level2_meta; "rec"; id = IDENT; recursive = level2_meta ->
531         Ast.Fold (kind, base, [id], recursive)
532     | "default"; some = level2_meta; none = level2_meta ->
533         Ast.Default (some, none)
534     | "if"; p_test = level2_meta;
535       "then"; p_true = level2_meta;
536       "else"; p_false = level2_meta ->
537         Ast.If (p_test, p_true, p_false)
538     | "fail" -> Ast.Fail
539     ]
540   ];
541   level2_meta: [
542     [ magic = l2_magic -> Ast.Magic magic
543     | var = l2_variable -> Ast.Variable var
544     | blob = UNPARSED_AST ->
545         parse_level2_ast grammars (Ulexing.from_utf8_string blob)
546     ]
547   ];
548 END
549   end;
550 (* }}} *)
551 (* {{{ Grammar for ast patterns, notation level 2 *)
552   begin
553   let level2_ast = grammars.level2_ast in
554   let term = grammars.term in
555   let let_defs = grammars.let_defs in
556   let protected_binder_vars = grammars.protected_binder_vars in
557 EXTEND
558   GLOBAL: level2_ast term let_defs protected_binder_vars;
559   level2_ast: [ [ p = term -> p ] ];
560   sort: [
561     [ "Prop" -> `Prop
562     | "Set" -> `Set
563     | "Type"; SYMBOL "["; n = [ NUMBER| IDENT ]; SYMBOL "]" -> `NType n
564     | "CProp"; SYMBOL "["; n = [ NUMBER| IDENT ]; SYMBOL "]" -> `NCProp n
565     ]
566   ];
567   explicit_subst: [
568     [ SYMBOL "\\subst ";  (* to avoid catching frequent "a [1]" cases *)
569       SYMBOL "[";
570       substs = LIST1 [
571         i = IDENT; SYMBOL <:unicode<Assign>> (* ≔ *); t = term -> (i, t)
572       ] SEP SYMBOL ";";
573       SYMBOL "]" ->
574         substs
575     ]
576   ];
577   meta_subst: [
578     [ s = SYMBOL "_" -> None
579     | p = term -> Some p ]
580   ];
581   meta_substs: [
582     [ SYMBOL "["; substs = LIST0 meta_subst; SYMBOL "]" -> substs ]
583   ];
584   possibly_typed_name: [
585     [ LPAREN; id = single_arg; SYMBOL ":"; typ = term; RPAREN ->
586         id, Some typ
587     | arg = single_arg -> arg, None
588     | id = PIDENT -> Ast.Ident (id, None), None
589     | SYMBOL "_" -> Ast.Ident ("_", None), None
590     | LPAREN; id = PIDENT; SYMBOL ":"; typ = term; RPAREN ->
591         Ast.Ident (id, None), Some typ
592     | LPAREN; SYMBOL "_"; SYMBOL ":"; typ = term; RPAREN ->
593         Ast.Ident ("_", None), Some typ
594     ]
595   ];
596   match_pattern: [
597     [ SYMBOL "_" -> Ast.Wildcard
598     | id = IDENT -> Ast.Pattern (id, None, [])
599     | LPAREN; id = IDENT; vars = LIST1 possibly_typed_name; RPAREN ->
600        Ast.Pattern (id, None, vars)
601     | id = IDENT; vars = LIST1 possibly_typed_name ->
602        Ast.Pattern (id, None, vars)
603     ]
604   ];
605   binder: [
606     [ SYMBOL <:unicode<Pi>>     (* Π *) -> `Pi
607     | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall
608     | SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda
609     ]
610   ];
611   arg: [
612     [ LPAREN; names = LIST1 IDENT SEP SYMBOL ",";
613       SYMBOL ":"; ty = term; RPAREN ->
614         List.map (fun n -> Ast.Ident (n, None)) names, Some ty
615     | name = IDENT -> [Ast.Ident (name, None)], None
616     | blob = UNPARSED_META ->
617         let meta = parse_level2_meta grammars (Ulexing.from_utf8_string blob) in
618         match meta with
619         | Ast.Variable (Ast.FreshVar _) -> [meta], None
620         | Ast.Variable (Ast.TermVar ("_",_)) -> [Ast.Ident ("_", None)], None
621         | _ -> failwith "Invalid bound name."
622    ]
623   ];
624   single_arg: [
625     [ name = IDENT -> Ast.Ident (name, None)
626     | blob = UNPARSED_META ->
627         let meta = parse_level2_meta grammars (Ulexing.from_utf8_string blob) in
628         match meta with
629         | Ast.Variable (Ast.FreshVar _)
630         | Ast.Variable (Ast.IdentVar _) -> meta
631         | Ast.Variable (Ast.TermVar ("_",_)) -> Ast.Ident ("_", None)
632         | _ -> failwith "Invalid index name."
633     ]
634   ];
635   let_defs: [
636     [ defs = LIST1 [
637         name = single_arg;
638         args = LIST1 arg;
639         index_name = OPT [ "on"; id = single_arg -> id ];
640         ty = OPT [ SYMBOL ":" ; p = term -> p ];
641         SYMBOL <:unicode<def>> (* ≝ *); body = term ->
642           let rec position_of name p = function 
643             | [] -> None, p
644             | n :: _ when n = name -> Some p, p
645             | _ :: tl -> position_of name (p + 1) tl
646           in
647           let rec find_arg name n = function 
648             | [] ->
649                 Ast.fail loc (sprintf "Argument %s not found"
650                   (NotationPp.pp_term name))
651             | (l,_) :: tl -> 
652                 (match position_of name 0 l with
653                 | None, len -> find_arg name (n + len) tl
654                 | Some where, len -> n + where)
655           in
656           let index = 
657             match index_name with 
658             | None -> 0 
659             | Some index_name -> find_arg index_name 0 args
660           in
661           let args =
662            List.concat
663             (List.map
664              (function (names,ty) -> List.map (function x -> x,ty) names
665              ) args)
666           in
667            args, (name, ty), body, index
668       ] SEP "and" ->
669         defs
670     ]
671   ];
672   binder_vars: [
673     [ vars = [ l =
674         [ l = LIST1 single_arg SEP SYMBOL "," -> l
675         | l = LIST1 [ PIDENT | SYMBOL "_" ] SEP SYMBOL "," -> 
676             List.map (fun x -> Ast.Ident(x,None)) l
677       ] -> l ];
678       typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
679     ]
680   ];
681   protected_binder_vars: [
682     [ LPAREN; vars = binder_vars; RPAREN -> vars 
683     ]
684   ];
685   maybe_protected_binder_vars: [
686     [ vars = binder_vars -> vars
687     | vars = protected_binder_vars -> vars
688     ]
689   ];
690   term: LEVEL "10"
691   [
692     [ "let"; 
693      var = 
694       [ LPAREN; id = single_arg; SYMBOL ":"; typ = term; RPAREN ->
695           id, Some typ
696       | id = IDENT; ty = OPT [ SYMBOL ":"; typ = term -> typ] ->
697           Ast.Ident(id,None), ty ];
698       SYMBOL <:unicode<def>> (* ≝ *);
699       p1 = term; "in"; p2 = term ->
700         return_term loc (Ast.LetIn (var, p1, p2))
701     | LETCOREC; defs = let_defs; "in";
702       body = term ->
703         return_term loc (Ast.LetRec (`CoInductive, defs, body))
704     | LETREC; defs = let_defs; "in";
705       body = term ->
706         return_term loc (Ast.LetRec (`Inductive, defs, body))
707     ]
708   ];
709   term: LEVEL "20"
710     [
711       [ b = binder; (vars, typ) = maybe_protected_binder_vars; SYMBOL "."; body = term LEVEL "19" ->
712           return_term loc (fold_cluster b vars typ body)
713       ]
714     ];
715   term: LEVEL "70"
716     [
717       [ p1 = term; p2 = term LEVEL "71" ->
718           let rec aux = function
719             | Ast.Appl (hd :: tl)
720             | Ast.AttributedTerm (_, Ast.Appl (hd :: tl)) ->
721                 aux hd @ tl
722             | term -> [term]
723           in
724           return_term loc (Ast.Appl (aux p1 @ [p2]))
725       ]
726     ];
727   term: LEVEL "90"
728     [
729       [ id = IDENT -> return_term loc (Ast.Ident (id, None))
730       | id = IDENT; s = explicit_subst ->
731           return_term loc (Ast.Ident (id, Some s))
732       | s = CSYMBOL -> return_term loc (Ast.Symbol (s, 0))
733       | u = URI -> return_term loc (Ast.Uri (u, None))
734       | r = NREF -> return_term loc (Ast.NRef (NReference.reference_of_string r))
735       | n = NUMBER -> return_term loc (Ast.Num (n, 0))
736       | IMPLICIT -> return_term loc (Ast.Implicit `JustOne)
737       | SYMBOL <:unicode<ldots>> -> return_term loc (Ast.Implicit `Vector)
738       | PLACEHOLDER -> return_term loc Ast.UserInput
739       | m = META -> return_term loc (Ast.Meta (int_of_string m, []))
740       | m = META; s = meta_substs ->
741           return_term loc (Ast.Meta (int_of_string m, s))
742       | s = sort -> return_term loc (Ast.Sort s)
743       | "match"; t = term;
744         indty_ident = OPT [ "in"; id = IDENT -> id, None ];
745         outtyp = OPT [ "return"; ty = term -> ty ];
746         "with"; SYMBOL "[";
747         patterns = LIST0 [
748           lhs = match_pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *);
749           rhs = term ->
750             lhs, rhs
751         ] SEP SYMBOL "|";
752         SYMBOL "]" ->
753           return_term loc (Ast.Case (t, indty_ident, outtyp, patterns))
754       | LPAREN; p1 = term; SYMBOL ":"; p2 = term; RPAREN ->
755           return_term loc (Ast.Cast (p1, p2))
756       | LPAREN; p = term; RPAREN -> p
757       | blob = UNPARSED_META ->
758           parse_level2_meta grammars (Ulexing.from_utf8_string blob)
759       ]
760     ];
761 END
762   end;
763 (* }}} *)
764   grammars
765 ;;
766
767 let initial_grammars keywords =
768   let lexers = CicNotationLexer.mk_lexers keywords in
769   let level1_pattern_grammar = 
770     Grammar.gcreate lexers.CicNotationLexer.level1_pattern_lexer in
771   let level2_ast_grammar = 
772     Grammar.gcreate lexers.CicNotationLexer.level2_ast_lexer in
773   let level2_meta_grammar = 
774     Grammar.gcreate lexers.CicNotationLexer.level2_meta_lexer in
775   let level1_pattern =
776     Grammar.Entry.create level1_pattern_grammar "level1_pattern" in
777   let level2_ast = Grammar.Entry.create level2_ast_grammar "level2_ast" in
778   let term = Grammar.Entry.create level2_ast_grammar "term" in
779   let let_defs = Grammar.Entry.create level2_ast_grammar "let_defs" in
780   let protected_binder_vars = 
781     Grammar.Entry.create level2_ast_grammar "protected_binder_vars" in
782   let level2_meta = Grammar.Entry.create level2_meta_grammar "level2_meta" in
783   initialize_grammars { level1_pattern=level1_pattern;
784     level2_ast=level2_ast;
785     term=term;
786     let_defs=let_defs;
787     protected_binder_vars=protected_binder_vars;
788     level2_meta=level2_meta;
789     level2_ast_grammar=level2_ast_grammar;
790   }
791 ;;
792
793 class type g_status =
794  object
795   method notation_parser_db: db
796  end
797
798 class status ~keywords:kwds =
799  object
800   val db = { grammars = initial_grammars kwds; keywords = kwds; items = [] }
801   method notation_parser_db = db
802   method set_notation_parser_db v = {< db = v >}
803   method set_notation_parser_status
804    : 'status. #g_status as 'status -> 'self
805    = fun o -> {< db = o#notation_parser_db >}
806  end
807
808 let extend (status : #status) (CL1P (level1_pattern,precedence)) action =
809         (* move inside constructor XXX *)
810   let add1item status (level, level1_pattern, action) =
811     let p_bindings, p_atoms =
812       List.split (extract_term_production status level1_pattern) in
813     Grammar.extend
814       [ Grammar.Entry.obj 
815         (status#notation_parser_db.grammars.term : 'a Grammar.Entry.e),
816         Some (Gramext.Level level),
817         [ None,
818           Some (*Gramext.NonA*) Gramext.NonA,
819           [ p_atoms, 
820             (make_action
821               (fun (env: NotationEnv.t) (loc: Ast.location) ->
822                 (action env loc))
823             p_bindings) ]]];
824     status
825   in
826   let current_item = 
827     let level = level_of precedence in
828     level, level1_pattern, action in
829   let keywords = NotationUtil.keywords_of_term level1_pattern @
830     status#notation_parser_db.keywords in
831   let items = current_item :: status#notation_parser_db.items in 
832   let status = status#set_notation_parser_status (new status ~keywords) in
833   let status = status#set_notation_parser_db 
834     {status#notation_parser_db with items = items} in
835   List.fold_left add1item status items
836 ;;
837
838
839 let parse_level1_pattern status =
840   parse_level1_pattern status#notation_parser_db.grammars 
841 let parse_level2_ast status =
842   parse_level2_ast status#notation_parser_db.grammars 
843 let parse_level2_meta status =
844   parse_level2_meta status#notation_parser_db.grammars
845 let parse_term status =
846   parse_term status#notation_parser_db.grammars
847
848 let level2_ast_grammar status = 
849   status#notation_parser_db.grammars.level2_ast_grammar
850 let term status = status#notation_parser_db.grammars.term
851 let let_defs status = status#notation_parser_db.grammars.let_defs
852 let protected_binder_vars status = 
853   status#notation_parser_db.grammars.protected_binder_vars
854
855 (** {2 Debugging} *)
856
857 let print_l2_pattern status =
858   Grammar.print_entry Format.std_formatter 
859     (Grammar.Entry.obj status#notation_parser_db.grammars.term);
860   Format.pp_print_flush Format.std_formatter ();
861   flush stdout  
862
863 (* vim:set encoding=utf8 foldmethod=marker: *)