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