]> matita.cs.unibo.it Git - helm.git/blob - components/grafite_parser/grafiteParser.ml
we started the infrastructure for the procedural rendering of proofs
[helm.git] / components / grafite_parser / 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 (* $Id$ *)
27
28 open Printf
29
30 module Ast = CicNotationPt
31
32 type 'a localized_option =
33    LSome of 'a
34  | LNone of GrafiteAst.loc
35
36 type ast_statement =
37   (CicNotationPt.term, CicNotationPt.term,
38    CicNotationPt.term GrafiteAst.reduction, CicNotationPt.obj, string)
39     GrafiteAst.statement
40
41 type statement =
42   include_paths:string list ->
43   LexiconEngine.status ->
44     LexiconEngine.status * ast_statement localized_option
45
46 let grammar = CicNotationParser.level2_ast_grammar
47
48 let term = CicNotationParser.term
49 let statement = Grammar.Entry.create grammar "statement"
50
51 let add_raw_attribute ~text t = Ast.AttributedTerm (`Raw text, t)
52
53 let default_precedence = 50
54 let default_associativity = Gramext.NonA
55
56 type by_continuation =
57    BYC_done
58  | BYC_weproved of CicNotationPt.term * string option * CicNotationPt.term option
59  | BYC_letsuchthat of string * CicNotationPt.term * string * CicNotationPt.term
60  | BYC_wehaveand of string * CicNotationPt.term * string * CicNotationPt.term
61
62 EXTEND
63   GLOBAL: term statement;
64   constructor: [ [ name = IDENT; SYMBOL ":"; typ = term -> (name, typ) ] ];
65   tactic_term: [ [ t = term LEVEL "90N" -> t ] ];
66   ident_list0: [ [ LPAREN; idents = LIST0 IDENT; RPAREN -> idents ] ];
67   tactic_term_list1: [
68     [ tactic_terms = LIST1 tactic_term SEP SYMBOL "," -> tactic_terms ]
69   ];
70   reduction_kind: [
71     [ IDENT "normalize" -> `Normalize
72     | IDENT "reduce" -> `Reduce
73     | IDENT "simplify" -> `Simpl
74     | IDENT "unfold"; t = OPT tactic_term -> `Unfold t
75     | IDENT "whd" -> `Whd ]
76   ];
77   sequent_pattern_spec: [
78    [ hyp_paths =
79       LIST0
80        [ id = IDENT ;
81          path = OPT [SYMBOL ":" ; path = tactic_term -> path ] ->
82          (id,match path with Some p -> p | None -> Ast.UserInput) ];
83      goal_path = OPT [ SYMBOL <:unicode<vdash>>; term = tactic_term -> term ] ->
84       let goal_path =
85        match goal_path, hyp_paths with
86           None, [] -> Some Ast.UserInput
87         | None, _::_ -> None
88         | Some goal_path, _ -> Some goal_path
89       in
90        hyp_paths,goal_path
91    ]
92   ];
93   pattern_spec: [
94     [ res = OPT [
95        "in";
96        wanted_and_sps =
97         [ "match" ; wanted = tactic_term ;
98           sps = OPT [ "in"; sps = sequent_pattern_spec -> sps ] ->
99            Some wanted,sps
100         | sps = sequent_pattern_spec ->
101            None,Some sps
102         ] ->
103          let wanted,hyp_paths,goal_path =
104           match wanted_and_sps with
105              wanted,None -> wanted, [], Some Ast.UserInput
106            | wanted,Some (hyp_paths,goal_path) -> wanted,hyp_paths,goal_path
107          in
108           wanted, hyp_paths, goal_path ] ->
109       match res with
110          None -> None,[],Some Ast.UserInput
111        | Some ps -> ps]
112   ];
113   direction: [
114     [ SYMBOL ">" -> `LeftToRight
115     | SYMBOL "<" -> `RightToLeft ]
116   ];
117   int: [ [ num = NUMBER -> int_of_string num ] ];
118   intros_spec: [
119     [ num = OPT [ num = int -> num ]; idents = OPT ident_list0 ->
120         let idents = match idents with None -> [] | Some idents -> idents in
121         num, idents
122     ]
123   ];
124   using: [ [ using = OPT [ IDENT "using"; t = tactic_term -> t ] -> using ] ];
125   tactic: [
126     [ IDENT "absurd"; t = tactic_term ->
127         GrafiteAst.Absurd (loc, t)
128     | IDENT "apply"; t = tactic_term ->
129         GrafiteAst.Apply (loc, t)
130     | IDENT "applyS"; t = tactic_term ; params = 
131         LIST0 [ i = IDENT -> i,"" | i = IDENT ; SYMBOL "="; v = [ v = int ->
132           string_of_int v | v = IDENT -> v ] -> i,v ] ->
133         GrafiteAst.ApplyS (loc, t, params)
134     | IDENT "assumption" ->
135         GrafiteAst.Assumption loc
136     | IDENT "auto"; params = auto_params ->
137         GrafiteAst.Auto (loc,params)
138     | IDENT "clear"; ids = LIST1 IDENT ->
139         GrafiteAst.Clear (loc, ids)
140     | IDENT "clearbody"; id = IDENT ->
141         GrafiteAst.ClearBody (loc,id)
142     | IDENT "change"; what = pattern_spec; "with"; t = tactic_term ->
143         GrafiteAst.Change (loc, what, t)
144     | IDENT "constructor"; n = int ->
145         GrafiteAst.Constructor (loc, n)
146     | IDENT "contradiction" ->
147         GrafiteAst.Contradiction loc
148     | IDENT "cut"; t = tactic_term; ident = OPT [ "as"; id = IDENT -> id] ->
149         GrafiteAst.Cut (loc, ident, t)
150     | IDENT "decompose"; types = OPT ident_list0; what = OPT IDENT;
151         idents = OPT [ "as"; idents = LIST1 IDENT -> idents ] ->
152         let types = match types with None -> [] | Some types -> types in
153         let idents = match idents with None -> [] | Some idents -> idents in
154         let to_spec id = GrafiteAst.Ident id in
155         GrafiteAst.Decompose (loc, List.rev_map to_spec types, what, idents)
156     | IDENT "demodulate" -> GrafiteAst.Demodulate loc
157     | IDENT "destruct"; t = tactic_term ->
158         GrafiteAst.Destruct (loc, t)
159     | IDENT "elim"; what = tactic_term; using = using;
160       (num, idents) = intros_spec ->
161         GrafiteAst.Elim (loc, what, using, num, idents)
162     | IDENT "elimType"; what = tactic_term; using = using;
163       (num, idents) = intros_spec ->
164         GrafiteAst.ElimType (loc, what, using, num, idents)
165     | IDENT "exact"; t = tactic_term ->
166         GrafiteAst.Exact (loc, t)
167     | IDENT "exists" ->
168         GrafiteAst.Exists loc
169     | IDENT "fail" -> GrafiteAst.Fail loc
170     | IDENT "fold"; kind = reduction_kind; t = tactic_term; p = pattern_spec ->
171         let (pt,_,_) = p in
172           if pt <> None then
173             raise (HExtlib.Localized (loc, CicNotationParser.Parse_error
174               ("the pattern cannot specify the term to replace, only its"
175               ^ " paths in the hypotheses and in the conclusion")))
176         else
177          GrafiteAst.Fold (loc, kind, t, p)
178     | IDENT "fourier" ->
179         GrafiteAst.Fourier loc
180     | IDENT "fwd"; hyp = IDENT; idents = OPT [ "as"; idents = LIST1 IDENT -> idents ] ->
181         let idents = match idents with None -> [] | Some idents -> idents in
182         GrafiteAst.FwdSimpl (loc, hyp, idents)
183     | IDENT "generalize"; p=pattern_spec; id = OPT ["as" ; id = IDENT -> id] ->
184        GrafiteAst.Generalize (loc,p,id)
185     | IDENT "goal"; n = int ->
186         GrafiteAst.Goal (loc, n)
187     | IDENT "id" -> GrafiteAst.IdTac loc
188     | IDENT "intro"; ident = OPT IDENT ->
189         let idents = match ident with None -> [] | Some id -> [id] in
190         GrafiteAst.Intros (loc, Some 1, idents)
191     | IDENT "intros"; (num, idents) = intros_spec ->
192         GrafiteAst.Intros (loc, num, idents)
193     | IDENT "inversion"; t = tactic_term ->
194         GrafiteAst.Inversion (loc, t)
195     | IDENT "lapply"; 
196       linear = OPT [ IDENT "linear" ];
197       depth = OPT [ IDENT "depth"; SYMBOL "="; i = int -> i ];
198       what = tactic_term; 
199       to_what = OPT [ "to" ; t = tactic_term_list1 -> t ];
200       ident = OPT [ "as" ; ident = IDENT -> ident ] ->
201         let linear = match linear with None -> false | Some _ -> true in 
202         let to_what = match to_what with None -> [] | Some to_what -> to_what in
203         GrafiteAst.LApply (loc, linear, depth, to_what, what, ident)
204     | IDENT "left" -> GrafiteAst.Left loc
205     | IDENT "letin"; where = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term ->
206         GrafiteAst.LetIn (loc, t, where)
207     | kind = reduction_kind; p = pattern_spec ->
208         GrafiteAst.Reduce (loc, kind, p)
209     | IDENT "reflexivity" ->
210         GrafiteAst.Reflexivity loc
211     | IDENT "replace"; p = pattern_spec; "with"; t = tactic_term ->
212         GrafiteAst.Replace (loc, p, t)
213     | IDENT "rewrite" ; d = direction; t = tactic_term ; p = pattern_spec ->
214        let (pt,_,_) = p in
215         if pt <> None then
216          raise
217           (HExtlib.Localized (loc,
218            (CicNotationParser.Parse_error
219             "the pattern cannot specify the term to rewrite, only its paths in the hypotheses and in the conclusion")))
220         else
221          GrafiteAst.Rewrite (loc, d, t, p)
222     | IDENT "right" ->
223         GrafiteAst.Right loc
224     | IDENT "ring" ->
225         GrafiteAst.Ring loc
226     | IDENT "split" ->
227         GrafiteAst.Split loc
228     | IDENT "subst" ->
229         GrafiteAst.Subst loc    
230     | IDENT "symmetry" ->
231         GrafiteAst.Symmetry loc
232     | IDENT "transitivity"; t = tactic_term ->
233         GrafiteAst.Transitivity (loc, t)
234      (* Produzioni Aggiunte *)
235     | IDENT "assume" ; id = IDENT ; SYMBOL ":" ; t = tactic_term ->
236         GrafiteAst.Assume (loc, id, t)
237     | IDENT "suppose" ; t = tactic_term ; LPAREN ; id = IDENT ; RPAREN ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t' = tactic_term -> t']->
238         GrafiteAst.Suppose (loc, t, id, t1)
239     | IDENT "by" ; t = [t' = tactic_term -> LSome t' | SYMBOL "_" -> LNone loc];
240       cont=by_continuation ->
241        let t' = match t with LNone _ -> None | LSome t -> Some t in
242        (match cont with
243            BYC_done -> GrafiteAst.Bydone (loc, t')
244          | BYC_weproved (ty,id,t1) ->
245             GrafiteAst.By_term_we_proved(loc, t', ty, id, t1)
246          | BYC_letsuchthat (id1,t1,id2,t2) ->
247             (match t with
248                 LNone floc ->
249                  raise (HExtlib.Localized
250                   (floc,CicNotationParser.Parse_error
251                     "tactic_term expected here"))
252               | LSome t -> GrafiteAst.ExistsElim (loc, t, id1, t1, id2, t2))
253          | BYC_wehaveand (id1,t1,id2,t2) ->
254             (match t with
255                 LNone floc ->
256                  raise (HExtlib.Localized
257                   (floc,CicNotationParser.Parse_error
258                     "tactic_term expected here"))
259               | LSome t -> GrafiteAst.AndElim (loc, t, id1, t1, id2, t2)))
260     | IDENT "we" ; IDENT "need" ; "to" ; IDENT "prove" ; t = tactic_term ; id = OPT [ LPAREN ; id = IDENT ; RPAREN -> id ] ; t1 = OPT [IDENT "or" ; IDENT "equivalently"; t' = tactic_term -> t']->
261         GrafiteAst.We_need_to_prove (loc, t, id, t1)
262     | IDENT "we" ; IDENT "proceed" ; IDENT "by" ; IDENT "induction" ; "on" ; t=tactic_term ; "to" ; IDENT "prove" ; t1=tactic_term ->  
263         GrafiteAst.We_proceed_by_induction_on (loc, t, t1)
264     | IDENT "by" ; IDENT "induction" ; IDENT "hypothesis" ; IDENT "we" ; IDENT "know" ; t=tactic_term ; LPAREN ; id = IDENT ; RPAREN ->
265         GrafiteAst.Byinduction(loc, t, id)
266     | IDENT "the" ; IDENT "thesis" ; IDENT "becomes" ; t=tactic_term ->
267         GrafiteAst.Thesisbecomes(loc, t)
268     | IDENT "case" ; id = IDENT ; params=LIST0[LPAREN ; i=IDENT ;
269         SYMBOL":" ; t=tactic_term ; RPAREN -> i,t] ->
270          GrafiteAst.Case(loc,id,params)
271     | start=[IDENT "conclude" -> None | IDENT "obtain" ; name = IDENT -> Some name] ; termine=tactic_term ; SYMBOL "=" ; t1=tactic_term ; IDENT "by" ; t2=[ t=tactic_term -> `Term t | SYMBOL "_" ; params = auto_params' -> `Auto params  ] ; cont=rewriting_step_continuation ->
272      GrafiteAst.RewritingStep(loc, Some (start,termine), t1, t2, cont)
273     | SYMBOL "=" ; t1=tactic_term ; IDENT "by" ; t2=[ t=tactic_term -> `Term t | SYMBOL "_" ; params = auto_params' -> `Auto params ] ;
274       cont=rewriting_step_continuation  ->
275      GrafiteAst.RewritingStep(loc, None, t1, t2, cont)
276   ]
277 ];
278   auto_params: [
279    [ params =
280       LIST0 [ i = IDENT -> i,"" | i = IDENT ; SYMBOL "="; v = [ v = int ->
281        string_of_int v | v = IDENT -> v ] -> i,v ] ->
282       params
283    ]
284 ];
285   auto_params': [
286    [ LPAREN; params = auto_params; RPAREN -> params
287    | -> []
288    ]
289 ];
290   by_continuation: [
291     [ IDENT "we" ; IDENT "proved" ; ty = tactic_term ; LPAREN ; id = IDENT ; RPAREN ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t2 = tactic_term -> t2] -> BYC_weproved (ty,Some id,t1)
292     | IDENT "we" ; IDENT "proved" ; ty = tactic_term ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t2 = tactic_term -> t2] ; 
293             IDENT "done" -> BYC_weproved (ty,None,t1)
294     | IDENT "done" -> BYC_done
295     | "let" ; id1 = IDENT ; SYMBOL ":" ; t1 = tactic_term ;
296       IDENT "such" ; IDENT "that" ; t2=tactic_term ; LPAREN ; id2 = IDENT ; RPAREN -> BYC_letsuchthat (id1,t1,id2,t2)
297     | IDENT "we" ; IDENT "have" ; t1=tactic_term ; LPAREN ; id1=IDENT ; RPAREN ;"and" ; t2=tactic_term ; LPAREN ; id2=IDENT ; RPAREN ->
298               BYC_wehaveand (id1,t1,id2,t2)
299     ]
300 ];
301   rewriting_step_continuation : [
302     [ IDENT "done" -> true
303     | -> false
304     ]
305 ];
306   atomic_tactical:
307     [ "sequence" LEFTA
308       [ t1 = SELF; SYMBOL ";"; t2 = SELF ->
309           let ts =
310             match t1 with
311             | GrafiteAst.Seq (_, l) -> l @ [ t2 ]
312             | _ -> [ t1; t2 ]
313           in
314           GrafiteAst.Seq (loc, ts)
315       ]
316     | "then" NONA
317       [ tac = SELF; SYMBOL ";";
318         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
319           (GrafiteAst.Then (loc, tac, tacs))
320       ]
321     | "loops" RIGHTA
322       [ IDENT "do"; count = int; tac = SELF; IDENT "end" ->
323           GrafiteAst.Do (loc, count, tac)
324       | IDENT "repeat"; tac = SELF; IDENT "end" -> GrafiteAst.Repeat (loc, tac)
325       ]
326     | "simple" NONA
327       [ IDENT "first";
328         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
329           GrafiteAst.First (loc, tacs)
330       | IDENT "try"; tac = SELF -> GrafiteAst.Try (loc, tac)
331       | IDENT "solve";
332         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
333           GrafiteAst.Solve (loc, tacs)
334       | IDENT "progress"; tac = SELF -> GrafiteAst.Progress (loc, tac)
335       | LPAREN; tac = SELF; RPAREN -> tac
336       | tac = tactic -> GrafiteAst.Tactic (loc, tac)
337       ]
338     ];
339   punctuation_tactical:
340     [
341       [ SYMBOL "[" -> GrafiteAst.Branch loc
342       | SYMBOL "|" -> GrafiteAst.Shift loc
343       | i = LIST1 int SEP SYMBOL ","; SYMBOL ":" -> GrafiteAst.Pos (loc, i)
344       | SYMBOL "*"; SYMBOL ":" -> GrafiteAst.Wildcard loc
345       | SYMBOL "]" -> GrafiteAst.Merge loc
346       | SYMBOL ";" -> GrafiteAst.Semicolon loc
347       | SYMBOL "." -> GrafiteAst.Dot loc
348       ]
349     ];
350   tactical:
351     [ "simple" NONA
352       [ IDENT "focus"; goals = LIST1 int -> GrafiteAst.Focus (loc, goals)
353       | IDENT "unfocus" -> GrafiteAst.Unfocus loc
354       | IDENT "skip" -> GrafiteAst.Skip loc
355       | tac = atomic_tactical LEVEL "loops" -> tac
356       ]
357     ];
358   theorem_flavour: [
359     [ [ IDENT "definition"  ] -> `Definition
360     | [ IDENT "fact"        ] -> `Fact
361     | [ IDENT "lemma"       ] -> `Lemma
362     | [ IDENT "remark"      ] -> `Remark
363     | [ IDENT "theorem"     ] -> `Theorem
364     ]
365   ];
366   inductive_spec: [ [
367     fst_name = IDENT; params = LIST0 CicNotationParser.protected_binder_vars;
368     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
369     fst_constructors = LIST0 constructor SEP SYMBOL "|";
370     tl = OPT [ "with";
371       types = LIST1 [
372         name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
373        OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
374           (name, true, typ, constructors) ] SEP "with" -> types
375     ] ->
376       let params =
377         List.fold_right
378           (fun (names, typ) acc ->
379             (List.map (fun name -> (name, typ)) names) @ acc)
380           params []
381       in
382       let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
383       let tl_ind_types = match tl with None -> [] | Some types -> types in
384       let ind_types = fst_ind_type :: tl_ind_types in
385       (params, ind_types)
386   ] ];
387   
388   record_spec: [ [
389     name = IDENT; params = LIST0 CicNotationParser.protected_binder_vars ;
390      SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; SYMBOL "{" ; 
391      fields = LIST0 [ 
392        name = IDENT ; 
393        coercion = [ 
394            SYMBOL ":" -> false,0 
395          | SYMBOL ":"; SYMBOL ">" -> true,0
396          | SYMBOL ":"; arity = int ; SYMBOL ">" -> true,arity
397        ]; 
398        ty = term -> 
399          let b,n = coercion in 
400          (name,ty,b,n) 
401      ] SEP SYMBOL ";"; SYMBOL "}" -> 
402       let params =
403         List.fold_right
404           (fun (names, typ) acc ->
405             (List.map (fun name -> (name, typ)) names) @ acc)
406           params []
407       in
408       (params,name,typ,fields)
409   ] ];
410   
411   macro: [
412     [ [ IDENT "check"   ]; t = term ->
413         GrafiteAst.Check (loc, t)
414     | [ IDENT "inline"]; 
415         style = OPT [ IDENT "procedural" ];
416         suri = QSTRING; prefix = OPT QSTRING ->
417          let style = match style with 
418             | None   -> GrafiteAst.Declarative
419             | Some _ -> GrafiteAst.Procedural
420          in
421          let prefix = match prefix with None -> "" | Some prefix -> prefix in
422          GrafiteAst.Inline (loc,style,suri,prefix)
423     | [ IDENT "hint" ] -> GrafiteAst.Hint loc
424     | [ IDENT "whelp"; "match" ] ; t = term -> 
425         GrafiteAst.WMatch (loc,t)
426     | [ IDENT "whelp"; IDENT "instance" ] ; t = term -> 
427         GrafiteAst.WInstance (loc,t)
428     | [ IDENT "whelp"; IDENT "locate" ] ; id = QSTRING -> 
429         GrafiteAst.WLocate (loc,id)
430     | [ IDENT "whelp"; IDENT "elim" ] ; t = term ->
431         GrafiteAst.WElim (loc, t)
432     | [ IDENT "whelp"; IDENT "hint" ] ; t = term -> 
433         GrafiteAst.WHint (loc,t)
434     ]
435   ];
436   alias_spec: [
437     [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
438       let alpha = "[a-zA-Z]" in
439       let num = "[0-9]+" in
440       let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
441       let ident = "\\("^alpha^ident_cont^"*\\|_"^ident_cont^"+\\)" in
442       let rex = Str.regexp ("^"^ident^"$") in
443       if Str.string_match rex id 0 then
444         if (try ignore (UriManager.uri_of_string uri); true
445             with UriManager.IllFormedUri _ -> false)
446         then
447           LexiconAst.Ident_alias (id, uri)
448         else 
449           raise
450            (HExtlib.Localized (loc, CicNotationParser.Parse_error (sprintf "Not a valid uri: %s" uri)))
451       else
452         raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
453           sprintf "Not a valid identifier: %s" id)))
454     | IDENT "symbol"; symbol = QSTRING;
455       instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
456       SYMBOL "="; dsc = QSTRING ->
457         let instance =
458           match instance with Some i -> i | None -> 0
459         in
460         LexiconAst.Symbol_alias (symbol, instance, dsc)
461     | IDENT "num";
462       instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
463       SYMBOL "="; dsc = QSTRING ->
464         let instance =
465           match instance with Some i -> i | None -> 0
466         in
467         LexiconAst.Number_alias (instance, dsc)
468     ]
469   ];
470   argument: [
471     [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
472       id = IDENT ->
473         Ast.IdentArg (List.length l, id)
474     ]
475   ];
476   associativity: [
477     [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
478     | IDENT "right"; IDENT "associative" -> Gramext.RightA
479     | IDENT "non"; IDENT "associative" -> Gramext.NonA
480     ]
481   ];
482   precedence: [
483     [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
484   ];
485   notation: [
486     [ dir = OPT direction; s = QSTRING;
487       assoc = OPT associativity; prec = OPT precedence;
488       IDENT "for";
489       p2 = 
490         [ blob = UNPARSED_AST ->
491             add_raw_attribute ~text:(sprintf "@{%s}" blob)
492               (CicNotationParser.parse_level2_ast
493                 (Ulexing.from_utf8_string blob))
494         | blob = UNPARSED_META ->
495             add_raw_attribute ~text:(sprintf "${%s}" blob)
496               (CicNotationParser.parse_level2_meta
497                 (Ulexing.from_utf8_string blob))
498         ] ->
499           let assoc =
500             match assoc with
501             | None -> default_associativity
502             | Some assoc -> assoc
503           in
504           let prec =
505             match prec with
506             | None -> default_precedence
507             | Some prec -> prec
508           in
509           let p1 =
510             add_raw_attribute ~text:s
511               (CicNotationParser.parse_level1_pattern
512                 (Ulexing.from_utf8_string s))
513           in
514           (dir, p1, assoc, prec, p2)
515     ]
516   ];
517   level3_term: [
518     [ u = URI -> Ast.UriPattern (UriManager.uri_of_string u)
519     | id = IDENT -> Ast.VarPattern id
520     | SYMBOL "_" -> Ast.ImplicitPattern
521     | LPAREN; terms = LIST1 SELF; RPAREN ->
522         (match terms with
523         | [] -> assert false
524         | [term] -> term
525         | terms -> Ast.ApplPattern terms)
526     ]
527   ];
528   interpretation: [
529     [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
530         (s, args, t)
531     ]
532   ];
533   
534   include_command: [ [
535       IDENT "include" ; path = QSTRING -> 
536         loc,path,LexiconAst.WithPreferences
537     | IDENT "include'" ; path = QSTRING -> 
538         loc,path,LexiconAst.WithoutPreferences
539    ]];
540
541   grafite_command: [ [
542       IDENT "set"; n = QSTRING; v = QSTRING ->
543         GrafiteAst.Set (loc, n, v)
544     | IDENT "drop" -> GrafiteAst.Drop loc
545     | IDENT "print"; s = IDENT -> GrafiteAst.Print (loc,s)
546     | IDENT "qed" -> GrafiteAst.Qed loc
547     | IDENT "variant" ; name = IDENT; SYMBOL ":"; 
548       typ = term; SYMBOL <:unicode<def>> ; newname = IDENT ->
549         GrafiteAst.Obj (loc, 
550           Ast.Theorem 
551             (`Variant,name,typ,Some (Ast.Ident (newname, None))))
552     | flavour = theorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
553       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
554         GrafiteAst.Obj (loc, Ast.Theorem (flavour, name, typ, body))
555     | flavour = theorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
556       body = term ->
557         GrafiteAst.Obj (loc,
558           Ast.Theorem (flavour, name, Ast.Implicit, Some body))
559     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
560         GrafiteAst.Obj (loc, Ast.Theorem (`Axiom, name, typ, None))
561     | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
562         defs = CicNotationParser.let_defs -> 
563           let name,ty = 
564             match defs with
565             | (params,(Ast.Ident (name, None), Some ty),_,_) :: _ ->
566                 let ty =
567                  List.fold_right
568                   (fun var ty -> Ast.Binder (`Pi,var,ty)
569                   ) params ty
570                 in
571                  name,ty
572             | (_,(Ast.Ident (name, None), None),_,_) :: _ ->
573                 name, Ast.Implicit
574             | _ -> assert false 
575           in
576           let body = Ast.Ident (name,None) in
577           GrafiteAst.Obj (loc, Ast.Theorem(`Definition, name, ty,
578             Some (Ast.LetRec (ind_kind, defs, body))))
579     | IDENT "inductive"; spec = inductive_spec ->
580         let (params, ind_types) = spec in
581         GrafiteAst.Obj (loc, Ast.Inductive (params, ind_types))
582     | IDENT "coinductive"; spec = inductive_spec ->
583         let (params, ind_types) = spec in
584         let ind_types = (* set inductive flags to false (coinductive) *)
585           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
586             ind_types
587         in
588         GrafiteAst.Obj (loc, Ast.Inductive (params, ind_types))
589     | IDENT "coercion" ; suri = URI ; arity = OPT int ->
590         let arity = match arity with None -> 0 | Some x -> x in
591         GrafiteAst.Coercion (loc, UriManager.uri_of_string suri, true, arity)
592     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
593         GrafiteAst.Obj (loc, Ast.Record (params,name,ty,fields))
594     | IDENT "default" ; what = QSTRING ; uris = LIST1 URI ->
595        let uris = List.map UriManager.uri_of_string uris in
596         GrafiteAst.Default (loc,what,uris)
597     | IDENT "relation" ; aeq = tactic_term ; "on" ; a = tactic_term ;
598       refl = OPT [ IDENT "reflexivity" ; IDENT "proved" ; IDENT "by" ;
599                    refl = tactic_term -> refl ] ;
600       sym = OPT [ IDENT "symmetry" ; IDENT "proved" ; IDENT "by" ;
601                    sym = tactic_term -> sym ] ;
602       trans = OPT [ IDENT "transitivity" ; IDENT "proved" ; IDENT "by" ;
603                    trans = tactic_term -> trans ] ;
604       "as" ; id = IDENT ->
605        GrafiteAst.Relation (loc,id,a,aeq,refl,sym,trans)
606   ]];
607   lexicon_command: [ [
608       IDENT "alias" ; spec = alias_spec ->
609         LexiconAst.Alias (loc, spec)
610     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
611         LexiconAst.Notation (loc, dir, l1, assoc, prec, l2)
612     | IDENT "interpretation"; id = QSTRING;
613       (symbol, args, l3) = interpretation ->
614         LexiconAst.Interpretation (loc, id, (symbol, args), l3)
615   ]];
616   executable: [
617     [ cmd = grafite_command; SYMBOL "." -> GrafiteAst.Command (loc, cmd)
618     | tac = tactical; punct = punctuation_tactical ->
619         GrafiteAst.Tactical (loc, tac, Some punct)
620     | punct = punctuation_tactical -> GrafiteAst.Tactical (loc, punct, None)
621     | mac = macro; SYMBOL "." -> GrafiteAst.Macro (loc, mac)
622     ]
623   ];
624   comment: [
625     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
626        GrafiteAst.Code (loc, ex)
627     | str = NOTE -> 
628        GrafiteAst.Note (loc, str)
629     ]
630   ];
631   statement: [
632     [ ex = executable ->
633        fun ~include_paths status -> status,LSome(GrafiteAst.Executable (loc,ex))
634     | com = comment ->
635        fun ~include_paths status -> status,LSome (GrafiteAst.Comment (loc, com))
636     | (iloc,fname,mode) = include_command ; SYMBOL "."  ->
637        fun ~include_paths status ->
638         let buri, fullpath = 
639           DependenciesParser.baseuri_of_script ~include_paths fname 
640         in
641         let status =
642          LexiconEngine.eval_command status 
643            (LexiconAst.Include (iloc,buri,mode,fullpath))
644         in
645          status,
646           LSome
647           (GrafiteAst.Executable
648            (loc,GrafiteAst.Command
649             (loc,GrafiteAst.Include (iloc,buri))))
650     | scom = lexicon_command ; SYMBOL "." ->
651        fun ~include_paths status ->
652         let status = LexiconEngine.eval_command status scom in
653          status,LNone loc
654     | EOI -> raise End_of_file
655     ]
656   ];
657 END
658
659 let exc_located_wrapper f =
660   try
661     f ()
662   with
663   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
664   | Stdpp.Exc_located (floc, Stream.Error msg) ->
665       raise (HExtlib.Localized (floc,CicNotationParser.Parse_error msg))
666   | Stdpp.Exc_located (floc, exn) ->
667       raise
668        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
669
670 let parse_statement lexbuf =
671   exc_located_wrapper
672     (fun () -> (Grammar.Entry.parse statement (Obj.magic lexbuf)))