]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_notation/grafiteParser.ml
- synced notation pretty printing with parsing syntax
[helm.git] / helm / ocaml / cic_notation / grafiteParser.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 open Printf
27
28 let grammar = CicNotationParser.level2_ast_grammar
29
30 let term = CicNotationParser.term
31 let statement = Grammar.Entry.create grammar "statement"
32
33 let add_raw_attribute ?context ~text term =
34   CicNotationPt.AttributedTerm (`Raw (text, context), term)
35
36 EXTEND
37   GLOBAL: term statement;
38   arg: [
39    [ LPAREN; names = LIST1 IDENT SEP SYMBOL ",";
40       SYMBOL ":"; ty = term; RPAREN -> names,ty
41    | name = IDENT -> [name],CicNotationPt.Implicit
42    ]
43   ];
44   constructor: [ [ name = IDENT; SYMBOL ":"; typ = term -> (name, typ) ] ];
45   tactic_term: [ [ t = term -> t ] ];
46   ident_list0: [
47     [ SYMBOL "["; idents = LIST0 IDENT SEP SYMBOL ";"; SYMBOL "]" -> idents ]
48   ];
49   tactic_term_list1: [
50     [ tactic_terms = LIST1 tactic_term SEP SYMBOL "," -> tactic_terms ]
51   ];
52   reduction_kind: [
53     [ IDENT "reduce" -> `Reduce
54     | IDENT "simplify" -> `Simpl
55     | IDENT "whd" -> `Whd 
56     | IDENT "normalize" -> `Normalize ]
57   ];
58   sequent_pattern_spec: [
59    [ hyp_paths =
60       LIST0
61        [ id = IDENT ;
62          path = OPT [SYMBOL ":" ; path = term -> path ] ->
63          (id,match path with Some p -> p | None -> CicNotationPt.UserInput) ]
64        SEP SYMBOL ";";
65      goal_path = OPT [ SYMBOL <:unicode<vdash>>; term = term -> term ] ->
66       let goal_path =
67        match goal_path with
68           None -> CicNotationPt.UserInput
69         | Some goal_path -> goal_path
70       in
71        hyp_paths,goal_path
72    ]
73   ];
74   pattern_spec: [
75     [ res = OPT [
76        "in";
77        wanted_and_sps =
78         [ "match" ; wanted = term ;
79           sps = OPT [ "in"; sps = sequent_pattern_spec -> sps ] ->
80            Some wanted,sps
81         | sps = sequent_pattern_spec ->
82            None,Some sps
83         ] ->
84          let wanted,hyp_paths,goal_path =
85           match wanted_and_sps with
86              wanted,None -> wanted, [], CicNotationPt.UserInput
87            | wanted,Some (hyp_paths,goal_path) -> wanted,hyp_paths,goal_path
88          in
89           wanted, hyp_paths, goal_path ] ->
90       match res with
91          None -> None,[],CicNotationPt.UserInput
92        | Some ps -> ps]
93   ];
94   direction: [
95     [ SYMBOL ">" -> `LeftToRight
96     | SYMBOL "<" -> `RightToLeft ]
97   ];
98   int: [ [ num = NUMBER -> int_of_string num ] ];
99   tactic: [
100     [ IDENT "absurd"; t = tactic_term ->
101         GrafiteAst.Absurd (loc, t)
102     | IDENT "apply"; t = tactic_term ->
103         GrafiteAst.Apply (loc, t)
104     | IDENT "assumption" ->
105         GrafiteAst.Assumption loc
106     | IDENT "auto";
107       depth = OPT [ IDENT "depth"; SYMBOL "="; i = int -> i ];
108       width = OPT [ IDENT "width"; SYMBOL "="; i = int -> i ] -> 
109           GrafiteAst.Auto (loc,depth,width)
110     | IDENT "clear"; id = IDENT ->
111         GrafiteAst.Clear (loc,id)
112     | IDENT "clearbody"; id = IDENT ->
113         GrafiteAst.ClearBody (loc,id)
114     | IDENT "change"; what = pattern_spec; "with"; t = tactic_term ->
115         GrafiteAst.Change (loc, what, t)
116     | IDENT "compare"; t = tactic_term ->
117         GrafiteAst.Compare (loc,t)
118     | IDENT "constructor"; n = int ->
119         GrafiteAst.Constructor (loc, n)
120     | IDENT "contradiction" ->
121         GrafiteAst.Contradiction loc
122     | IDENT "cut"; t = tactic_term; ident = OPT [ "as"; id = IDENT -> id] ->
123         GrafiteAst.Cut (loc, ident, t)
124     | IDENT "decide"; IDENT "equality" ->
125         GrafiteAst.DecideEquality loc
126     | IDENT "decompose"; where = tactic_term ->
127         GrafiteAst.Decompose (loc, where)
128     | IDENT "discriminate"; t = tactic_term ->
129         GrafiteAst.Discriminate (loc, t)
130     | IDENT "elim"; what = tactic_term;
131       using = OPT [ "using"; using = tactic_term -> using ];  
132       OPT "names"; num = OPT [num = int -> num];
133       idents = OPT ident_list0 ->
134         let idents = match idents with None -> [] | Some idents -> idents in
135         GrafiteAst.Elim (loc, what, using, num, idents)
136     | IDENT "elimType"; what = tactic_term;
137       using = OPT [ "using"; using = tactic_term -> using ];  
138       OPT "names"; num = OPT [num = int -> num]; idents = OPT ident_list0 ->
139         let idents = match idents with None -> [] | Some idents -> idents in
140         GrafiteAst.ElimType (loc, what, using, num, idents)
141     | IDENT "exact"; t = tactic_term ->
142         GrafiteAst.Exact (loc, t)
143     | IDENT "exists" ->
144         GrafiteAst.Exists loc
145     | IDENT "fail" -> GrafiteAst.Fail loc
146     | IDENT "fold"; kind = reduction_kind; t = tactic_term; p = pattern_spec ->
147         let (pt,_,_) = p in
148           if pt <> None then
149             raise (CicNotationParser.Parse_error
150               (loc, "the pattern cannot specify the term to replace, only its"
151               ^ " paths in the hypotheses and in the conclusion"))
152         else
153          GrafiteAst.Fold (loc, kind, t, p)
154     | IDENT "fourier" ->
155         GrafiteAst.Fourier loc
156     | IDENT "fwd"; hyp = IDENT; idents = OPT ident_list0 ->
157         let idents = match idents with None -> [] | Some idents -> idents in
158         GrafiteAst.FwdSimpl (loc, hyp, idents)
159     | IDENT "generalize"; p=pattern_spec; id = OPT ["as" ; id = IDENT -> id] ->
160        GrafiteAst.Generalize (loc,p,id)
161     | IDENT "goal"; n = int ->
162         GrafiteAst.Goal (loc, n)
163     | IDENT "id" -> GrafiteAst.IdTac loc
164     | IDENT "injection"; t = tactic_term ->
165         GrafiteAst.Injection (loc, t)
166     | IDENT "intro"; ident = OPT IDENT ->
167         let idents = match ident with None -> [] | Some id -> [id] in
168         GrafiteAst.Intros (loc, Some 1, idents)
169     | IDENT "intros"; num = OPT [num = int -> num]; idents = OPT ident_list0 ->
170         let idents = match idents with None -> [] | Some idents -> idents in
171         GrafiteAst.Intros (loc, num, idents)
172     | IDENT "lapply"; 
173       depth = OPT [ IDENT "depth"; SYMBOL "="; i = int -> i ];
174       what = tactic_term; 
175       to_what = OPT [ "to" ; t = tactic_term_list1 -> t ];
176       ident = OPT [ "using" ; ident = IDENT -> ident ] ->
177         let to_what = match to_what with None -> [] | Some to_what -> to_what in
178         GrafiteAst.LApply (loc, depth, to_what, what, ident)
179     | IDENT "left" -> GrafiteAst.Left loc
180     | IDENT "letin"; where = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term ->
181         GrafiteAst.LetIn (loc, t, where)
182     | kind = reduction_kind; p = pattern_spec ->
183         GrafiteAst.Reduce (loc, kind, p)
184     | IDENT "reflexivity" ->
185         GrafiteAst.Reflexivity loc
186     | IDENT "replace"; p = pattern_spec; "with"; t = tactic_term ->
187         GrafiteAst.Replace (loc, p, t)
188     | IDENT "rewrite" ; d = direction; t = tactic_term ; p = pattern_spec ->
189        let (pt,_,_) = p in
190         if pt <> None then
191          raise
192           (CicNotationParser.Parse_error
193             (loc,"the pattern cannot specify the term to rewrite, only its paths in the hypotheses and in the conclusion"))
194         else
195          GrafiteAst.Rewrite (loc, d, t, p)
196     | IDENT "right" ->
197         GrafiteAst.Right loc
198     | IDENT "ring" ->
199         GrafiteAst.Ring loc
200     | IDENT "split" ->
201         GrafiteAst.Split loc
202     | IDENT "symmetry" ->
203         GrafiteAst.Symmetry loc
204     | IDENT "transitivity"; t = tactic_term ->
205         GrafiteAst.Transitivity (loc, t)
206     ]
207   ];
208   tactical:
209     [ "sequence" LEFTA
210       [ tacticals = LIST1 NEXT SEP SYMBOL ";" ->
211          match tacticals with
212             [] -> assert false
213           | [tac] -> tac
214           | l -> GrafiteAst.Seq (loc, l)
215       ]
216     | "then" NONA
217       [ tac = tactical; SYMBOL ";";
218         SYMBOL "["; tacs = LIST0 tactical SEP SYMBOL "|"; SYMBOL "]" ->
219           (GrafiteAst.Then (loc, tac, tacs))
220       ]
221     | "loops" RIGHTA
222       [ IDENT "do"; count = int; tac = tactical ->
223           GrafiteAst.Do (loc, count, tac)
224       | IDENT "repeat"; tac = tactical ->
225           GrafiteAst.Repeat (loc, tac)
226       ]
227     | "simple" NONA
228       [ IDENT "first";
229         SYMBOL "["; tacs = LIST0 tactical SEP SYMBOL "|"; SYMBOL "]" ->
230           GrafiteAst.First (loc, tacs)
231       | IDENT "try"; tac = NEXT ->
232           GrafiteAst.Try (loc, tac)
233       | IDENT "solve";
234         SYMBOL "["; tacs = LIST0 tactical SEP SYMBOL "|"; SYMBOL "]" ->
235           GrafiteAst.Solve (loc, tacs)
236       | LPAREN; tac = tactical; RPAREN -> tac
237       | tac = tactic -> GrafiteAst.Tactic (loc, tac)
238       ]
239     ];
240   theorem_flavour: [
241     [ [ IDENT "definition"  ] -> `Definition
242     | [ IDENT "fact"        ] -> `Fact
243     | [ IDENT "lemma"       ] -> `Lemma
244     | [ IDENT "remark"      ] -> `Remark
245     | [ IDENT "theorem"     ] -> `Theorem
246     ]
247   ];
248   inductive_spec: [ [
249     fst_name = IDENT; params = LIST0 [ arg=arg -> arg ];
250     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
251     fst_constructors = LIST0 constructor SEP SYMBOL "|";
252     tl = OPT [ "with";
253       types = LIST1 [
254         name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
255        OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
256           (name, true, typ, constructors) ] SEP "with" -> types
257     ] ->
258       let params =
259         List.fold_right
260           (fun (names, typ) acc ->
261             (List.map (fun name -> (name, typ)) names) @ acc)
262           params []
263       in
264       let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
265       let tl_ind_types = match tl with None -> [] | Some types -> types in
266       let ind_types = fst_ind_type :: tl_ind_types in
267       (params, ind_types)
268   ] ];
269   
270   record_spec: [ [
271     name = IDENT; params = LIST0 [ arg = arg -> arg ] ;
272      SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; SYMBOL "{" ; 
273      fields = LIST0 [ 
274        name = IDENT ; SYMBOL ":" ; ty = term -> (name,ty) 
275      ] SEP SYMBOL ";"; SYMBOL "}" -> 
276       let params =
277         List.fold_right
278           (fun (names, typ) acc ->
279             (List.map (fun name -> (name, typ)) names) @ acc)
280           params []
281       in
282       (params,name,typ,fields)
283   ] ];
284   
285   macro: [
286     [ [ IDENT "quit"  ] -> GrafiteAst.Quit loc
287 (*     | [ IDENT "abort" ] -> GrafiteAst.Abort loc *)
288     | [ IDENT "print" ]; name = QSTRING -> GrafiteAst.Print (loc, name)
289 (*     | [ IDENT "undo"   ]; steps = OPT NUMBER ->
290         GrafiteAst.Undo (loc, int_opt steps)
291     | [ IDENT "redo"   ]; steps = OPT NUMBER ->
292         GrafiteAst.Redo (loc, int_opt steps) *)
293     | [ IDENT "check"   ]; t = term ->
294         GrafiteAst.Check (loc, t)
295     | [ IDENT "hint" ] -> GrafiteAst.Hint loc
296     | [ IDENT "whelp"; "match" ] ; t = term -> 
297         GrafiteAst.WMatch (loc,t)
298     | [ IDENT "whelp"; IDENT "instance" ] ; t = term -> 
299         GrafiteAst.WInstance (loc,t)
300     | [ IDENT "whelp"; IDENT "locate" ] ; id = IDENT -> 
301         GrafiteAst.WLocate (loc,id)
302     | [ IDENT "whelp"; IDENT "elim" ] ; t = term ->
303         GrafiteAst.WElim (loc, t)
304     | [ IDENT "whelp"; IDENT "hint" ] ; t = term -> 
305         GrafiteAst.WHint (loc,t)
306     | [ IDENT "print" ]; name = QSTRING -> GrafiteAst.Print (loc, name)
307     ]
308   ];
309   alias_spec: [
310     [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
311       let alpha = "[a-zA-Z]" in
312       let num = "[0-9]+" in
313       let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
314       let ident = "\\("^alpha^ident_cont^"*\\|_"^ident_cont^"+\\)" in
315       let rex = Str.regexp ("^"^ident^"$") in
316       if Str.string_match rex id 0 then
317         if (try ignore (UriManager.uri_of_string uri); true
318             with UriManager.IllFormedUri _ -> false)
319         then
320           GrafiteAst.Ident_alias (id, uri)
321         else 
322           raise (CicNotationParser.Parse_error (loc,sprintf "Not a valid uri: %s" uri))
323       else
324         raise (CicNotationParser.Parse_error (loc,
325           sprintf "Not a valid identifier: %s" id))
326     | IDENT "symbol"; symbol = QSTRING;
327       instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
328       SYMBOL "="; dsc = QSTRING ->
329         let instance =
330           match instance with Some i -> i | None -> 0
331         in
332         GrafiteAst.Symbol_alias (symbol, instance, dsc)
333     | IDENT "num";
334       instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
335       SYMBOL "="; dsc = QSTRING ->
336         let instance =
337           match instance with Some i -> i | None -> 0
338         in
339         GrafiteAst.Number_alias (instance, dsc)
340     ]
341   ];
342   argument: [
343     [ id = IDENT -> CicNotationPt.IdentArg (0, id)
344     | l = LIST1 [ SYMBOL <:unicode<eta>> (* η *) -> () ] SEP SYMBOL ".";
345       SYMBOL "."; id = IDENT ->
346         CicNotationPt.IdentArg (List.length l, id)
347     ]
348   ];
349   associativity: [
350     [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
351     | IDENT "right"; IDENT "associative" -> Gramext.RightA
352     | IDENT "non"; IDENT "associative" -> Gramext.NonA
353     ]
354   ];
355   precedence: [
356     [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
357   ];
358   notation: [
359     [ s = QSTRING;
360       assoc = OPT associativity; prec = OPT precedence;
361       IDENT "for";
362       p2 = 
363         [ blob = UNPARSED_AST ->
364             add_raw_attribute ~context:`Ast ~text:blob
365               (CicNotationParser.parse_level2_ast (Stream.of_string blob))
366         | blob = UNPARSED_META ->
367             add_raw_attribute ~context:`Meta ~text:blob
368               (CicNotationParser.parse_level2_meta (Stream.of_string blob))
369         ] ->
370           (add_raw_attribute ~text:s
371             (CicNotationParser.parse_level1_pattern (Stream.of_string s)),
372            assoc, prec, p2)
373     ]
374   ];
375   level3_term: [
376     [ u = URI -> CicNotationPt.UriPattern (UriManager.uri_of_string u)
377     | id = IDENT -> CicNotationPt.VarPattern id
378     | SYMBOL "_" -> CicNotationPt.ImplicitPattern
379     | LPAREN; terms = LIST1 SELF; RPAREN ->
380         (match terms with
381         | [] -> assert false
382         | [term] -> term
383         | terms -> CicNotationPt.ApplPattern terms)
384     ]
385   ];
386   interpretation: [
387     [ s = CSYMBOL; args = LIST1 argument; SYMBOL "="; t = level3_term ->
388         (s, args, t)
389     ]
390   ];
391   command: [ [
392       IDENT "set"; n = QSTRING; v = QSTRING ->
393         GrafiteAst.Set (loc, n, v)
394     | IDENT "drop" -> GrafiteAst.Drop loc
395     | IDENT "qed" -> GrafiteAst.Qed loc
396     | IDENT "variant" ; name = IDENT; SYMBOL ":"; 
397       typ = term; SYMBOL <:unicode<def>> ; newname = IDENT ->
398         GrafiteAst.Obj (loc, 
399           GrafiteAst.Theorem 
400             (`Variant,name,typ,Some (CicNotationPt.Ident (newname, None))))
401     | flavour = theorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
402       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
403         GrafiteAst.Obj (loc,GrafiteAst.Theorem (flavour, name, typ, body))
404     | flavour = theorem_flavour; name = IDENT;
405       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
406         GrafiteAst.Obj (loc,
407           GrafiteAst.Theorem (flavour, name, CicNotationPt.Implicit, body))
408     | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
409         defs = CicNotationParser.let_defs -> 
410           let name,ty = 
411             match defs with
412             | ((CicNotationPt.Ident (name, None), Some ty),_,_) :: _ -> name,ty
413             | ((CicNotationPt.Ident (name, None), None),_,_) :: _ ->
414                 name, CicNotationPt.Implicit
415             | _ -> assert false 
416           in
417           let body = CicNotationPt.Ident (name,None) in
418           GrafiteAst.Obj (loc,GrafiteAst.Theorem(`Definition, name, ty,
419             Some (CicNotationPt.LetRec (ind_kind, defs, body))))
420     | [ IDENT "inductive" ]; spec = inductive_spec ->
421         let (params, ind_types) = spec in
422         GrafiteAst.Obj (loc,GrafiteAst.Inductive (params, ind_types))
423     | [ IDENT "coinductive" ]; spec = inductive_spec ->
424         let (params, ind_types) = spec in
425         let ind_types = (* set inductive flags to false (coinductive) *)
426           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
427             ind_types
428         in
429         GrafiteAst.Obj (loc,GrafiteAst.Inductive (params, ind_types))
430     | IDENT "coercion" ; name = IDENT -> 
431         GrafiteAst.Coercion (loc, CicNotationPt.Ident (name,Some []))
432     | IDENT "coercion" ; name = URI -> 
433         GrafiteAst.Coercion (loc, CicNotationPt.Uri (name,Some []))
434     | IDENT "alias" ; spec = alias_spec ->
435         GrafiteAst.Alias (loc, spec)
436     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
437         GrafiteAst.Obj (loc,GrafiteAst.Record (params,name,ty,fields))
438     | IDENT "include" ; path = QSTRING ->
439         GrafiteAst.Include (loc,path)
440     | IDENT "default" ; what = QSTRING ; uris = LIST1 URI ->
441        let uris = List.map UriManager.uri_of_string uris in
442         GrafiteAst.Default (loc,what,uris)
443     | IDENT "notation"; (l1, assoc, prec, l2) = notation ->
444         GrafiteAst.Notation (loc, l1, assoc, prec, l2)
445     | IDENT "interpretation"; id = QSTRING;
446       (symbol, args, l3) = interpretation ->
447         GrafiteAst.Interpretation (loc, id, (symbol, args), l3)
448
449     | IDENT "dump" -> GrafiteAst.Dump loc
450     | IDENT "render"; u = URI ->
451         GrafiteAst.Render (loc, UriManager.uri_of_string u)
452   ]];
453   executable: [
454     [ cmd = command; SYMBOL "." -> GrafiteAst.Command (loc, cmd)
455     | tac = tactical; SYMBOL "." -> GrafiteAst.Tactical (loc, tac)
456     | mac = macro; SYMBOL "." -> GrafiteAst.Macro (loc, mac)
457     ]
458   ];
459   comment: [
460     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
461        GrafiteAst.Code (loc, ex)
462     | str = NOTE -> 
463        GrafiteAst.Note (loc, str)
464     ]
465   ];
466   statement: [
467     [ ex = executable -> GrafiteAst.Executable (loc,ex)
468     | com = comment -> GrafiteAst.Comment (loc, com)
469     | EOI -> raise End_of_file
470     ]
471   ];
472 END
473
474 let exc_located_wrapper f =
475   try
476     f ()
477   with
478   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
479   | Stdpp.Exc_located (floc, Stream.Error msg) ->
480       raise (CicNotationParser.Parse_error (floc, msg))
481   | Stdpp.Exc_located (floc, exn) ->
482       raise (CicNotationParser.Parse_error (floc, (Printexc.to_string exn)))
483
484 let parse_statement stream =
485   exc_located_wrapper (fun () -> (Grammar.Entry.parse statement stream))
486