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