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