]> matita.cs.unibo.it Git - helm.git/blob - matitaB/components/grafite_parser/grafiteParser.ml
b72fecb76656bdace9c41fb35bcd220849629129
[helm.git] / matitaB / 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 module N  = NotationPt
29 module G  = GrafiteAst
30
31 let exc_located_wrapper f =
32   try
33     f ()
34   with
35   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
36   | Stdpp.Exc_located (floc, Stream.Error msg) ->
37       raise (HExtlib.Localized (floc,CicNotationParser.Parse_error msg))
38   | Stdpp.Exc_located (floc, HExtlib.Localized(_,exn)) ->
39       raise (HExtlib.Localized 
40         (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
41   | Stdpp.Exc_located (floc, exn) ->
42       raise (HExtlib.Localized 
43         (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
44
45 type parsable = Grammar.parsable
46
47 let parsable_statement status buf =
48  let grammar = CicNotationParser.level2_ast_grammar status in
49   Grammar.parsable grammar (Obj.magic buf)
50
51 let parse_statement grafite_parser parsable =
52   exc_located_wrapper
53     (fun () -> (Grammar.Entry.parse_parsable (Obj.magic grafite_parser) parsable))
54
55 let add_raw_attribute ~text t = N.AttributedTerm (`Raw text, t)
56
57 let default_associativity = Gramext.NonA
58         
59 let mk_rec_corec ind_kind defs loc = 
60   let name,ty = 
61     match defs with
62     | (params,(N.Ident (name, `Ambiguous), ty),_,_) :: _ ->
63         let ty = match ty with Some ty -> ty | None -> N.Implicit `JustOne in
64         let ty =
65          List.fold_right
66           (fun var ty -> N.Binder (`Pi,var,ty)
67           ) params ty
68         in
69          name,ty
70     | _ -> assert false 
71   in
72   let body = N.Ident (name,`Ambiguous) in
73    (loc, N.Theorem(`Definition, name, ty, Some (N.LetRec (ind_kind, defs, body)), `Regular))
74
75 let nmk_rec_corec ind_kind defs loc = 
76  let loc,t = mk_rec_corec ind_kind defs loc in
77   G.NObj (loc,t)
78
79 (*
80 let nnon_punct_of_punct = function
81   | G.Skip loc -> G.NSkip loc
82   | G.Unfocus loc -> G.NUnfocus loc
83   | G.Focus (loc,l) -> G.NFocus (loc,l)
84 ;; *)
85
86 type by_continuation =
87    BYC_done
88  | BYC_weproved of N.term * string option * N.term option
89  | BYC_letsuchthat of string * N.term * string * N.term
90  | BYC_wehaveand of string * N.term * string * N.term
91
92 let mk_parser statement lstatus =
93 (*   let grammar = CicNotationParser.level2_ast_grammar lstatus in *)
94   let term = CicNotationParser.term lstatus in
95   let let_defs = CicNotationParser.let_defs lstatus in
96   let protected_binder_vars = CicNotationParser.protected_binder_vars lstatus in
97   (* {{{ parser initialization *)
98 EXTEND
99   GLOBAL: term statement;
100   constructor: [ [ name = IDENT; SYMBOL ":"; typ = term -> (name, typ) ] ];
101   tactic_term: [ [ t = term LEVEL "90" -> t ] ];
102 (* MATITA 1.0
103   new_name: [
104     [ SYMBOL "_" -> None
105     | id = IDENT -> Some id ]
106     ];
107 *)
108   ident_list1: [ [ LPAREN; idents = LIST1 IDENT; RPAREN -> idents ] ];
109   tactic_term_list1: [
110     [ tactic_terms = LIST1 tactic_term SEP SYMBOL "," -> tactic_terms ]
111   ];
112   nreduction_kind: [
113     [ IDENT "normalize" ; delta = OPT [ IDENT "nodelta" -> () ] ->
114        let delta = match delta with None -> true | _ -> false in
115         `Normalize delta
116     (*| IDENT "unfold"; t = OPT tactic_term -> `Unfold t*)
117     | IDENT "whd" ; delta = OPT [ IDENT "nodelta" -> () ] ->
118        let delta = match delta with None -> true | _ -> false in
119         `Whd delta]
120   ];
121   sequent_pattern_spec: [
122    [ hyp_paths =
123       LIST0
124        [ id = IDENT ;
125          path = OPT [SYMBOL ":" ; path = tactic_term -> path ] ->
126          (id,match path with Some p -> p | None -> N.UserInput) ];
127      goal_path = OPT [ SYMBOL <:unicode<vdash>>; term = tactic_term -> term ] ->
128       let goal_path =
129        match goal_path, hyp_paths with
130           None, [] -> Some N.UserInput
131         | None, _::_ -> None
132         | Some goal_path, _ -> Some goal_path
133       in
134        hyp_paths,goal_path
135    ]
136   ];
137   pattern_spec: [
138     [ res = OPT [
139        "in";
140        wanted_and_sps =
141         [ "match" ; wanted = tactic_term ;
142           sps = OPT [ "in"; sps = sequent_pattern_spec -> sps ] ->
143            Some wanted,sps
144         | sps = sequent_pattern_spec ->
145            None,Some sps
146         ] ->
147          let wanted,hyp_paths,goal_path =
148           match wanted_and_sps with
149              wanted,None -> wanted, [], Some N.UserInput
150            | wanted,Some (hyp_paths,goal_path) -> wanted,hyp_paths,goal_path
151          in
152           wanted, hyp_paths, goal_path ] ->
153       match res with
154          None -> None,[],Some N.UserInput
155        | Some ps -> ps]
156   ];
157   inverter_param_list: [ 
158     [ params = tactic_term -> 
159       let deannotate = function
160         | N.AttributedTerm (_,t) | t -> t
161       in match deannotate params with
162       | N.Implicit _ -> [false]
163       | N.UserInput -> [true]
164       | N.Appl l -> 
165          List.map (fun x -> match deannotate x with  
166            | N.Implicit _ -> false
167            | N.UserInput -> true
168            | _ -> raise (Invalid_argument "malformed target parameter list 1")) l
169       | _ ->
170        (*CSC: new NCicPp.status is the best I can do here without changing the
171          result type *)
172        raise (Invalid_argument ("malformed target parameter list 2\n" ^
173               NotationPp.pp_term (new NCicPp.status None ) params)) ]
174   ];
175   direction: [
176     [ SYMBOL ">" -> `LeftToRight
177     | SYMBOL "<" -> `RightToLeft ]
178   ];
179   int: [ [ num = NUMBER -> int_of_string num ] ];
180 (* MATITA 1.0
181   intros_spec: [
182     [ OPT [ IDENT "names" ]; 
183       num = OPT [ num = int -> num ]; 
184       idents = intros_names ->
185         num, idents
186     ]
187   ];
188 *)
189 (* MATITA 1.0  using: [ [ using = OPT [ IDENT "using"; t = tactic_term -> t ] -> using ]  ]; *)
190   ntactic: [
191     [ SYMBOL "@"; t = tactic_term -> G.NTactic(loc,[G.NApply (loc, t)])
192     | IDENT "apply"; t = tactic_term -> G.NTactic(loc,[G.NApply (loc, t)])
193     | IDENT "applyS"; t = tactic_term -> G.NTactic(loc,[G.NSmartApply(loc, t)])
194     | IDENT "assert";
195        seqs = LIST0 [
196         hyps = LIST0
197          [ id = IDENT ; SYMBOL ":" ; ty = tactic_term -> id,`Decl ty
198          | id = IDENT ; SYMBOL ":" ; ty = tactic_term ;
199                         SYMBOL <:unicode<def>> ; bo = tactic_term ->
200             id,`Def (bo,ty)];
201         SYMBOL <:unicode<vdash>>;
202         concl = tactic_term -> (List.rev hyps,concl) ] ->
203          G.NTactic(loc,[G.NAssert (loc, seqs)])
204     (*| IDENT "auto"; params = auto_params -> 
205         G.NTactic(loc,[G.NAuto (loc, params)])*)
206     | SYMBOL "/"; num = OPT NUMBER ; 
207        just_and_params = auto_params; SYMBOL "/" ->
208        let just,params = just_and_params in
209        let depth = match num with Some n -> n | None -> "1" in
210        (match just with
211        | None -> 
212                  G.NTactic(loc,
213             [G.NAuto(loc,(None,["depth",depth]@params))])
214        | Some (b,`Univ univ) ->
215                  G.NTactic(loc,
216             [G.NAuto(loc,(Some (b,univ),["depth",depth]@params))])
217        | Some (b,`EmptyUniv) ->
218                  G.NTactic(loc,
219             [G.NAuto(loc,(Some (b,[]),["depth",depth]@params))])
220        | Some (b,`Trace) ->
221                  G.NMacro(loc,
222              G.NAutoInteractive (loc, (None,["depth",depth]@params))))
223     | IDENT "intros" -> G.NMacro (loc, G.NIntroGuess loc)
224     | IDENT "check"; t = tactic_term -> G.NMacro(loc,G.NCheck (loc,t))
225     | IDENT "screenshot"; fname = QSTRING -> 
226         G.NMacro(loc,G.Screenshot (loc, fname))
227     | IDENT "cases"; what = tactic_term ; where = pattern_spec ->
228         G.NTactic(loc,[G.NCases (loc, what, where)])
229     | IDENT "change"; what = pattern_spec; "with"; with_what = tactic_term -> 
230         G.NTactic(loc,[G.NChange (loc, what, with_what)])
231     | SYMBOL "-"; ids = LIST1 IDENT ->
232         G.NTactic(loc,[G.NClear (loc, ids)])
233     | (*SYMBOL "^"*)PLACEHOLDER; num = OPT NUMBER; 
234         l = OPT [ SYMBOL "{"; l = LIST1 tactic_term; SYMBOL "}" -> l ] -> 
235         G.NTactic(loc,[G.NConstructor (loc, (match num with None -> None | Some x -> Some (int_of_string x)),match l with None -> [] | Some l -> l)])
236     | IDENT "cut"; t = tactic_term -> G.NTactic(loc,[G.NCut (loc, t)])
237 (*  | IDENT "discriminate"; t = tactic_term -> G.NDiscriminate (loc, t)
238     | IDENT "subst"; t = tactic_term -> G.NSubst (loc, t) *)
239     | IDENT "destruct"; just = OPT [ dom = ident_list1 -> dom ];
240       exclude = OPT [ IDENT "skip"; skip = ident_list1 -> skip ]
241         -> let exclude' = match exclude with None -> [] | Some l -> l in
242            G.NTactic(loc,[G.NDestruct (loc,just,exclude')])
243     | IDENT "elim"; what = tactic_term ; where = pattern_spec ->
244         G.NTactic(loc,[G.NElim (loc, what, where)])
245     | IDENT "generalize"; p=pattern_spec ->
246         G.NTactic(loc,[G.NGeneralize (loc, p)])
247     | IDENT "inversion"; what = tactic_term ; where = pattern_spec ->
248         G.NTactic(loc,[G.NInversion (loc, what, where)])
249     | IDENT "lapply"; t = tactic_term -> G.NTactic(loc,[G.NLApply (loc, t)])
250     | IDENT "letin"; name = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term;
251         where = pattern_spec ->
252         G.NTactic(loc,[G.NLetIn (loc,where,t,name)])
253     | kind = nreduction_kind; p = pattern_spec ->
254         G.NTactic(loc,[G.NReduce (loc, kind, p)])
255     | dir = direction; what = tactic_term ; where = pattern_spec ->     
256         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
257     | IDENT "rewrite"; dir = direction; what = tactic_term ; where = pattern_spec ->    
258         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
259     | IDENT "try"; tac = SELF -> 
260         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
261         G.NTactic(loc,[ G.NTry (loc,tac)])
262     | IDENT "repeat"; tac = SELF -> 
263         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
264         G.NTactic(loc,[ G.NRepeat (loc,tac)])
265     | LPAREN; l = LIST1 SELF; RPAREN -> 
266         let l = 
267           List.flatten 
268             (List.map (function G.NTactic(_,t) -> t | _ -> assert false) l) in
269         G.NTactic(loc,[G.NBlock (loc,l)])
270     | IDENT "assumption" -> G.NTactic(loc,[ G.NAssumption loc])
271     | SYMBOL "#"; ns=IDENT -> G.NTactic(loc,[ G.NIntros (loc,[ns])])
272     | SYMBOL "#"; SYMBOL "_" -> G.NTactic(loc,[ G.NIntro (loc,"_")])
273     | SYMBOL "*" -> G.NTactic(loc,[ G.NCase1 (loc,"_")])
274     | SYMBOL "*"; n=IDENT -> G.NTactic(loc,[ G.NCase1 (loc,n)])
275     ]
276   ];
277   auto_fixed_param: [
278    [ IDENT "demod"
279    | IDENT "fast_paramod"
280    | IDENT "paramod"
281    | IDENT "depth"
282    | IDENT "width"
283    | IDENT "size"
284    | IDENT "timeout"
285    | IDENT "library"
286    | IDENT "type"
287    | IDENT "all"
288    ]
289 ];
290   auto_params: [
291     [ params = 
292       LIST0 [
293          i = auto_fixed_param -> i,""
294        | i = auto_fixed_param ; SYMBOL "="; v = [ v = int ->
295               string_of_int v | v = IDENT -> v ] -> i,v ]; 
296       just = OPT [ is_user_trace = 
297               [ IDENT "by" -> true
298               | IDENT "trace" -> false ]; 
299           by = 
300            [ univ = tactic_term_list1 -> `Univ univ
301            | SYMBOL "{"; SYMBOL "}" -> `EmptyUniv
302            | SYMBOL "_" -> `Trace ] -> is_user_trace,by ] -> just,params
303    ]
304 ];
305
306 (* MATITA 1.0
307   by_continuation: [
308     [ WEPROVED; 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)
309     | WEPROVED; ty = tactic_term ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t2 = tactic_term -> t2] ; 
310             "done" -> BYC_weproved (ty,None,t1)
311     | "done" -> BYC_done
312     | "let" ; id1 = IDENT ; SYMBOL ":" ; t1 = tactic_term ;
313       IDENT "such" ; IDENT "that" ; t2=tactic_term ; LPAREN ; 
314       id2 = IDENT ; RPAREN -> BYC_letsuchthat (id1,t1,id2,t2)
315     | WEHAVE; t1=tactic_term ; LPAREN ; id1=IDENT ; RPAREN ;"and" ; t2=tactic_term ; LPAREN ; id2=IDENT ; RPAREN ->
316               BYC_wehaveand (id1,t1,id2,t2)
317     ]
318 ];
319 *)
320 (* MATITA 1.0
321   rewriting_step_continuation : [
322     [ "done" -> true
323     | -> false
324     ]
325 ];
326 *)
327 (* MATITA 1.0
328   atomic_tactical:
329     [ "sequence" LEFTA
330       [ t1 = SELF; SYMBOL ";"; t2 = SELF ->
331           let ts =
332             match t1 with
333             | G.Seq (_, l) -> l @ [ t2 ]
334             | _ -> [ t1; t2 ]
335           in
336           G.Seq (loc, ts)
337       ]
338     | "then" NONA
339       [ tac = SELF; SYMBOL ";";
340         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
341           (G.Then (loc, tac, tacs))
342       ]
343     | "loops" RIGHTA
344       [ IDENT "do"; count = int; tac = SELF ->
345           G.Do (loc, count, tac)
346       | IDENT "repeat"; tac = SELF -> G.Repeat (loc, tac)
347       ]
348     | "simple" NONA
349       [ IDENT "first";
350         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
351           G.First (loc, tacs)
352       | IDENT "try"; tac = SELF -> G.Try (loc, tac)
353       | IDENT "solve";
354         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
355           G.Solve (loc, tacs)
356       | IDENT "progress"; tac = SELF -> G.Progress (loc, tac)
357       | LPAREN; tac = SELF; RPAREN -> tac
358       | tac = tactic -> tac
359         ]
360       ];
361 *)
362   npunctuation_tactical:
363     [
364       [ SYMBOL "[" -> G.NBranch loc
365       | SYMBOL "|" -> G.NShift loc
366       | i = LIST1 int SEP SYMBOL ","; SYMBOL ":" -> G.NPos (loc, i)
367       | SYMBOL "*"; SYMBOL ":" -> G.NWildcard loc
368       | name = IDENT; SYMBOL ":" -> G.NPosbyname (loc, name)
369       | SYMBOL "]" -> G.NMerge loc
370       | SYMBOL ";" -> G.NSemicolon loc
371       | SYMBOL "." -> G.NDot loc
372       ]
373     ];
374   nnon_punctuation_tactical:
375     [ "simple" NONA
376       [ IDENT "focus"; goals = LIST1 int -> G.NFocus (loc, goals)
377       | IDENT "unfocus" -> G.NUnfocus loc
378       | IDENT "skip" -> G.NSkip loc
379       ]
380       ];
381   ntheorem_flavour: [
382     [ [ IDENT "definition"  ] -> `Definition
383     | [ IDENT "fact"        ] -> `Fact
384     | [ IDENT "lemma"       ] -> `Lemma
385     | [ IDENT "example"     ] -> `Example
386     | [ IDENT "theorem"     ] -> `Theorem
387     | [ IDENT "corollary"   ] -> `Corollary
388     ]
389   ];
390   inductive_spec: [ [
391     fst_name = IDENT; 
392       params = LIST0 protected_binder_vars;
393     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
394     fst_constructors = LIST0 constructor SEP SYMBOL "|";
395     tl = OPT [ "with";
396         types = LIST1 [
397           name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
398          OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
399             (name, true, typ, constructors) ] SEP "with" -> types
400       ] ->
401         let params =
402           List.fold_right
403             (fun (names, typ) acc ->
404               (List.map (fun name -> (name, typ)) names) @ acc)
405             params []
406         in
407         let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
408         let tl_ind_types = match tl with None -> [] | Some types -> types in
409         let ind_types = fst_ind_type :: tl_ind_types in
410         (params, ind_types)
411     ] ];
412     
413     record_spec: [ [
414       name = IDENT; 
415       params = LIST0 protected_binder_vars;
416        SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; SYMBOL "{" ; 
417        fields = LIST0 [ 
418          name = IDENT ; 
419          coercion = [ 
420              SYMBOL ":" -> false,0 
421            | SYMBOL ":"; SYMBOL ">" -> true,0
422            | SYMBOL ":"; arity = int ; SYMBOL ">" -> true,arity
423          ]; 
424          ty = term -> 
425            let b,n = coercion in 
426            (name,ty,b,n) 
427        ] SEP SYMBOL ";"; SYMBOL "}" -> 
428         let params =
429           List.fold_right
430             (fun (names, typ) acc ->
431               (List.map (fun name -> (name, typ)) names) @ acc)
432             params []
433         in
434         (params,name,typ,fields)
435     ] ];
436
437     (* XXX: alias spec must be revised (no more instance nums) *)
438     alias_spec: [
439       [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
440         let alpha = "[a-zA-Z]" in
441         let num = "[0-9]+" in
442         let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
443         let decoration = "\\'" in
444         let ident = "\\("^alpha^ident_cont^"*"^decoration^"*\\|_"^ident_cont^"+"^decoration^"*\\)" in
445         let rex = Str.regexp ("^"^ident^"$") in
446         if Str.string_match rex id 0 then
447           if (try ignore (NReference.reference_of_string uri); true
448               with NReference.IllFormedReference _ -> false)
449           then
450             G.Ident_alias (id, uri)
451           else
452             raise
453              (HExtlib.Localized (loc, CicNotationParser.Parse_error (Printf.sprintf "Not a valid uri: %s" uri)))
454         else
455           raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
456             Printf.sprintf "Not a valid identifier: %s" id)))
457       | IDENT "symbol"; symbol = QSTRING;
458         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
459         SYMBOL "="; dsc = QSTRING ->
460           let instance =
461             match instance with Some i -> i | None -> 0
462           in
463           G.Symbol_alias (symbol, None, dsc)
464       | IDENT "num";
465         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
466         SYMBOL "="; dsc = QSTRING ->
467           let instance =
468             match instance with Some i -> i | None -> 0
469           in
470           G.Number_alias (None,dsc)
471       ]
472      ];
473     argument: [
474       [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
475         id = IDENT ->
476           N.IdentArg (List.length l, id)
477       ]
478     ];
479     associativity: [
480       [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
481       | IDENT "right"; IDENT "associative" -> Gramext.RightA
482       | IDENT "non"; IDENT "associative" -> Gramext.NonA
483       ]
484     ];
485     precedence: [
486       [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
487     ];
488     notation: [
489       [ dir = OPT direction; s = QSTRING;
490         assoc = OPT associativity; prec = precedence;
491         IDENT "for";
492         p2 = 
493           [ blob = UNPARSED_AST ->
494               add_raw_attribute ~text:(Printf.sprintf "@{%s}" blob)
495                 (CicNotationParser.parse_level2_ast lstatus
496                   (Ulexing.from_utf8_string blob))
497           | blob = UNPARSED_META ->
498               add_raw_attribute ~text:(Printf.sprintf "${%s}" blob)
499                 (CicNotationParser.parse_level2_meta lstatus
500                   (Ulexing.from_utf8_string blob))
501           ] ->
502             let assoc =
503               match assoc with
504               | None -> default_associativity
505               | Some assoc -> assoc
506             in
507             let p1 =
508               add_raw_attribute ~text:s
509                 (CicNotationParser.parse_level1_pattern lstatus prec
510                   (Ulexing.from_utf8_string s))
511             in
512             (dir, p1, assoc, prec, p2)
513       ]
514     ];
515     level3_term: [
516       [ r = NREF -> N.NRefPattern (NReference.reference_of_string r)
517       | IMPLICIT -> N.ImplicitPattern
518       | id = IDENT -> N.VarPattern id
519       | LPAREN; terms = LIST1 SELF; RPAREN ->
520           (match terms with
521           | [] -> assert false
522           | [term] -> term
523           | terms -> N.ApplPattern terms)
524       ]
525     ];
526     interpretation: [
527       [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
528           (s, args, t)
529       ]
530     ];
531     
532     include_command: [ [
533         IDENT "include" ; path = QSTRING -> 
534           loc,path,G.WithPreferences
535       | IDENT "include" ; IDENT "alias"; path = QSTRING -> 
536           loc,path,G.OnlyPreferences
537       | IDENT "include'" ; path = QSTRING -> 
538           loc,path,G.WithoutPreferences
539      ]];
540
541   grafite_ncommand: [ [
542       IDENT "qed" ;  b = OPT SYMBOL "-" -> 
543         let b = match b with None -> true | Some _ -> false in G.NQed (loc,b)
544     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
545       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
546         G.NObj (loc, N.Theorem (nflavour, name, typ, body,`Regular))
547     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
548       body = term ->
549         G.NObj (loc, N.Theorem (nflavour, name, N.Implicit `JustOne, Some body,`Regular))
550     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
551         G.NObj (loc, N.Theorem (`Axiom, name, typ, None, `Regular))
552     | IDENT "discriminator" ; indty = tactic_term -> G.NDiscriminator (loc,indty)
553     | IDENT "inverter"; name = IDENT; IDENT "for" ; indty = tactic_term ;
554       paramspec = OPT inverter_param_list ; 
555       outsort = OPT [ SYMBOL ":" ; outsort = term -> outsort ] -> 
556         G.NInverter (loc,name,indty,paramspec,outsort)
557     | LETCOREC ; defs = let_defs -> 
558         nmk_rec_corec `CoInductive defs loc
559     | LETREC ; defs = let_defs -> 
560         nmk_rec_corec `Inductive defs loc
561     | IDENT "inductive"; spec = inductive_spec ->
562         let (params, ind_types) = spec in
563         G.NObj (loc, N.Inductive (params, ind_types))
564     | IDENT "coinductive"; spec = inductive_spec ->
565         let (params, ind_types) = spec in
566         let ind_types = (* set inductive flags to false (coinductive) *)
567           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
568             ind_types
569         in
570         G.NObj (loc, N.Inductive (params, ind_types))
571     | IDENT "universe"; IDENT "constraint"; u1 = tactic_term; 
572         SYMBOL <:unicode<lt>> ; u2 = tactic_term ->
573         let urify = function 
574           | NotationPt.AttributedTerm (_, NotationPt.Sort (`NType i)) ->
575               NUri.uri_of_string ("cic:/matita/pts/Type"^i^".univ")
576           | _ -> raise (Failure "only a Type[…] sort can be constrained")
577         in
578         let u1 = urify u1 in
579         let u2 = urify u2 in
580          G.NUnivConstraint (loc,u1,u2)
581     | IDENT "unification"; IDENT "hint"; n = int; t = tactic_term ->
582         G.UnificationHint (loc, t, n)
583     | IDENT "coercion"; name = IDENT; spec = OPT [ SYMBOL ":"; ty = term; 
584         SYMBOL <:unicode<def>>; t = term; "on"; 
585         id = [ IDENT | PIDENT ]; SYMBOL ":"; source = term;
586         "to"; target = term -> t,ty,(id,source),target ] ->
587         G.NCoercion(loc,name,spec)
588     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
589         G.NObj (loc, N.Record (params,name,ty,fields))
590     | IDENT "copy" ; s = IDENT; IDENT "from"; u = URI; "with"; 
591       m = LIST0 [ u1 = URI; SYMBOL <:unicode<mapsto>>; u2 = URI -> u1,u2 ] ->
592         G.NCopy (loc,s,NUri.uri_of_string u,
593           List.map (fun a,b -> NUri.uri_of_string a, NUri.uri_of_string b) m)
594     | lc = lexicon_command -> lc
595   ]];
596
597   lexicon_command: [ [
598       IDENT "alias" ; spec = alias_spec ->
599         G.Alias (loc, spec)
600     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
601         G.Notation (loc, dir, l1, assoc, prec, l2)
602     | IDENT "interpretation"; id = QSTRING;
603       (symbol, args, l3) = interpretation ->
604         G.Interpretation (loc, id, (symbol, args), l3)
605   ]];
606   executable: [
607     [ ncmd = grafite_ncommand; SYMBOL "." -> G.NCommand (loc, ncmd)
608     | punct = npunctuation_tactical -> G.NTactic (loc, [punct])
609     | tac = nnon_punctuation_tactical(*; punct = npunctuation_tactical*) ->
610           G.NTactic (loc, [tac])
611     | tac = ntactic (*; punct = npunctuation_tactical*) ->
612          tac 
613 (*
614     | tac = nnon_punctuation_tactical; 
615         punct = npunctuation_tactical ->
616           G.NTactic (loc, [tac; punct])
617 *)
618     ]
619   ];
620   comment: [
621     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
622        G.Code (loc, ex)
623     | str = NOTE -> 
624        G.Note (loc, str)
625     ]
626   ];
627   statement: [
628     [ ex = executable -> G.Executable (loc, ex)
629     | com = comment -> G.Comment (loc, com)
630     | (iloc,fname,mode) = include_command ; SYMBOL "."  ->
631                G.Executable (loc,G.NCommand (loc,G.Include (iloc,mode,fname)))
632     | EOI -> raise End_of_file
633     ]
634   ];
635   END;
636 (* }}} *)
637   statement
638 ;;
639
640 type db = GrafiteAst.statement Grammar.Entry.e ;;
641
642 class type g_status =
643  object
644   inherit CicNotationParser.g_status
645   method parser_db: db
646  end
647
648 class virtual status uid =
649  object(self)
650   inherit CicNotationParser.status uid ~keywords:[]
651   val mutable db = None (* mutable only to initialize it :-( *)
652   method parser_db = match db with None -> assert false | Some x -> x
653   method set_parser_db v = {< db = Some v >}
654   method set_parser_status
655    : 'status. #g_status as 'status -> 'self
656    = fun o -> {< db = Some o#parser_db >}#set_notation_parser_status o
657   initializer
658    let grammar = CicNotationParser.level2_ast_grammar self in
659    db <- Some (mk_parser (Grammar.Entry.create grammar "statement") self)
660  end
661
662 let extend status l1 action = 
663   let status = CicNotationParser.extend status l1 action in
664   let grammar = CicNotationParser.level2_ast_grammar status in
665   status#set_parser_db
666     (mk_parser (Grammar.Entry.create grammar "statement") status)
667 ;;
668
669
670 let parse_statement status =
671   status#reset_loctable (); 
672   parse_statement status#parser_db
673
674 (* vim:set foldmethod=marker: *)