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/
31 exception Parse_error of Token.flocation * string
32 exception Level_not_found of int
34 let grammar = Grammar.gcreate CicNotationLexer.notation_lexer
36 let min_precedence = 0
37 let max_precedence = 100
38 let default_precedence = 50
40 let level1_pattern = Grammar.Entry.create grammar "level1_pattern"
41 let level2_pattern = Grammar.Entry.create grammar "level2_pattern"
42 let level3_term = Grammar.Entry.create grammar "level3_term"
43 let l2_pattern = Grammar.Entry.create grammar "l2_pattern"
44 let notation = Grammar.Entry.create grammar "notation" (* level1 <-> level 2 *)
46 Grammar.Entry.create grammar "interpretation" (* level2 <-> level 3 *)
47 let phrase = Grammar.Entry.create grammar "phrase"
49 let return_term loc term = ()
52 let (x, y) = loc_of_floc floc in
53 failwith (sprintf "Error at characters %d - %d: %s" x y msg)
57 Pervasives.int_of_string s
59 failwith (sprintf "Lexer failure: string_of_int \"%s\" failed" s)
61 (** {2 Grammar extension} *)
63 let symbol s = Gramext.Stoken ("SYMBOL", s)
64 let ident s = Gramext.Stoken ("IDENT", s)
65 let number s = Gramext.Stoken ("NUMBER", s)
66 let term = Gramext.Sself
68 let g_symbol_of_literal =
70 | `Symbol s -> symbol s
71 | `Keyword s -> ident s
72 | `Number s -> number s
76 | Binding of string * value_type
77 | Env of (string * value_type) list
79 let make_action action bindings =
80 let rec aux (vl : CicNotationEnv.t) =
83 prerr_endline "aux: make_action";
84 Gramext.action (fun (loc: location) -> action vl loc)
86 prerr_endline "aux: none";
87 Gramext.action (fun _ -> aux vl tl)
88 (* LUCA: DEFCON 5 BEGIN *)
89 | Binding (name, TermType) :: tl ->
90 prerr_endline "aux: term";
92 (fun (v:term) -> aux ((name, (TermType, TermValue v))::vl) tl)
93 | Binding (name, StringType) :: tl ->
94 prerr_endline "aux: string";
97 aux ((name, (StringType, StringValue v)) :: vl) tl)
98 | Binding (name, NumType) :: tl ->
99 prerr_endline "aux: num";
101 (fun (v:string) -> aux ((name, (NumType, NumValue v)) :: vl) tl)
102 | Binding (name, OptType t) :: tl ->
103 prerr_endline "aux: opt";
105 (fun (v:'a option) ->
106 aux ((name, (OptType t, OptValue v)) :: vl) tl)
107 | Binding (name, ListType t) :: tl ->
108 prerr_endline "aux: list";
111 aux ((name, (ListType t, ListValue v)) :: vl) tl)
113 prerr_endline "aux: env";
114 Gramext.action (fun (v:CicNotationEnv.t) -> aux (v @ vl) tl)
115 (* LUCA: DEFCON 5 END *)
117 aux [] (List.rev bindings)
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
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 | AttributedTerm (_, t) -> aux t
133 | Literal l -> aux_literal l
134 | Layout l -> aux_layout l
135 | Magic m -> aux_magic m
136 | Variable v -> aux_variable v
138 prerr_endline (CicNotationPp.pp_term t);
142 | `Symbol s -> [NoBinding, symbol s]
143 | `Keyword s -> [NoBinding, ident s]
144 | `Number s -> [NoBinding, number s]
145 and aux_layout = function
146 | Sub (p1, p2) -> aux p1 @ [NoBinding, symbol "\\SUB"] @ aux p2
147 | Sup (p1, p2) -> aux p1 @ [NoBinding, symbol "\\SUP"] @ aux p2
148 | Below (p1, p2) -> aux p1 @ [NoBinding, symbol "\\BELOW"] @ aux p2
149 | Above (p1, p2) -> aux p1 @ [NoBinding, symbol "\\ABOVE"] @ aux p2
150 | Frac (p1, p2) -> aux p1 @ [NoBinding, symbol "\\FRAC"] @ aux p2
151 | Atop (p1, p2) -> aux p1 @ [NoBinding, symbol "\\ATOP"] @ aux p2
152 | Over (p1, p2) -> aux p1 @ [NoBinding, symbol "\\OVER"] @ aux p2
154 [NoBinding, symbol "\\ROOT"] @ aux p2 @ [NoBinding, symbol "\\OF"]
156 | Sqrt p -> [NoBinding, symbol "\\SQRT"] @ aux p
158 | Box (_, pl) -> List.flatten (List.map aux pl)
159 and aux_magic magic =
162 let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
163 let action (env_opt : CicNotationEnv.t option) (loc : location) =
165 | Some env -> List.map opt_binding_some env
166 | None -> List.map opt_binding_of_name p_names
168 [ Env (List.map opt_declaration p_names),
170 [ [ Gramext.Sopt (Gramext.srules [ p_atoms, p_action ]) ],
171 Gramext.action action ] ]
174 let p_bindings, p_atoms, p_names, p_action = inner_pattern p in
175 let env0 = List.map list_binding_of_name p_names in
176 let grow_env_entry env n v =
177 prerr_endline "grow_env_entry";
180 | (n', (ty, ListValue vl)) as entry ->
181 if n' = n then n', (ty, ListValue (v :: vl)) else entry
185 let grow_env env_i env =
186 prerr_endline "grow_env";
188 (fun env (n, (_, v)) -> grow_env_entry env n v)
191 let action (env_list : CicNotationEnv.t list) (loc : location) =
192 prerr_endline "list action";
193 List.fold_right grow_env env_list env0
197 | List0 (_, None) -> Gramext.Slist0 s
198 | List1 (_, None) -> Gramext.Slist1 s
199 | List0 (_, Some l) -> Gramext.Slist0sep (s, g_symbol_of_literal l)
200 | List1 (_, Some l) -> Gramext.Slist1sep (s, g_symbol_of_literal l)
203 [ Env (List.map list_declaration p_names),
205 [ [ g_symbol (Gramext.srules [ p_atoms, p_action ]) ],
206 Gramext.action action ] ]
210 | NumVar s -> [Binding (s, NumType), number ""]
211 | TermVar s -> [Binding (s, TermType), term]
212 | IdentVar s -> [Binding (s, StringType), ident ""]
213 | Ascription (p, s) -> assert false (* TODO *)
214 | FreshVar _ -> assert false
215 and inner_pattern p =
216 let p_bindings, p_atoms = List.split (aux p) in
217 let p_names = flatten_opt p_bindings in
218 let _ = prerr_endline ("inner names: " ^ String.concat " " (List.map fst p_names)) in
220 make_action (fun (env : CicNotationEnv.t) (loc : location) -> env)
223 p_bindings, p_atoms, p_names, action
227 let level_of_int precedence =
228 if precedence < min_precedence || precedence > max_precedence then
229 raise (Level_not_found precedence);
230 string_of_int precedence
232 type rule_id = Token.t Gramext.g_symbol list
234 let extend level1_pattern ?(precedence = default_precedence)
235 ?associativity action
237 let p_bindings, p_atoms =
238 List.split (extract_term_production level1_pattern)
240 let level = level_of_int precedence in
241 let p_names = flatten_opt p_bindings in
243 prerr_endline (string_of_int (List.length p_bindings));
245 [ Grammar.Entry.obj (l2_pattern: 'a Grammar.Entry.e),
246 Some (Gramext.Level level),
251 (fun (env: CicNotationEnv.t) (loc: location) -> (action env loc))
256 let delete atoms = Grammar.delete_rule l2_pattern atoms
260 let boxify = function
262 | l -> Layout (Box (H, l))
264 let fold_binder binder pt_names body =
265 let fold_cluster binder terms ty body =
267 (fun term body -> Binder (binder, (term, ty), body))
268 terms body (* terms are names: either Ident or FreshVar *)
271 (fun (names, ty) body -> fold_cluster binder names ty body)
274 let return_term loc term = AttributedTerm (`Loc loc, term)
276 let _ = (* create empty precedence level for "l2_pattern" *)
277 let mk_level_list first last =
278 let rec aux acc = function
279 | i when i < first -> acc
280 | i -> aux ((Some (string_of_int i), None, []) :: acc) (i - 1)
285 [ Grammar.Entry.obj (l2_pattern: 'a Grammar.Entry.e),
287 mk_level_list min_precedence max_precedence ]
290 GLOBAL: level1_pattern level2_pattern level3_term
292 notation interpretation
294 (* {{{ Grammar for concrete syntax patterns, notation level 1 *)
295 level1_pattern: [ [ p = l1_simple_pattern -> p ] ];
296 l1_pattern: [ [ p = LIST1 l1_simple_pattern -> p ] ];
298 [ s = SYMBOL -> `Symbol s
299 | k = KEYWORD -> `Keyword k
300 | n = NUMBER -> `Number n
303 sep: [ [ SYMBOL "\\SEP"; sep = literal -> sep ] ];
304 (* row_sep: [ [ SYMBOL "\\ROWSEP"; sep = literal -> sep ] ];
305 field_sep: [ [ SYMBOL "\\FIELDSEP"; sep = literal -> sep ] ]; *)
307 [ SYMBOL "\\LIST0"; p = l1_simple_pattern; sep = OPT sep -> List0 (p, sep)
308 | SYMBOL "\\LIST1"; p = l1_simple_pattern; sep = OPT sep -> List1 (p, sep)
309 | SYMBOL "\\OPT"; p = l1_simple_pattern -> Opt p
312 l1_pattern_variable: [
313 [ SYMBOL "\\TERM"; id = IDENT -> TermVar id
314 | SYMBOL "\\NUM"; id = IDENT -> NumVar id
315 | SYMBOL "\\IDENT"; id = IDENT -> IdentVar id
320 [ p1 = SELF; SYMBOL "\\SUB"; p2 = SELF ->
321 return_term loc (Layout (Sub (p1, p2)))
322 | p1 = SELF; SYMBOL "\\SUP"; p2 = SELF ->
323 return_term loc (Layout (Sup (p1, p2)))
324 | p1 = SELF; SYMBOL "\\BELOW"; p2 = SELF ->
325 return_term loc (Layout (Below (p1, p2)))
326 | p1 = SELF; SYMBOL "\\ABOVE"; p2 = SELF ->
327 return_term loc (Layout (Above (p1, p2)))
328 | p1 = SELF; SYMBOL "\\OVER"; p2 = SELF ->
329 return_term loc (Layout (Over (p1, p2)))
330 | p1 = SELF; SYMBOL "\\ATOP"; p2 = SELF ->
331 return_term loc (Layout (Atop (p1, p2)))
332 (* | SYMBOL "\\ARRAY"; p = SELF; csep = OPT field_sep; rsep = OPT row_sep ->
333 return_term loc (Array (p, csep, rsep)) *)
334 | SYMBOL "\\FRAC"; p1 = SELF; p2 = SELF ->
335 return_term loc (Layout (Frac (p1, p2)))
336 | SYMBOL "\\SQRT"; p = SELF -> return_term loc (Layout (Sqrt p))
337 | SYMBOL "\\ROOT"; index = SELF; SYMBOL "\\OF"; arg = SELF ->
338 return_term loc (Layout (Root (arg, index)));
339 | SYMBOL "\\HBOX"; DELIM "\\["; p = l1_pattern; DELIM "\\]" ->
340 return_term loc (Layout (Box (H, p)))
341 | SYMBOL "\\VBOX"; DELIM "\\["; p = l1_pattern; DELIM "\\]" ->
342 return_term loc (Layout (Box (V, p)))
343 | SYMBOL "\\BREAK" -> return_term loc (Layout Break)
344 | DELIM "\\["; p = l1_pattern; DELIM "\\]" ->
345 return_term loc (boxify p)
346 | p = SELF; SYMBOL "\\AS"; id = IDENT ->
347 return_term loc (Variable (Ascription (p, id)))
350 [ i = IDENT -> return_term loc (Ident (i, None))
351 | m = l1_magic_pattern -> return_term loc (Magic m)
352 | v = l1_pattern_variable -> return_term loc (Variable v)
353 | l = literal -> return_term loc (Literal l)
357 (* {{{ Grammar for ast patterns, notation level 2 *)
358 level2_pattern: [ [ p = l2_pattern -> p ] ];
360 [ SYMBOL "\\PROP" -> `Prop
361 | SYMBOL "\\SET" -> `Set
362 | SYMBOL "\\TYPE" -> `Type
366 [ SYMBOL "\\subst"; (* to avoid catching frequent "a [1]" cases *)
369 i = IDENT; SYMBOL <:unicode<Assign>> (* ≔ *); t = l2_pattern -> (i, t)
376 [ s = SYMBOL "_" -> None
377 | p = l2_pattern -> Some p ]
380 [ SYMBOL "["; substs = LIST0 meta_subst; SYMBOL "]" -> substs ]
382 possibly_typed_name: [
383 [ SYMBOL "("; id = bound_name; SYMBOL ":"; typ = l2_pattern; SYMBOL ")" ->
385 | id = bound_name -> id, None
389 [ id = IDENT -> id, []
390 | SYMBOL "("; id = IDENT; vars = LIST1 possibly_typed_name; SYMBOL ")" ->
395 [ SYMBOL <:unicode<Pi>> (* Π *) -> `Pi
396 | SYMBOL <:unicode<exists>> (* ∃ *) -> `Exists
397 | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall
398 | SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda
402 [ i = IDENT -> Ident (i, None)
403 | SYMBOL "\\FRESH"; i = IDENT -> Variable (FreshVar i)
407 [ vars = LIST1 bound_name SEP SYMBOL ",";
408 ty = OPT [ SYMBOL ":"; p = l2_pattern -> p ] ->
412 vars = LIST1 bound_name SEP SYMBOL ",";
413 ty = OPT [ SYMBOL ":"; p = l2_pattern -> p ];
421 [ IDENT "rec" -> `Inductive
422 | IDENT "corec" -> `CoInductive
427 name = bound_name; args = bound_names;
428 index_name = OPT [ IDENT "on"; id = bound_name -> id ];
429 ty = OPT [ SYMBOL ":" ; p = l2_pattern -> p ];
430 SYMBOL <:unicode<def>> (* ≝ *); body = l2_pattern ->
431 let body = fold_binder `Lambda args body in
435 | Some ty -> Some (fold_binder `Pi args ty)
437 let rec position_of name p = function
439 | n :: _ when n = name -> Some p, p
440 | _ :: tl -> position_of name (p + 1) tl
442 let rec find_arg name n = function
444 fail loc (sprintf "Argument %s not found"
445 (CicNotationPp.pp_term name))
447 (match position_of name 0 l with
448 | None, len -> find_arg name (n + len) tl
449 | Some where, len -> n + where)
452 match index_name with
454 | Some name -> find_arg name 0 args
456 (name, ty), body, index
461 l2_pattern_variable: [
462 [ SYMBOL "\\TERM"; id = IDENT -> TermVar id
463 | SYMBOL "\\NUM"; id = IDENT -> NumVar id
464 | SYMBOL "\\IDENT"; id = IDENT -> IdentVar id
465 | SYMBOL "\\FRESH"; id = IDENT -> FreshVar id
470 kind = [ IDENT "left" -> `Left | IDENT "right" -> `Right ];
471 DELIM "\\["; base = l2_pattern; DELIM "\\]";
472 SYMBOL "\\LAMBDA"; id = IDENT;
473 DELIM "\\["; recursive = l2_pattern; DELIM "\\]" ->
474 Fold (kind, base, [id], recursive)
475 | SYMBOL "\\DEFAULT";
476 DELIM "\\["; some = l2_pattern; DELIM "\\]";
477 DELIM "\\["; none = l2_pattern; DELIM "\\]" ->
481 l2_pattern: LEVEL "10" (* let in *)
483 [ IDENT "let"; var = possibly_typed_name; SYMBOL <:unicode<def>> (* ≝ *);
484 p1 = l2_pattern; "in"; p2 = l2_pattern ->
485 return_term loc (LetIn (var, p1, p2))
486 | IDENT "let"; k = induction_kind; defs = let_defs; IDENT "in";
488 return_term loc (LetRec (k, defs, body))
491 l2_pattern: LEVEL "20" (* binder *)
493 [ b = binder; names = bound_names; SYMBOL "."; body = l2_pattern ->
494 return_term loc (fold_binder b names body)
497 l2_pattern: LEVEL "70" (* apply *)
499 [ p1 = l2_pattern; p2 = l2_pattern ->
500 let rec aux = function
502 | AttributedTerm (_, Appl (hd :: tl)) ->
506 return_term loc (Appl (aux p1 @ [p2]))
509 l2_pattern: LEVEL "90" (* simple *)
511 [ id = IDENT -> return_term loc (Ident (id, None))
512 | id = IDENT; s = explicit_subst -> return_term loc (Ident (id, Some s))
513 | s = CSYMBOL -> return_term loc (Symbol (s, 0))
514 | u = URI -> return_term loc (Uri (u, None))
515 | n = NUMBER -> prerr_endline "number"; return_term loc (Num (n, 0))
516 | IMPLICIT -> return_term loc (Implicit)
517 | m = META -> return_term loc (Meta (int_of_string m, []))
518 | m = META; s = meta_substs -> return_term loc (Meta (int_of_string m, s))
519 | s = sort -> return_term loc (Sort s)
520 | outtyp = OPT [ SYMBOL "["; ty = l2_pattern; SYMBOL "]" -> ty ];
521 IDENT "match"; t = l2_pattern;
522 indty_ident = OPT [ SYMBOL ":"; id = IDENT -> id ];
523 IDENT "with"; SYMBOL "[";
525 lhs = match_pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *);
530 return_term loc (Case (t, indty_ident, outtyp, patterns))
531 | SYMBOL "("; p1 = l2_pattern; SYMBOL ":"; p2 = l2_pattern; SYMBOL ")" ->
532 return_term loc (Appl [ Symbol ("cast", 0); p1; p2 ])
533 | SYMBOL "("; p = l2_pattern; SYMBOL ")" -> p
534 | v = l2_pattern_variable -> return_term loc (Variable v)
535 | m = l2_magic_pattern -> return_term loc (Magic m)
539 (* {{{ Grammar for interpretation, notation level 3 *)
541 [ id = IDENT -> IdentArg id
542 | SYMBOL <:unicode<eta>> (* η *); SYMBOL "."; a = SELF -> EtaArg (None, a)
543 | SYMBOL <:unicode<eta>> (* η *); id = IDENT; SYMBOL "."; a = SELF ->
548 [ u = URI -> UriPattern u
549 | a = argument -> ArgPattern a
550 | SYMBOL "("; terms = LIST1 SELF; SYMBOL ")" ->
554 | terms -> ApplPattern terms)
558 (* {{{ Notation glues *)
560 [ IDENT "left"; IDENT "associative" -> Gramext.LeftA
561 | IDENT "right"; IDENT "associative" -> Gramext.RightA
562 | IDENT "non"; IDENT "associative" -> Gramext.NonA
566 [ IDENT "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
569 [ p1 = level1_pattern;
570 assoc = OPT associativity; prec = OPT precedence;
571 IDENT "for"; p2 = level2_pattern ->
572 (p1, assoc, prec, p2)
576 [ s = CSYMBOL; args = LIST1 argument; SYMBOL "="; t = level3_term ->
581 (* {{{ Top-level phrases *)
583 [ IDENT "print"; p2 = level2_pattern; SYMBOL "." -> Print p2
584 | IDENT "notation"; (l1, assoc, prec, l2) = notation; SYMBOL "." ->
585 Notation (l1, assoc, prec, l2)
586 | IDENT "interpretation"; (symbol, args, l3) = interpretation; SYMBOL "." ->
587 Interpretation ((symbol, args), l3)
588 | IDENT "render"; u = URI; SYMBOL "." -> Render (UriManager.uri_of_string u)
594 (** {2 API implementation} *)
596 let exc_located_wrapper f =
600 | Stdpp.Exc_located (floc, Stream.Error msg) ->
601 raise (Parse_error (floc, msg))
602 | Stdpp.Exc_located (floc, exn) ->
603 raise (Parse_error (floc, (Printexc.to_string exn)))
605 let parse_syntax_pattern stream =
606 exc_located_wrapper (fun () -> Grammar.Entry.parse level1_pattern stream)
607 let parse_ast_pattern stream =
608 exc_located_wrapper (fun () -> Grammar.Entry.parse level2_pattern stream)
609 let parse_interpretation stream =
610 exc_located_wrapper (fun () -> Grammar.Entry.parse level3_term stream)
611 let parse_phrase stream =
612 exc_located_wrapper (fun () -> Grammar.Entry.parse phrase stream)
616 let print_l2_pattern () =
617 Grammar.print_entry Format.std_formatter (Grammar.Entry.obj l2_pattern);
618 Format.pp_print_flush Format.std_formatter ();
621 (* vim:set encoding=utf8 foldmethod=marker: *)