]> matita.cs.unibo.it Git - helm.git/blob - components/grafite_parser/grafiteParser.ml
New syntax and semantics for the rewriting steps that make the pretty-printed
[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"]; suri = QSTRING; prefix = OPT QSTRING ->
415          let prefix = match prefix with None -> "" | Some prefix -> prefix in
416          GrafiteAst.Inline (loc,suri,prefix)
417     | [ IDENT "hint" ] -> GrafiteAst.Hint loc
418     | [ IDENT "whelp"; "match" ] ; t = term -> 
419         GrafiteAst.WMatch (loc,t)
420     | [ IDENT "whelp"; IDENT "instance" ] ; t = term -> 
421         GrafiteAst.WInstance (loc,t)
422     | [ IDENT "whelp"; IDENT "locate" ] ; id = QSTRING -> 
423         GrafiteAst.WLocate (loc,id)
424     | [ IDENT "whelp"; IDENT "elim" ] ; t = term ->
425         GrafiteAst.WElim (loc, t)
426     | [ IDENT "whelp"; IDENT "hint" ] ; t = term -> 
427         GrafiteAst.WHint (loc,t)
428     ]
429   ];
430   alias_spec: [
431     [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
432       let alpha = "[a-zA-Z]" in
433       let num = "[0-9]+" in
434       let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
435       let ident = "\\("^alpha^ident_cont^"*\\|_"^ident_cont^"+\\)" in
436       let rex = Str.regexp ("^"^ident^"$") in
437       if Str.string_match rex id 0 then
438         if (try ignore (UriManager.uri_of_string uri); true
439             with UriManager.IllFormedUri _ -> false)
440         then
441           LexiconAst.Ident_alias (id, uri)
442         else 
443           raise
444            (HExtlib.Localized (loc, CicNotationParser.Parse_error (sprintf "Not a valid uri: %s" uri)))
445       else
446         raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
447           sprintf "Not a valid identifier: %s" id)))
448     | IDENT "symbol"; symbol = QSTRING;
449       instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
450       SYMBOL "="; dsc = QSTRING ->
451         let instance =
452           match instance with Some i -> i | None -> 0
453         in
454         LexiconAst.Symbol_alias (symbol, instance, dsc)
455     | IDENT "num";
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.Number_alias (instance, dsc)
462     ]
463   ];
464   argument: [
465     [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
466       id = IDENT ->
467         Ast.IdentArg (List.length l, id)
468     ]
469   ];
470   associativity: [
471     [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
472     | IDENT "right"; IDENT "associative" -> Gramext.RightA
473     | IDENT "non"; IDENT "associative" -> Gramext.NonA
474     ]
475   ];
476   precedence: [
477     [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
478   ];
479   notation: [
480     [ dir = OPT direction; s = QSTRING;
481       assoc = OPT associativity; prec = OPT precedence;
482       IDENT "for";
483       p2 = 
484         [ blob = UNPARSED_AST ->
485             add_raw_attribute ~text:(sprintf "@{%s}" blob)
486               (CicNotationParser.parse_level2_ast
487                 (Ulexing.from_utf8_string blob))
488         | blob = UNPARSED_META ->
489             add_raw_attribute ~text:(sprintf "${%s}" blob)
490               (CicNotationParser.parse_level2_meta
491                 (Ulexing.from_utf8_string blob))
492         ] ->
493           let assoc =
494             match assoc with
495             | None -> default_associativity
496             | Some assoc -> assoc
497           in
498           let prec =
499             match prec with
500             | None -> default_precedence
501             | Some prec -> prec
502           in
503           let p1 =
504             add_raw_attribute ~text:s
505               (CicNotationParser.parse_level1_pattern
506                 (Ulexing.from_utf8_string s))
507           in
508           (dir, p1, assoc, prec, p2)
509     ]
510   ];
511   level3_term: [
512     [ u = URI -> Ast.UriPattern (UriManager.uri_of_string u)
513     | id = IDENT -> Ast.VarPattern id
514     | SYMBOL "_" -> Ast.ImplicitPattern
515     | LPAREN; terms = LIST1 SELF; RPAREN ->
516         (match terms with
517         | [] -> assert false
518         | [term] -> term
519         | terms -> Ast.ApplPattern terms)
520     ]
521   ];
522   interpretation: [
523     [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
524         (s, args, t)
525     ]
526   ];
527   
528   include_command: [ [
529       IDENT "include" ; path = QSTRING -> 
530         loc,path,LexiconAst.WithPreferences
531     | IDENT "include'" ; path = QSTRING -> 
532         loc,path,LexiconAst.WithoutPreferences
533    ]];
534
535   grafite_command: [ [
536       IDENT "set"; n = QSTRING; v = QSTRING ->
537         GrafiteAst.Set (loc, n, v)
538     | IDENT "drop" -> GrafiteAst.Drop loc
539     | IDENT "print"; s = IDENT -> GrafiteAst.Print (loc,s)
540     | IDENT "qed" -> GrafiteAst.Qed loc
541     | IDENT "variant" ; name = IDENT; SYMBOL ":"; 
542       typ = term; SYMBOL <:unicode<def>> ; newname = IDENT ->
543         GrafiteAst.Obj (loc, 
544           Ast.Theorem 
545             (`Variant,name,typ,Some (Ast.Ident (newname, None))))
546     | flavour = theorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
547       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
548         GrafiteAst.Obj (loc, Ast.Theorem (flavour, name, typ, body))
549     | flavour = theorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
550       body = term ->
551         GrafiteAst.Obj (loc,
552           Ast.Theorem (flavour, name, Ast.Implicit, Some body))
553     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
554         GrafiteAst.Obj (loc, Ast.Theorem (`Axiom, name, typ, None))
555     | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
556         defs = CicNotationParser.let_defs -> 
557           let name,ty = 
558             match defs with
559             | (params,(Ast.Ident (name, None), Some ty),_,_) :: _ ->
560                 let ty =
561                  List.fold_right
562                   (fun var ty -> Ast.Binder (`Pi,var,ty)
563                   ) params ty
564                 in
565                  name,ty
566             | (_,(Ast.Ident (name, None), None),_,_) :: _ ->
567                 name, Ast.Implicit
568             | _ -> assert false 
569           in
570           let body = Ast.Ident (name,None) in
571           GrafiteAst.Obj (loc, Ast.Theorem(`Definition, name, ty,
572             Some (Ast.LetRec (ind_kind, defs, body))))
573     | IDENT "inductive"; spec = inductive_spec ->
574         let (params, ind_types) = spec in
575         GrafiteAst.Obj (loc, Ast.Inductive (params, ind_types))
576     | IDENT "coinductive"; spec = inductive_spec ->
577         let (params, ind_types) = spec in
578         let ind_types = (* set inductive flags to false (coinductive) *)
579           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
580             ind_types
581         in
582         GrafiteAst.Obj (loc, Ast.Inductive (params, ind_types))
583     | IDENT "coercion" ; suri = URI ; arity = OPT int ->
584         let arity = match arity with None -> 0 | Some x -> x in
585         GrafiteAst.Coercion (loc, UriManager.uri_of_string suri, true, arity)
586     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
587         GrafiteAst.Obj (loc, Ast.Record (params,name,ty,fields))
588     | IDENT "default" ; what = QSTRING ; uris = LIST1 URI ->
589        let uris = List.map UriManager.uri_of_string uris in
590         GrafiteAst.Default (loc,what,uris)
591     | IDENT "relation" ; aeq = tactic_term ; "on" ; a = tactic_term ;
592       refl = OPT [ IDENT "reflexivity" ; IDENT "proved" ; IDENT "by" ;
593                    refl = tactic_term -> refl ] ;
594       sym = OPT [ IDENT "symmetry" ; IDENT "proved" ; IDENT "by" ;
595                    sym = tactic_term -> sym ] ;
596       trans = OPT [ IDENT "transitivity" ; IDENT "proved" ; IDENT "by" ;
597                    trans = tactic_term -> trans ] ;
598       "as" ; id = IDENT ->
599        GrafiteAst.Relation (loc,id,a,aeq,refl,sym,trans)
600   ]];
601   lexicon_command: [ [
602       IDENT "alias" ; spec = alias_spec ->
603         LexiconAst.Alias (loc, spec)
604     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
605         LexiconAst.Notation (loc, dir, l1, assoc, prec, l2)
606     | IDENT "interpretation"; id = QSTRING;
607       (symbol, args, l3) = interpretation ->
608         LexiconAst.Interpretation (loc, id, (symbol, args), l3)
609   ]];
610   executable: [
611     [ cmd = grafite_command; SYMBOL "." -> GrafiteAst.Command (loc, cmd)
612     | tac = tactical; punct = punctuation_tactical ->
613         GrafiteAst.Tactical (loc, tac, Some punct)
614     | punct = punctuation_tactical -> GrafiteAst.Tactical (loc, punct, None)
615     | mac = macro; SYMBOL "." -> GrafiteAst.Macro (loc, mac)
616     ]
617   ];
618   comment: [
619     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
620        GrafiteAst.Code (loc, ex)
621     | str = NOTE -> 
622        GrafiteAst.Note (loc, str)
623     ]
624   ];
625   statement: [
626     [ ex = executable ->
627        fun ~include_paths status -> status,LSome(GrafiteAst.Executable (loc,ex))
628     | com = comment ->
629        fun ~include_paths status -> status,LSome (GrafiteAst.Comment (loc, com))
630     | (iloc,fname,mode) = include_command ; SYMBOL "."  ->
631        fun ~include_paths status ->
632         let buri, fullpath = 
633           DependenciesParser.baseuri_of_script ~include_paths fname 
634         in
635         let status =
636          LexiconEngine.eval_command status 
637            (LexiconAst.Include (iloc,buri,mode,fullpath))
638         in
639          status,
640           LSome
641           (GrafiteAst.Executable
642            (loc,GrafiteAst.Command
643             (loc,GrafiteAst.Include (iloc,buri))))
644     | scom = lexicon_command ; SYMBOL "." ->
645        fun ~include_paths status ->
646         let status = LexiconEngine.eval_command status scom in
647          status,LNone loc
648     | EOI -> raise End_of_file
649     ]
650   ];
651 END
652
653 let exc_located_wrapper f =
654   try
655     f ()
656   with
657   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
658   | Stdpp.Exc_located (floc, Stream.Error msg) ->
659       raise (HExtlib.Localized (floc,CicNotationParser.Parse_error msg))
660   | Stdpp.Exc_located (floc, exn) ->
661       raise
662        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
663
664 let parse_statement lexbuf =
665   exc_located_wrapper
666     (fun () -> (Grammar.Entry.parse statement (Obj.magic lexbuf)))