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