1 (* Copyright (C) 2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
30 module Ast = NotationPt
31 module Env = NotationEnv
33 module StringSet = Set.Make(String)
35 (* let prerr_endline _ = () *)
37 exception Parse_error of string
38 exception Level_not_found of int
40 let min_precedence = 0
41 let max_precedence = 100
43 type ('a,'b,'c,'d,'e) grammars = {
44 level1_pattern: 'a Grammar.Entry.e;
45 level2_ast: 'b Grammar.Entry.e;
46 level2_ast_grammar : Grammar.g;
47 term: 'b Grammar.Entry.e;
48 ident: 'e Grammar.Entry.e;
49 sym_attributes: (string option * string option) Grammar.Entry.e;
50 sym_table: ([ `Sym of string | `Kwd of string ] * Stdpp.location Grammar.Entry.e) list;
51 let_defs: 'c Grammar.Entry.e;
52 let_codefs: 'c Grammar.Entry.e;
53 protected_binder_vars: 'd Grammar.Entry.e;
54 level2_meta: 'b Grammar.Entry.e;
57 type checked_l1_pattern = CL1P of NotationPt.term * int
59 let refresh_uri_in_checked_l1_pattern ~refresh_uri_in_term
60 ~refresh_uri_in_reference (CL1P (t,n))
62 CL1P (NotationUtil.refresh_uri_in_term ~refresh_uri_in_term
63 ~refresh_uri_in_reference t, n)
66 | NoBinding of string option (* name of Ast.Symbol associated to this literal *)
67 | Binding of string * Env.value_type
68 | Env of (string * Env.value_type) list
72 (int -> NotationPt.term,
74 (Ast.term Ast.capture_variable list *
75 Ast.term Ast.capture_variable * Ast.term * int) list,
76 Ast.term list * Ast.term option, Env.ident_or_var) grammars;
77 keywords: string list;
78 items: (string * Ast.term * (NotationEnv.t -> Ast.location -> Ast.term)) list;
79 loctable: (string option * string option) CicNotationLexer.LocalizeEnv.t ref
84 Pervasives.int_of_string s
86 failwith (sprintf "Lexer failure: string_of_int \"%s\" failed" s)
88 (** {2 Grammar extension} *)
90 let level_of precedence =
91 if precedence < min_precedence || precedence > max_precedence then
92 raise (Level_not_found precedence);
93 string_of_int precedence
95 let add_item_to_grammar_explicit level2_ast_grammar
96 sym_attributes sym_table item =
97 let stok, nonterm = match item with
98 | `Sym sy -> Gramext.Stoken ("SYMBOL",sy), "sym" ^ sy
99 | `Kwd i -> Gramext.Stoken("",i), "kwd" ^ i
102 let _ = List.assoc item sym_table
105 (* let entry = Grammar.Entry.create level2_ast_grammar ("sym" ^ s) in *)
106 let entry = Grammar.Entry.create level2_ast_grammar nonterm in
108 [ Grammar.Entry.obj entry,
111 Some (*Gramext.NonA*) Gramext.NonA,
112 [ [stok], (* concrete l1 syntax *)
113 (Gramext.action (fun _ loc -> (* None, *) loc))
114 (* ; [Gramext.Stoken ("ATAG","")
115 ;Gramext.Snterm (Grammar.Entry.obj sym_attributes)
116 ;Gramext.Stoken ("SYMBOL","\005")
118 ;Gramext.Stoken ("ATAGEND","")],
119 (Gramext.action (fun _ uridesc _ _ _ loc -> (Some uridesc),loc)) *)
121 (* prerr_endline ("adding to grammar symbol " ^ s); *)
122 (item,entry)::sym_table
125 let add_item_to_grammar status item =
126 let sym_attributes = status#notation_parser_db.grammars.sym_attributes in
127 let sym_table = status#notation_parser_db.grammars.sym_table in
128 let level2_ast_grammar =
129 status#notation_parser_db.grammars.level2_ast_grammar
132 add_item_to_grammar_explicit level2_ast_grammar sym_attributes sym_table
136 { status#notation_parser_db.grammars with sym_table = sym_table }
138 let notation_parser_db =
139 { status#notation_parser_db with grammars = grammars } in
140 status#set_notation_parser_db notation_parser_db
142 let gram_symbol status s =
143 let sym_table = status#notation_parser_db.grammars.sym_table in
145 try List.assoc (`Sym s) sym_table
147 (let syms = List.map fst (status#notation_parser_db.grammars.sym_table) in
148 let syms = List.map (fun x -> match x with `Sym x | `Kwd x -> "\"" ^ x ^ "\"") syms in
149 prerr_endline ("new symbol/keyword non-terminals: " ^ (String.concat ", " syms));
150 prerr_endline ("unable to find symbol \"" ^ s ^ "\"");
152 * Gramext.Stoken("SYMBOL", s) *)
155 Gramext.Snterm (Grammar.Entry.obj entry)
157 let gram_ident status =
158 Gramext.Snterm (Grammar.Entry.obj
159 (status#notation_parser_db.grammars.ident : 'a Grammar.Entry.e))
160 (*Gramext.Stoken ("IDENT", s)*)
161 let gram_number s = Gramext.Stoken ("NUMBER", s)
162 let gram_keyword status s =
163 let sym_table = status#notation_parser_db.grammars.sym_table in
164 try Gramext.Snterm (Grammar.Entry.obj
165 (List.assoc (`Kwd s) sym_table))
167 (let syms = List.map fst (status#notation_parser_db.grammars.sym_table) in
168 let syms = List.map (fun x -> match x with `Sym x | `Kwd x -> "\"" ^ x ^ "\"") syms in
169 (* prerr_endline ("new symbol/keyword non-terminals: " ^ (String.concat ", " syms));
170 prerr_endline ("unable to find keyword \"" ^ s ^ "\""); *)
171 Gramext.Stoken("", s))
173 let gram_term status = function
174 | Ast.Self _ -> Gramext.Sself
175 | Ast.Level precedence ->
178 (status#notation_parser_db.grammars.term : 'a Grammar.Entry.e),
182 let gram_of_literal status =
184 | `Symbol (s,_) -> gram_symbol status s
185 | `Keyword (s,_) -> gram_keyword status s
186 | `Number (s,_) -> gram_number s
188 let make_action status action bindings =
189 let rec aux (vl : NotationEnv.t) =
191 [] -> Gramext.action (fun (loc: Ast.location) -> action vl loc)
192 | NoBinding csym :: tl ->
194 (fun ((*_,*)(loc: Ast.location)) ->
197 let a,b = HExtlib.loc_of_floc loc in
198 CicNotationLexer.LocalizeEnv.find loc
199 !(status#notation_parser_db.loctable)
200 with Not_found -> None, None
201 in aux (("",(Env.NoType,
202 Env.DisambiguationValue (csym,loc,uri,desc)))::vl) tl)
203 (* LUCA: DEFCON 3 BEGIN *)
204 | Binding (name, Env.TermType l) :: tl ->
207 aux ((name, (Env.TermType l, Env.TermValue v))::vl) tl)
208 | Binding (name, Env.StringType) :: tl ->
210 (fun (v:Env.ident_or_var) ->
211 aux ((name, (Env.StringType, Env.StringValue v)) :: vl) tl)
212 | Binding (name, Env.NumType) :: tl ->
215 aux ((name, (Env.NumType, Env.NumValue v)) :: vl) tl)
216 | Binding (name, Env.OptType t) :: tl ->
218 (fun (v:'a option) ->
219 aux ((name, (Env.OptType t, Env.OptValue v)) :: vl) tl)
220 | Binding (name, Env.ListType t) :: tl ->
223 aux ((name, (Env.ListType t, Env.ListValue v)) :: vl) tl)
225 Gramext.action (fun (v:NotationEnv.t) -> aux (v @ vl) tl)
226 | _ (* Binding (_,NoType) *) -> assert false
227 (* LUCA: DEFCON 3 END *)
229 aux [] (List.rev bindings)
235 | NoBinding _ :: tl -> aux acc tl
236 | Env names :: tl -> aux (List.rev names @ acc) tl
237 | Binding (name, ty) :: tl -> aux ((name, ty) :: acc) tl
241 (* given a level 1 pattern, adds productions for symbols when needed *)
242 let update_sym_grammar status pattern =
243 let rec aux status = function
244 | Ast.AttributedTerm (_, t) -> aux status t
245 | Ast.Literal l -> aux_literal status l
246 | Ast.Layout l -> aux_layout status l
247 | Ast.Magic m -> aux_magic status m
248 | Ast.Variable v -> aux_variable status v
250 prerr_endline (NotationPp.pp_term status t);
252 and aux_literal status =
254 | _,`Symbol (s,_) -> add_item_to_grammar status (`Sym s)
255 | _,`Keyword (s,_) ->
256 if not (List.mem s CicNotationLexer.initial_keywords)
257 then add_item_to_grammar status (`Kwd s)
259 | _,`Number _ -> status
260 and aux_layout status = function
261 | Ast.Sub (p1, p2) -> aux (aux status p1) p2
262 | Ast.Sup (p1, p2) -> aux (aux status p1) p2
263 | Ast.Below (p1, p2) -> aux (aux status p1) p2
264 | Ast.Above (p1, p2) -> aux (aux status p1) p2
265 | Ast.Frac (p1, p2) -> aux (aux status p1) p2
266 | Ast.InfRule (p1, p2, p3) -> aux (aux (aux status p1) p2) p3
267 | Ast.Atop (p1, p2) -> aux (aux status p1) p2
268 | Ast.Over (p1, p2) -> aux (aux status p1) p2
269 | Ast.Root (p1, p2) -> aux (aux status p1) p2
270 | Ast.Sqrt p -> aux status p
271 | Ast.Break -> status
272 | Ast.Box (_, pl) -> List.fold_left aux status pl
273 | Ast.Group pl -> List.fold_left aux status pl
274 | Ast.Mstyle (_,pl) -> List.fold_left aux status pl
275 | Ast.Mpadded (_,pl) -> List.fold_left aux status pl
276 | Ast.Maction l -> List.fold_left aux status l
277 and aux_magic status magic =
279 | Ast.Opt p -> aux status p
281 | Ast.List1 (p, s) ->
283 match s with None -> status | Some s' -> aux_literal status (None,s')
287 and aux_variable status _ = status
291 (* given a level 1 pattern computes the new RHS of "term" grammar entry *)
292 let extract_term_production status pattern =
293 let rec aux = function
294 | Ast.AttributedTerm (_, t) -> aux t
295 | Ast.Literal l -> aux_literal l
296 | Ast.Layout l -> aux_layout l
297 | Ast.Magic m -> aux_magic m
298 | Ast.Variable v -> aux_variable v
300 prerr_endline (NotationPp.pp_term status t);
304 | csym,`Symbol (s,_) -> [NoBinding csym, gram_symbol status s]
305 | csym,`Keyword (s,_) ->
306 (* assumption: s will be registered as a keyword with the lexer *)
307 [NoBinding csym, gram_keyword status s]
308 | csym,`Number (s,_) -> [NoBinding csym, gram_number s]
309 and aux_layout = function
310 | Ast.Sub (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\sub "] @ aux p2
311 | Ast.Sup (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\sup "] @ aux p2
312 | Ast.Below (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\below "] @ aux p2
313 | Ast.Above (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\above "] @ aux p2
314 | Ast.Frac (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\frac "] @ aux p2
315 | Ast.InfRule (p1, p2, p3) -> [NoBinding None, gram_symbol status "\\infrule "] @ aux p1 @ aux p2 @ aux p3
316 | Ast.Atop (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\atop "] @ aux p2
317 | Ast.Over (p1, p2) -> aux p1 @ [NoBinding None, gram_symbol status "\\over "] @ aux p2
318 | Ast.Root (p1, p2) ->
319 [NoBinding None, gram_symbol status "\\root "] @ aux p2
320 @ [NoBinding None, gram_symbol status "\\of "] @ aux p1
321 | Ast.Sqrt p -> [NoBinding None, gram_symbol status "\\sqrt "] @ aux p
323 | Ast.Box (_, pl) -> List.flatten (List.map aux pl)
324 | Ast.Group pl -> List.flatten (List.map aux pl)
325 | Ast.Mstyle (_,pl) -> List.flatten (List.map aux pl)
326 | Ast.Mpadded (_,pl) -> List.flatten (List.map aux pl)
327 | Ast.Maction l -> List.flatten (List.map aux l)
328 and aux_magic magic =
331 let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
332 let action (env_opt : NotationEnv.t option) (loc : Ast.location) =
334 | Some env -> List.map Env.opt_binding_some env
335 | None -> List.map Env.opt_binding_of_name p_names
337 [ Env (List.map Env.opt_declaration p_names),
339 [ [ Gramext.Sopt (Gramext.srules [ p_atoms, p_action ]) ],
340 Gramext.action action ] ]
342 | Ast.List1 (p, _) ->
343 let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
344 let action (env_list : NotationEnv.t list) (loc : Ast.location) =
345 NotationEnv.coalesce_env p_names env_list
349 | Ast.List0 (_, None) -> Gramext.Slist0 s
350 | Ast.List1 (_, None) -> Gramext.Slist1 s
351 | Ast.List0 (_, Some l) ->
352 Gramext.Slist0sep (s, gram_of_literal status l,true)
353 | Ast.List1 (_, Some l) ->
354 Gramext.Slist1sep (s, gram_of_literal status l,true)
357 [ Env (List.map Env.list_declaration p_names),
359 [ [ gram_of_list (Gramext.srules [ p_atoms, p_action ]) ],
360 Gramext.action action ] ]
364 | Ast.NumVar s -> [Binding (s, Env.NumType), gram_number ""]
365 | Ast.TermVar (s,(Ast.Self level|Ast.Level level as lv)) ->
366 [Binding (s, Env.TermType level), gram_term status lv]
367 | Ast.IdentVar s -> [Binding (s, Env.StringType), gram_ident status]
368 | Ast.Ascription (p, s) -> assert false (* TODO *)
369 | Ast.FreshVar _ -> assert false
370 and inner_pattern p =
371 let p_bindings, p_atoms = List.split (aux p) in
372 let p_names = flatten_opt p_bindings in
375 (fun (env : NotationEnv.t) (loc : Ast.location) -> env) p_bindings
377 p_bindings, p_atoms, p_names, action
381 type rule_id = Grammar.token Gramext.g_symbol list
383 let compare_rule_id x y =
384 let rec aux = function
388 | ((s1::tl1) as x),((s2::tl2) as y) ->
389 if Gramext.eq_symbol s1 s2 then aux (tl1,tl2)
390 else Pervasives.compare x y
395 let check_l1_pattern level1_pattern pponly level associativity =
396 let variables = ref 0 in
397 let symbols = ref 0 in
398 let rec aux = function
399 | Ast.AttributedTerm (att, t) -> Ast.AttributedTerm (att,aux t)
400 | Ast.Literal _ as l -> incr symbols; l
401 | Ast.Layout l -> Ast.Layout (aux_layout l)
402 | Ast.Magic m -> Ast.Magic (aux_magic m)
403 | Ast.Variable v -> (aux_variable v)
405 and aux_layout = function
406 | Ast.Sub (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Sub (p1, p2)
407 | Ast.Sup (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Sup (p1, p2)
408 | Ast.Below (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Below (p1, p2)
409 | Ast.Above (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Above (p1, p2)
410 | Ast.Frac (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Frac (p1, p2)
411 | 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)
412 | Ast.Atop (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Atop (p1, p2)
413 | Ast.Over (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Over (p1, p2)
414 | Ast.Root (p1, p2) -> let p1 = aux p1 in let p2 = aux p2 in Ast.Root (p1, p2)
415 | Ast.Sqrt p -> Ast.Sqrt (aux p)
416 | Ast.Break as t -> t
417 | Ast.Box (b, pl) -> Ast.Box(b, List.map aux pl)
418 | Ast.Group pl -> Ast.Group (List.map aux pl)
419 | Ast.Mstyle (l,pl) -> Ast.Mstyle (l, List.map aux pl)
420 | Ast.Mpadded (l,pl) -> Ast.Mpadded (l, List.map aux pl)
421 | Ast.Maction l as t ->
423 raise(Parse_error("Maction can be used only in output notations"))
425 and aux_magic magic =
427 | Ast.Opt p -> Ast.Opt (aux p)
428 | Ast.List0 (p, x) -> Ast.List0 (aux p, x)
429 | Ast.List1 (p, x) -> Ast.List1 (aux p, x)
433 | Ast.NumVar _ as t -> Ast.Variable t
434 | Ast.TermVar (s,Ast.Self _) when associativity <> Gramext.NonA ->
436 if !variables > 2 then
437 raise (Parse_error ("Exactly 2 variables must be specified in an "^
438 "associative notation"));
439 (match !variables, associativity with
441 Ast.Variable (Ast.TermVar (s, Ast.Self level))
442 | 1,Gramext.RightA ->
443 Ast.Variable (Ast.TermVar (s, Ast.Self (level+1)))
445 Ast.Variable (Ast.TermVar (s, Ast.Self (level+1)))
446 | 2,Gramext.RightA ->
447 Ast.Variable (Ast.TermVar (s, Ast.Level (level-1)))
449 | Ast.TermVar (s,Ast.Level _) when associativity <> Gramext.NonA ->
450 raise (Parse_error ("Variables can not be declared with a " ^
451 "precedence in an associative notation"))
452 (*avoid camlp5 divergence due to non-Sself recursion at the same level *)
453 | Ast.TermVar (s,Ast.Level l) when l<=level && !variables=0 && !symbols=0->
454 raise(Parse_error("Left recursive rule with precedence not greater " ^
455 "than " ^ string_of_int level ^ " is not allowed to avoid divergence"))
456 | Ast.TermVar _ as t -> incr variables; Ast.Variable t
457 | Ast.IdentVar _ as t -> Ast.Variable t
458 | Ast.Ascription _ -> assert false (* TODO *)
459 | Ast.FreshVar _ -> assert false
461 if associativity <> Gramext.NonA && level = min_precedence then
462 raise (Parse_error ("You can not specify an associative notation " ^
463 "at level "^string_of_int min_precedence ^ "; increase it"));
464 let cp = aux level1_pattern in
465 (* prerr_endline ("checked_pattern: " ^ NotationPp.pp_term cp); *)
466 if !variables <> 2 && associativity <> Gramext.NonA then
467 raise (Parse_error ("Exactly 2 variables must be specified in an "^
468 "associative notation"));
474 let fold_cluster binder terms ty body =
476 (fun term body -> Ast.Binder (binder, (term, ty), body))
477 terms body (* terms are names: either Ident or FreshVar *)
479 let fold_exists terms ty body =
482 let lambda = Ast.Binder (`Lambda, (term, ty), body) in
483 Ast.Appl [ Ast.Symbol ("exists", None); lambda ])
486 let fold_binder binder pt_names body =
488 (fun (names, ty) body -> fold_cluster binder names ty body)
491 let return_term loc term = Ast.AttributedTerm (`Loc loc, term)
492 let return_term_of_level loc term l =
493 Ast.AttributedTerm (`Loc loc, term l)
495 (** {2 API implementation} *)
497 let exc_located_wrapper f =
501 | Stdpp.Exc_located (floc, Stream.Error msg) ->
502 raise (HExtlib.Localized (floc, Parse_error msg))
503 | Stdpp.Exc_located (floc, HExtlib.Localized (_,exn)) ->
504 raise (HExtlib.Localized (floc, (Parse_error (Printexc.to_string exn))))
505 | Stdpp.Exc_located (floc, exn) ->
506 raise (HExtlib.Localized (floc, (Parse_error (Printexc.to_string exn))))
508 let parse_level1_pattern grammars precedence lexbuf =
510 (fun () -> Grammar.Entry.parse grammars.level1_pattern (Obj.magic lexbuf) precedence)
512 let parse_level2_ast grammars lexbuf =
515 Grammar.Entry.parse grammars.level2_ast (Obj.magic lexbuf))
517 let parse_level2_meta grammars lexbuf =
519 (fun () -> Grammar.Entry.parse grammars.level2_meta (Obj.magic lexbuf))
521 (* create empty precedence level for "term" *)
522 let initialize_grammars loctable grammars =
524 Gramext.action (fun _ ->
525 failwith "internal error, lexer generated a dummy token")
527 (* Needed since campl4 on "delete_rule" remove the precedence level if it gets
528 * empty after the deletion. The lexer never generate the Stoken below. *)
529 let dummy_prod = [ [ Gramext.Stoken ("DUMMY", "") ], dummy_action ] in
530 let mk_level_list first last =
531 let rec aux acc = function
532 | i when i < first -> acc
535 ((Some (level_of i), Some Gramext.NonA, dummy_prod)
542 [ Grammar.Entry.obj (grammars.term: 'a Grammar.Entry.e),
544 mk_level_list min_precedence max_precedence ];
545 (* {{{ Grammar for concrete syntax patterns, notation level 1 *)
547 let level1_pattern = grammars.level1_pattern in
549 GLOBAL: level1_pattern;
552 [ p = l1_pattern; EOI -> fun l -> NotationUtil.boxify (p l) ]
555 [ p = LIST1 l1_simple_pattern ->
556 fun l -> List.map (fun x -> x l) p ]
559 [ s = SYMBOL -> `Symbol (s, (None,None))
560 | k = QKEYWORD -> `Keyword (k, (None,None))
561 | n = NUMBER -> `Number (n,(None,None))
565 [ csymname = OPT [ "ref" ; csymname = CSYMBOL ->
566 prerr_endline ("parser in rliteral (ref " ^ csymname ^ ")");
572 sep: [ [ "sep"; sep = literal -> sep ] ];
574 [ "list0"; p = l1_simple_pattern; sep = OPT sep ->
575 fun l -> Ast.List0 (p l, sep)
576 | "list1"; p = l1_simple_pattern; sep = OPT sep ->
577 fun l -> Ast.List1 (p l, sep)
578 | "opt"; p = l1_simple_pattern -> fun l -> Ast.Opt (p l)
581 l1_pattern_variable: [
582 [ "term"; precedence = NUMBER; id = IDENT ->
583 Ast.TermVar (id, Ast.Level (int_of_string precedence))
584 | "number"; id = IDENT -> Ast.NumVar id
585 | "ident"; id = IDENT -> Ast.IdentVar id
590 v = [ IDENT | NUMBER | COLOR | FLOATWITHUNIT ] -> id, v]];
593 v = [ PERCENTAGE ] -> id, v]];
596 [ p1 = SELF; SYMBOL "\\sub "; p2 = SELF ->
597 return_term_of_level loc
598 (fun l -> Ast.Layout (Ast.Sub (p1 l, p2 l)))
599 | p1 = SELF; SYMBOL "\\sup "; p2 = SELF ->
600 return_term_of_level loc
601 (fun l -> Ast.Layout (Ast.Sup (p1 l, p2 l)))
602 | p1 = SELF; SYMBOL "\\below "; p2 = SELF ->
603 return_term_of_level loc
604 (fun l -> Ast.Layout (Ast.Below (p1 l, p2 l)))
605 | p1 = SELF; SYMBOL "\\above "; p2 = SELF ->
606 return_term_of_level loc
607 (fun l -> Ast.Layout (Ast.Above (p1 l, p2 l)))
608 | p1 = SELF; SYMBOL "\\over "; p2 = SELF ->
609 return_term_of_level loc
610 (fun l -> Ast.Layout (Ast.Over (p1 l, p2 l)))
611 | p1 = SELF; SYMBOL "\\atop "; p2 = SELF ->
612 return_term_of_level loc
613 (fun l -> Ast.Layout (Ast.Atop (p1 l, p2 l)))
614 | p1 = SELF; SYMBOL "\\frac "; p2 = SELF ->
615 return_term_of_level loc
616 (fun l -> Ast.Layout (Ast.Frac (p1 l, p2 l)))
617 | SYMBOL "\\infrule "; p1 = SELF; p2 = SELF; p3 = SELF ->
618 return_term_of_level loc
619 (fun l -> Ast.Layout (Ast.InfRule (p1 l, p2 l, p3 l)))
620 | SYMBOL "\\sqrt "; p = SELF ->
621 return_term_of_level loc (fun l -> Ast.Layout (Ast.Sqrt p l))
622 | SYMBOL "\\root "; index = SELF; SYMBOL "\\of "; arg = SELF ->
623 return_term_of_level loc
624 (fun l -> Ast.Layout (Ast.Root (arg l, index l)))
625 | "hbox"; LPAREN; p = l1_pattern; RPAREN ->
626 return_term_of_level loc
627 (fun l -> Ast.Layout (Ast.Box ((Ast.H, false, false), p l)))
628 | "vbox"; LPAREN; p = l1_pattern; RPAREN ->
629 return_term_of_level loc
630 (fun l -> Ast.Layout (Ast.Box ((Ast.V, false, false), p l)))
631 | "hvbox"; LPAREN; p = l1_pattern; RPAREN ->
632 return_term_of_level loc
633 (fun l -> Ast.Layout (Ast.Box ((Ast.HV, false, false), p l)))
634 | "hovbox"; LPAREN; p = l1_pattern; RPAREN ->
635 return_term_of_level loc
636 (fun l -> Ast.Layout (Ast.Box ((Ast.HOV, false, false), p l)))
637 | "break" -> return_term_of_level loc (fun _ -> Ast.Layout Ast.Break)
638 | "mstyle"; m = LIST1 mstyle ; LPAREN; t = l1_pattern; RPAREN ->
639 return_term_of_level loc
641 Ast.Layout (Ast.Mstyle (m, t l)))
642 | "mpadded"; m = LIST1 mpadded ; LPAREN; t = l1_pattern; RPAREN ->
643 return_term_of_level loc
645 Ast.Layout (Ast.Mpadded (m, t l)))
646 | "maction"; m = LIST1 [ LPAREN; l = l1_pattern; RPAREN -> l ] ->
647 return_term_of_level loc
648 (fun l -> Ast.Layout (Ast.Maction (List.map (fun x ->
649 NotationUtil.group (x l)) m)))
650 | LPAREN; p = l1_pattern; RPAREN ->
651 return_term_of_level loc (fun l -> NotationUtil.group (p l))
655 return_term_of_level loc
656 (fun l -> Ast.Variable (Ast.TermVar (i,Ast.Self l)))
657 | m = l1_magic_pattern ->
658 return_term_of_level loc (fun l -> Ast.Magic (m l))
659 | v = l1_pattern_variable ->
660 return_term_of_level loc (fun _ -> Ast.Variable v)
661 | l = rliteral -> return_term_of_level loc (fun _ -> Ast.Literal l)
667 (* {{{ Grammar for ast magics, notation level 2 *)
669 let level2_meta = grammars.level2_meta in
673 [ "term"; precedence = NUMBER; id = IDENT ->
674 Ast.TermVar (id,Ast.Level (int_of_string precedence))
675 | "number"; id = IDENT -> Ast.NumVar id
676 | "ident"; id = IDENT -> Ast.IdentVar id
677 | "fresh"; id = IDENT -> Ast.FreshVar id
678 | "anonymous" -> Ast.TermVar ("_",Ast.Self 0) (* is the level relevant?*)
679 | id = IDENT -> Ast.TermVar (id,Ast.Self 0)
683 [ "fold"; kind = [ "left" -> `Left | "right" -> `Right ];
684 base = level2_meta; "rec"; id = IDENT; recursive = level2_meta ->
685 Ast.Fold (kind, base, [id], recursive)
686 | "default"; some = level2_meta; none = level2_meta ->
687 Ast.Default (some, none)
688 | "if"; p_test = level2_meta;
689 "then"; p_true = level2_meta;
690 "else"; p_false = level2_meta ->
691 Ast.If (p_test, p_true, p_false)
696 [ magic = l2_magic -> Ast.Magic magic
697 | var = l2_variable -> Ast.Variable var
698 | blob = UNPARSED_AST ->
699 parse_level2_ast grammars (Ulexing.from_utf8_string blob)
705 (* {{{ Grammar for ast patterns, notation level 2 *)
707 let level2_ast = grammars.level2_ast in
708 let term = grammars.term in
709 let atag_attributes = grammars.sym_attributes in
710 let let_defs = grammars.let_defs in
711 let let_codefs = grammars.let_codefs in
712 let ident = grammars.ident in
713 let protected_binder_vars = grammars.protected_binder_vars in
715 GLOBAL: level2_ast term let_defs let_codefs protected_binder_vars ident atag_attributes;
716 level2_ast: [ [ p = term -> p ] ];
720 | "Type"; SYMBOL "["; n = [ NUMBER| IDENT ]; SYMBOL "]" -> `NType n
721 | "CProp"; SYMBOL "["; n = [ NUMBER| IDENT ]; SYMBOL "]" -> `NCProp n
725 [ s = SYMBOL "_" -> None
726 | p = term -> Some p ]
729 [ SYMBOL "["; substs = LIST0 meta_subst; SYMBOL "]" -> substs ]
731 possibly_typed_name: [
732 [ LPAREN; id = single_arg; SYMBOL ":"; typ = term; RPAREN ->
734 | arg = single_arg -> arg, None
735 | id = PIDENT -> Ast.Ident (id, `Ambiguous), None
736 | SYMBOL "_" -> Ast.Ident ("_", `Ambiguous), None
737 | LPAREN; id = PIDENT; SYMBOL ":"; typ = term; RPAREN ->
738 Ast.Ident (id, `Ambiguous), Some typ
739 | LPAREN; SYMBOL "_"; SYMBOL ":"; typ = term; RPAREN ->
740 Ast.Ident ("_", `Ambiguous), Some typ
744 [ SYMBOL "_" -> Ast.Wildcard
745 | id = IDENT -> Ast.Pattern (id, None, [])
746 | LPAREN; id = IDENT; vars = LIST1 possibly_typed_name; RPAREN ->
747 Ast.Pattern (id, None, vars)
748 | id = IDENT; vars = LIST1 possibly_typed_name ->
749 Ast.Pattern (id, None, vars)
753 [ SYMBOL <:unicode<Pi>> (* Π *) -> `Pi
754 | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall
755 | SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda
761 let uri,_ = CicNotationLexer.LocalizeEnv.find loc
765 prerr_endline ("trovata interpretazione per " ^ id ^ ": " ^ u);
768 prerr_endline ("identificatore ambiguo: " ^ id);
772 prerr_endline ("identificatore non trovato: " ^ id);
777 match CicNotationLexer.LocalizeEnv.find loc !loctable with
778 | _uri, Some interpr -> n, Some (Some "cic:/fakeuri.def(1)",interpr)
781 | Not_found -> n,None ]];
783 [ LPAREN; names = LIST1 gident SEP SYMBOL ",";
784 SYMBOL ":"; ty = term; RPAREN ->
785 List.map (fun (n,u) -> Ast.Ident (n,u)) names, Some ty
786 | (name,uri) = gident -> [Ast.Ident (name,uri)], None
787 | blob = UNPARSED_META ->
788 let meta = parse_level2_meta grammars (Ulexing.from_utf8_string blob) in
790 | Ast.Variable (Ast.FreshVar _) -> [meta], None
791 | Ast.Variable (Ast.TermVar ("_",_)) -> [Ast.Ident ("_", `Ambiguous)], None
792 | _ -> failwith "Invalid bound name."
796 [ (name,uri) = gident -> Ast.Ident (name,uri)
797 | blob = UNPARSED_META ->
798 let meta = parse_level2_meta grammars (Ulexing.from_utf8_string blob) in
800 | Ast.Variable (Ast.FreshVar _)
801 | Ast.Variable (Ast.IdentVar _) -> meta
802 | Ast.Variable (Ast.TermVar ("_",_)) -> Ast.Ident ("_", `Ambiguous)
803 | _ -> failwith "Invalid index name."
807 [ name = IDENT -> Env.Ident name
808 | blob = UNPARSED_META ->
809 let meta = parse_level2_meta grammars (Ulexing.from_utf8_string blob) in
811 | Ast.Variable (Ast.FreshVar _) ->
812 (* it makes sense: extend Env.ident_or_var *)
814 | Ast.Variable (Ast.IdentVar name) -> Env.Var name
815 | Ast.Variable (Ast.TermVar ("_",_)) -> Env.Var "_"
816 | _ -> failwith ("Invalid index name: " ^ blob)
823 index_name = OPT [ "on"; id = single_arg -> id ];
824 ty = OPT [ SYMBOL ":" ; p = term -> p ];
825 SYMBOL <:unicode<def>> (* ≝ *); body = term ->
826 let rec position_of name p = function
828 | n :: _ when n = name -> Some p, p
829 | _ :: tl -> position_of name (p + 1) tl
831 let rec find_arg name n = function
833 (* CSC: new NCicPp.status is the best I can do here
834 without changing the return type *)
835 Ast.fail loc (sprintf "Argument %s not found"
836 (NotationPp.pp_term (new NCicPp.status None) name))
838 (match position_of name 0 l with
839 | None, len -> find_arg name (n + len) tl
840 | Some where, len -> n + where)
843 match index_name with
845 | Some index_name -> find_arg index_name 0 args
850 (function (names,ty) -> List.map (function x -> x,ty) names
853 args, (name, ty), body, index
860 [ l = LIST1 single_arg SEP SYMBOL "," -> l
861 | l = LIST1 [ PIDENT | SYMBOL "_" ] SEP SYMBOL "," ->
862 List.map (fun x -> Ast.Ident(x,`Ambiguous)) l
864 typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
867 protected_binder_vars: [
868 [ LPAREN; vars = binder_vars; RPAREN -> vars
871 maybe_protected_binder_vars: [
872 [ vars = binder_vars -> vars
873 | vars = protected_binder_vars -> vars
880 [ LPAREN; id = single_arg; SYMBOL ":"; typ = term; RPAREN ->
882 | (id,uri) = gident; ty = OPT [ SYMBOL ":"; typ = term -> typ] ->
883 Ast.Ident (id,uri), ty ];
884 SYMBOL <:unicode<def>> (* ≝ *);
885 p1 = term; "in"; p2 = term ->
886 return_term loc (Ast.LetIn (var, p1, p2))
887 | LETCOREC; defs = let_defs; "in";
889 return_term loc (Ast.LetRec (`CoInductive, defs, body))
890 | LETREC; defs = let_defs; "in";
892 return_term loc (Ast.LetRec (`Inductive, defs, body))
897 [ b = binder; (vars, typ) = maybe_protected_binder_vars; SYMBOL "."; body = term LEVEL "19" ->
898 return_term loc (fold_cluster b vars typ body)
903 [ p1 = term; p2 = term LEVEL "71" ->
904 let rec aux = function
905 | Ast.Appl (hd :: tl)
906 | Ast.AttributedTerm (_, Ast.Appl (hd :: tl)) ->
910 return_term loc (Ast.Appl (aux p1 @ [p2]))
915 [ (id,uri) = gident -> return_term loc (Ast.Ident (id,uri))
916 | s = CSYMBOL -> return_term loc (Ast.Symbol (s, None))
917 | u = URI -> return_term loc (Ast.Ident
918 (NUri.name_of_uri (NUri.uri_of_string u), `Uri u))
919 | r = NREF -> return_term loc (Ast.NRef (NReference.reference_of_string r))
920 | (n,interpr) = gnum -> return_term loc (Ast.Num (n, interpr))
921 | IMPLICIT -> return_term loc (Ast.Implicit `JustOne)
922 | SYMBOL <:unicode<ldots>> -> return_term loc (Ast.Implicit `Vector)
923 | PLACEHOLDER -> return_term loc Ast.UserInput
924 | m = META -> return_term loc (Ast.Meta (int_of_string m, []))
925 | m = META; s = meta_substs ->
926 return_term loc (Ast.Meta (int_of_string m, s))
927 | s = sort -> return_term loc (Ast.Sort s)
929 indty_ident = OPT [ "in"; id = IDENT -> id, None ];
930 outtyp = OPT [ "return"; ty = term -> ty ];
933 lhs = match_pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *);
938 return_term loc (Ast.Case (t, indty_ident, outtyp, patterns))
939 | LPAREN; p1 = term; SYMBOL ":"; p2 = term; RPAREN ->
940 return_term loc (Ast.Cast (p1, p2))
941 | LPAREN; p = term; RPAREN -> p
942 | blob = UNPARSED_META ->
943 parse_level2_meta grammars (Ulexing.from_utf8_string blob)
953 let initial_grammars loctable keywords =
954 let lexers = CicNotationLexer.mk_lexers loctable keywords in
955 let level1_pattern_grammar =
956 Grammar.gcreate lexers.CicNotationLexer.level1_pattern_lexer in
957 let level2_ast_grammar =
958 Grammar.gcreate lexers.CicNotationLexer.level2_ast_lexer in
959 let level2_meta_grammar =
960 Grammar.gcreate lexers.CicNotationLexer.level2_meta_lexer in
962 Grammar.Entry.create level1_pattern_grammar "level1_pattern" in
963 let level2_ast = Grammar.Entry.create level2_ast_grammar "level2_ast" in
964 let term = Grammar.Entry.create level2_ast_grammar "term" in
965 let ident = Grammar.Entry.create level2_ast_grammar "ident" in
966 (* unexpanded TeX macros terminated by a space (see comment in
967 * CicNotationLexer) *)
968 let initial_symbols =
969 ["\\sub ";"\\sup ";"\\below ";"\\above ";"\\frac "
970 ;"\\infrule ";"\\atop ";"\\over ";"\\root ";"\\of ";"\\sqrt "] in
972 Grammar.Entry.create level2_ast_grammar "atag_attributes" in
975 (add_item_to_grammar_explicit level2_ast_grammar sym_attributes)
976 [] (List.map (fun s -> `Sym s) initial_symbols)
978 let let_defs = Grammar.Entry.create level2_ast_grammar "let_defs" in
979 let let_codefs = Grammar.Entry.create level2_ast_grammar "let_codefs" in
980 let protected_binder_vars =
981 Grammar.Entry.create level2_ast_grammar "protected_binder_vars" in
982 let level2_meta = Grammar.Entry.create level2_meta_grammar "level2_meta" in
983 initialize_grammars loctable
984 { level1_pattern=level1_pattern;
985 level2_ast=level2_ast;
989 sym_attributes=sym_attributes;
991 let_codefs=let_codefs;
992 protected_binder_vars=protected_binder_vars;
993 level2_meta=level2_meta;
994 level2_ast_grammar=level2_ast_grammar;
998 class type g_status =
1000 method notation_parser_db: db
1003 class status0 ~keywords:kwds =
1006 let lt = ref CicNotationLexer.LocalizeEnv.empty in
1007 { grammars = initial_grammars lt kwds; keywords = kwds;
1008 items = []; loctable = lt }
1009 method notation_parser_db = db
1010 method set_notation_parser_db v = {< db = v >}
1011 method set_notation_parser_status
1012 : 'status. #g_status as 'status -> 'self
1013 = fun o -> {< db = o#notation_parser_db >}
1014 method reset_loctable () =
1015 db.loctable := CicNotationLexer.LocalizeEnv.empty
1018 class virtual status uid ~keywords:kwds =
1020 inherit NCic.status uid
1021 inherit status0 kwds
1024 let extend (status : #status) (CL1P (level1_pattern,precedence)) action =
1025 (* move inside constructor XXX *)
1026 let add1item status (level, level1_pattern, action) =
1027 let status = update_sym_grammar status level1_pattern in
1028 let p_bindings, p_atoms =
1029 List.split (extract_term_production status level1_pattern)
1033 (status#notation_parser_db.grammars.term : 'a Grammar.Entry.e),
1034 Some (Gramext.Level level),
1036 Some (*Gramext.NonA*) Gramext.NonA,
1037 [ p_atoms, (* concrete l1 syntax *)
1039 (fun (env: NotationEnv.t) (loc: Ast.location) ->
1045 let level = level_of precedence in
1046 level, level1_pattern, action in
1047 let keywords = NotationUtil.keywords_of_term level1_pattern @
1048 status#notation_parser_db.keywords in
1049 let items = current_item :: status#notation_parser_db.items in
1050 let status = status#set_notation_parser_status (new status0 ~keywords) in
1051 let status = status#set_notation_parser_db
1052 {status#notation_parser_db with items = items} in
1053 List.fold_left add1item status items
1057 let parse_level1_pattern status =
1058 parse_level1_pattern status#notation_parser_db.grammars
1059 let parse_level2_ast status =
1060 parse_level2_ast status#notation_parser_db.grammars
1061 let parse_level2_meta status =
1062 parse_level2_meta status#notation_parser_db.grammars
1064 let level2_ast_grammar status =
1065 status#notation_parser_db.grammars.level2_ast_grammar
1066 let term status = status#notation_parser_db.grammars.term
1067 let let_defs status = status#notation_parser_db.grammars.let_defs
1068 let let_codefs status = status#notation_parser_db.grammars.let_codefs
1069 let protected_binder_vars status =
1070 status#notation_parser_db.grammars.protected_binder_vars
1072 (** {2 Debugging} *)
1074 let print_l2_pattern status =
1075 Grammar.print_entry Format.std_formatter
1076 (Grammar.Entry.obj status#notation_parser_db.grammars.term);
1077 Format.pp_print_flush Format.std_formatter ();
1080 (* vim:set encoding=utf8 foldmethod=marker: *)