]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_parser/grafiteParser.ml
Previous patch improved: we now use an ad-hoc wrapper for Grammar.parsable
[helm.git] / matita / 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, None), 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,None) 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       | _ -> raise (Invalid_argument ("malformed target parameter list 2\n" ^ NotationPp.pp_term params)) ]
170   ];
171   direction: [
172     [ SYMBOL ">" -> `LeftToRight
173     | SYMBOL "<" -> `RightToLeft ]
174   ];
175   int: [ [ num = NUMBER -> int_of_string num ] ];
176 (* MATITA 1.0
177   intros_spec: [
178     [ OPT [ IDENT "names" ]; 
179       num = OPT [ num = int -> num ]; 
180       idents = intros_names ->
181         num, idents
182     ]
183   ];
184 *)
185 (* MATITA 1.0  using: [ [ using = OPT [ IDENT "using"; t = tactic_term -> t ] -> using ]  ]; *)
186   ntactic: [
187     [ SYMBOL "@"; t = tactic_term -> G.NTactic(loc,[G.NApply (loc, t)])
188     | IDENT "apply"; t = tactic_term -> G.NTactic(loc,[G.NApply (loc, t)])
189     | IDENT "applyS"; t = tactic_term -> G.NTactic(loc,[G.NSmartApply(loc, t)])
190     | IDENT "assert";
191        seqs = LIST0 [
192         hyps = LIST0
193          [ id = IDENT ; SYMBOL ":" ; ty = tactic_term -> id,`Decl ty
194          | id = IDENT ; SYMBOL ":" ; ty = tactic_term ;
195                         SYMBOL <:unicode<def>> ; bo = tactic_term ->
196             id,`Def (bo,ty)];
197         SYMBOL <:unicode<vdash>>;
198         concl = tactic_term -> (List.rev hyps,concl) ] ->
199          G.NTactic(loc,[G.NAssert (loc, seqs)])
200     (*| IDENT "auto"; params = auto_params -> 
201         G.NTactic(loc,[G.NAuto (loc, params)])*)
202     | SYMBOL "/"; num = OPT NUMBER ; 
203        just_and_params = auto_params; SYMBOL "/" ->
204        let just,params = just_and_params in
205        let depth = match num with Some n -> n | None -> "1" in
206        (match just with
207        | None -> 
208                  G.NTactic(loc,
209             [G.NAuto(loc,(None,["depth",depth]@params))])
210        | Some (`Univ univ) ->
211                  G.NTactic(loc,
212             [G.NAuto(loc,(Some univ,["depth",depth]@params))])
213        | Some `EmptyUniv ->
214                  G.NTactic(loc,
215             [G.NAuto(loc,(Some [],["depth",depth]@params))])
216        | Some `Trace ->
217                  G.NMacro(loc,
218              G.NAutoInteractive (loc, (None,["depth",depth]@params))))
219     | IDENT "intros" -> G.NMacro (loc, G.NIntroGuess loc)
220     | IDENT "check"; t = term -> G.NMacro(loc,G.NCheck (loc,t))
221     | IDENT "screenshot"; fname = QSTRING -> 
222         G.NMacro(loc,G.Screenshot (loc, fname))
223     | IDENT "cases"; what = tactic_term ; where = pattern_spec ->
224         G.NTactic(loc,[G.NCases (loc, what, where)])
225     | IDENT "change"; what = pattern_spec; "with"; with_what = tactic_term -> 
226         G.NTactic(loc,[G.NChange (loc, what, with_what)])
227     | SYMBOL "-"; ids = LIST1 IDENT ->
228         G.NTactic(loc,[G.NClear (loc, ids)])
229     | (*SYMBOL "^"*)PLACEHOLDER; num = OPT NUMBER; 
230         l = OPT [ SYMBOL "{"; l = LIST1 tactic_term; SYMBOL "}" -> l ] -> 
231         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)])
232     | IDENT "cut"; t = tactic_term -> G.NTactic(loc,[G.NCut (loc, t)])
233 (*  | IDENT "discriminate"; t = tactic_term -> G.NDiscriminate (loc, t)
234     | IDENT "subst"; t = tactic_term -> G.NSubst (loc, t) *)
235     | IDENT "destruct"; just = OPT [ dom = ident_list1 -> dom ];
236       exclude = OPT [ IDENT "skip"; skip = ident_list1 -> skip ]
237         -> let exclude' = match exclude with None -> [] | Some l -> l in
238            G.NTactic(loc,[G.NDestruct (loc,just,exclude')])
239     | IDENT "elim"; what = tactic_term ; where = pattern_spec ->
240         G.NTactic(loc,[G.NElim (loc, what, where)])
241     | IDENT "generalize"; p=pattern_spec ->
242         G.NTactic(loc,[G.NGeneralize (loc, p)])
243     | IDENT "inversion"; what = tactic_term ; where = pattern_spec ->
244         G.NTactic(loc,[G.NInversion (loc, what, where)])
245     | IDENT "lapply"; t = tactic_term -> G.NTactic(loc,[G.NLApply (loc, t)])
246     | IDENT "letin"; name = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term;
247         where = pattern_spec ->
248         G.NTactic(loc,[G.NLetIn (loc,where,t,name)])
249     | kind = nreduction_kind; p = pattern_spec ->
250         G.NTactic(loc,[G.NReduce (loc, kind, p)])
251     | dir = direction; what = tactic_term ; where = pattern_spec ->     
252         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
253     | IDENT "rewrite"; dir = direction; what = tactic_term ; where = pattern_spec ->    
254         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
255     | IDENT "try"; tac = SELF -> 
256         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
257         G.NTactic(loc,[ G.NTry (loc,tac)])
258     | IDENT "repeat"; tac = SELF -> 
259         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
260         G.NTactic(loc,[ G.NRepeat (loc,tac)])
261     | LPAREN; l = LIST1 SELF; RPAREN -> 
262         let l = 
263           List.flatten 
264             (List.map (function G.NTactic(_,t) -> t | _ -> assert false) l) in
265         G.NTactic(loc,[G.NBlock (loc,l)])
266     | IDENT "assumption" -> G.NTactic(loc,[ G.NAssumption loc])
267     | SYMBOL "#"; ns=IDENT -> G.NTactic(loc,[ G.NIntros (loc,[ns])])
268     | SYMBOL "#"; SYMBOL "_" -> G.NTactic(loc,[ G.NIntro (loc,"_")])
269     | SYMBOL "*" -> G.NTactic(loc,[ G.NCase1 (loc,"_")])
270     | SYMBOL "*"; n=IDENT -> G.NTactic(loc,[ G.NCase1 (loc,n)])
271     ]
272   ];
273   auto_fixed_param: [
274    [ IDENT "demod"
275    | IDENT "fast_paramod"
276    | IDENT "paramod"
277    | IDENT "depth"
278    | IDENT "width"
279    | IDENT "size"
280    | IDENT "timeout"
281    | IDENT "library"
282    | IDENT "type"
283    | IDENT "all"
284    ]
285 ];
286   auto_params: [
287     [ params = 
288       LIST0 [
289          i = auto_fixed_param -> i,""
290        | i = auto_fixed_param ; SYMBOL "="; v = [ v = int ->
291               string_of_int v | v = IDENT -> v ] -> i,v ]; 
292       just = OPT [ IDENT "by"; by = 
293         [ univ = tactic_term_list1 -> `Univ univ
294         | SYMBOL "{"; SYMBOL "}" -> `EmptyUniv
295         | SYMBOL "_" -> `Trace ] -> by ] -> just,params
296    ]
297 ];
298
299 (* MATITA 1.0
300   by_continuation: [
301     [ 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)
302     | WEPROVED; ty = tactic_term ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t2 = tactic_term -> t2] ; 
303             "done" -> BYC_weproved (ty,None,t1)
304     | "done" -> BYC_done
305     | "let" ; id1 = IDENT ; SYMBOL ":" ; t1 = tactic_term ;
306       IDENT "such" ; IDENT "that" ; t2=tactic_term ; LPAREN ; 
307       id2 = IDENT ; RPAREN -> BYC_letsuchthat (id1,t1,id2,t2)
308     | WEHAVE; t1=tactic_term ; LPAREN ; id1=IDENT ; RPAREN ;"and" ; t2=tactic_term ; LPAREN ; id2=IDENT ; RPAREN ->
309               BYC_wehaveand (id1,t1,id2,t2)
310     ]
311 ];
312 *)
313 (* MATITA 1.0
314   rewriting_step_continuation : [
315     [ "done" -> true
316     | -> false
317     ]
318 ];
319 *)
320 (* MATITA 1.0
321   atomic_tactical:
322     [ "sequence" LEFTA
323       [ t1 = SELF; SYMBOL ";"; t2 = SELF ->
324           let ts =
325             match t1 with
326             | G.Seq (_, l) -> l @ [ t2 ]
327             | _ -> [ t1; t2 ]
328           in
329           G.Seq (loc, ts)
330       ]
331     | "then" NONA
332       [ tac = SELF; SYMBOL ";";
333         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
334           (G.Then (loc, tac, tacs))
335       ]
336     | "loops" RIGHTA
337       [ IDENT "do"; count = int; tac = SELF ->
338           G.Do (loc, count, tac)
339       | IDENT "repeat"; tac = SELF -> G.Repeat (loc, tac)
340       ]
341     | "simple" NONA
342       [ IDENT "first";
343         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
344           G.First (loc, tacs)
345       | IDENT "try"; tac = SELF -> G.Try (loc, tac)
346       | IDENT "solve";
347         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
348           G.Solve (loc, tacs)
349       | IDENT "progress"; tac = SELF -> G.Progress (loc, tac)
350       | LPAREN; tac = SELF; RPAREN -> tac
351       | tac = tactic -> tac
352         ]
353       ];
354 *)
355   npunctuation_tactical:
356     [
357       [ SYMBOL "[" -> G.NBranch loc
358       | SYMBOL "|" -> G.NShift loc
359       | i = LIST1 int SEP SYMBOL ","; SYMBOL ":" -> G.NPos (loc, i)
360       | SYMBOL "*"; SYMBOL ":" -> G.NWildcard loc
361       | name = IDENT; SYMBOL ":" -> G.NPosbyname (loc, name)
362       | SYMBOL "]" -> G.NMerge loc
363       | SYMBOL ";" -> G.NSemicolon loc
364       | SYMBOL "." -> G.NDot loc
365       ]
366     ];
367   nnon_punctuation_tactical:
368     [ "simple" NONA
369       [ IDENT "focus"; goals = LIST1 int -> G.NFocus (loc, goals)
370       | IDENT "unfocus" -> G.NUnfocus loc
371       | IDENT "skip" -> G.NSkip loc
372       ]
373       ];
374   ntheorem_flavour: [
375     [ [ IDENT "definition"  ] -> `Definition
376     | [ IDENT "fact"        ] -> `Fact
377     | [ IDENT "lemma"       ] -> `Lemma
378     | [ IDENT "example"     ] -> `Example
379     | [ IDENT "theorem"     ] -> `Theorem
380     | [ IDENT "corollary"   ] -> `Corollary
381     ]
382   ];
383   inductive_spec: [ [
384     fst_name = IDENT; 
385       params = LIST0 protected_binder_vars;
386     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
387     fst_constructors = LIST0 constructor SEP SYMBOL "|";
388     tl = OPT [ "with";
389         types = LIST1 [
390           name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
391          OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
392             (name, true, typ, constructors) ] SEP "with" -> types
393       ] ->
394         let params =
395           List.fold_right
396             (fun (names, typ) acc ->
397               (List.map (fun name -> (name, typ)) names) @ acc)
398             params []
399         in
400         let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
401         let tl_ind_types = match tl with None -> [] | Some types -> types in
402         let ind_types = fst_ind_type :: tl_ind_types in
403         (params, ind_types)
404     ] ];
405     
406     record_spec: [ [
407       name = IDENT; 
408       params = LIST0 protected_binder_vars;
409        SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; SYMBOL "{" ; 
410        fields = LIST0 [ 
411          name = IDENT ; 
412          coercion = [ 
413              SYMBOL ":" -> false,0 
414            | SYMBOL ":"; SYMBOL ">" -> true,0
415            | SYMBOL ":"; arity = int ; SYMBOL ">" -> true,arity
416          ]; 
417          ty = term -> 
418            let b,n = coercion in 
419            (name,ty,b,n) 
420        ] SEP SYMBOL ";"; SYMBOL "}" -> 
421         let params =
422           List.fold_right
423             (fun (names, typ) acc ->
424               (List.map (fun name -> (name, typ)) names) @ acc)
425             params []
426         in
427         (params,name,typ,fields)
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 decoration = "\\'" in
436         let ident = "\\("^alpha^ident_cont^"*"^decoration^"*\\|_"^ident_cont^"+"^decoration^"*\\)" in
437         let rex = Str.regexp ("^"^ident^"$") in
438         if Str.string_match rex id 0 then
439           if (try ignore (NReference.reference_of_string uri); true
440               with NReference.IllFormedReference _ -> false)
441           then
442             G.Ident_alias (id, uri)
443           else
444             raise
445              (HExtlib.Localized (loc, CicNotationParser.Parse_error (Printf.sprintf "Not a valid uri: %s" uri)))
446         else
447           raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
448             Printf.sprintf "Not a valid identifier: %s" id)))
449       | IDENT "symbol"; symbol = QSTRING;
450         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
451         SYMBOL "="; dsc = QSTRING ->
452           let instance =
453             match instance with Some i -> i | None -> 0
454           in
455           G.Symbol_alias (symbol, instance, dsc)
456       | IDENT "num";
457         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
458         SYMBOL "="; dsc = QSTRING ->
459           let instance =
460             match instance with Some i -> i | None -> 0
461           in
462           G.Number_alias (instance, dsc)
463       ]
464      ];
465     argument: [
466       [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
467         id = IDENT ->
468           N.IdentArg (List.length l, id)
469       ]
470     ];
471     associativity: [
472       [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
473       | IDENT "right"; IDENT "associative" -> Gramext.RightA
474       | IDENT "non"; IDENT "associative" -> Gramext.NonA
475       ]
476     ];
477     precedence: [
478       [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
479     ];
480     notation: [
481       [ dir = OPT direction; s = QSTRING;
482         assoc = OPT associativity; prec = precedence;
483         IDENT "for";
484         p2 = 
485           [ blob = UNPARSED_AST ->
486               add_raw_attribute ~text:(Printf.sprintf "@{%s}" blob)
487                 (CicNotationParser.parse_level2_ast lstatus
488                   (Ulexing.from_utf8_string blob))
489           | blob = UNPARSED_META ->
490               add_raw_attribute ~text:(Printf.sprintf "${%s}" blob)
491                 (CicNotationParser.parse_level2_meta lstatus
492                   (Ulexing.from_utf8_string blob))
493           ] ->
494             let assoc =
495               match assoc with
496               | None -> default_associativity
497               | Some assoc -> assoc
498             in
499             let p1 =
500               add_raw_attribute ~text:s
501                 (CicNotationParser.parse_level1_pattern lstatus prec
502                   (Ulexing.from_utf8_string s))
503             in
504             (dir, p1, assoc, prec, p2)
505       ]
506     ];
507     level3_term: [
508       [ r = NREF -> N.NRefPattern (NReference.reference_of_string r)
509       | IMPLICIT -> N.ImplicitPattern
510       | id = IDENT -> N.VarPattern id
511       | LPAREN; terms = LIST1 SELF; RPAREN ->
512           (match terms with
513           | [] -> assert false
514           | [term] -> term
515           | terms -> N.ApplPattern terms)
516       ]
517     ];
518     interpretation: [
519       [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
520           (s, args, t)
521       ]
522     ];
523     
524     include_command: [ [
525         IDENT "include" ; path = QSTRING -> 
526           loc,path,G.WithPreferences
527       | IDENT "include" ; IDENT "alias"; path = QSTRING -> 
528           loc,path,G.OnlyPreferences
529       | IDENT "include'" ; path = QSTRING -> 
530           loc,path,G.WithoutPreferences
531      ]];
532
533   grafite_ncommand: [ [
534       IDENT "qed" -> G.NQed loc
535     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
536       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
537         G.NObj (loc, N.Theorem (nflavour, name, typ, body,`Regular))
538     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
539       body = term ->
540         G.NObj (loc, N.Theorem (nflavour, name, N.Implicit `JustOne, Some body,`Regular))
541     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
542         G.NObj (loc, N.Theorem (`Axiom, name, typ, None, `Regular))
543     | IDENT "discriminator" ; indty = tactic_term -> G.NDiscriminator (loc,indty)
544     | IDENT "inverter"; name = IDENT; IDENT "for" ; indty = tactic_term ;
545       paramspec = OPT inverter_param_list ; 
546       outsort = OPT [ SYMBOL ":" ; outsort = term -> outsort ] -> 
547         G.NInverter (loc,name,indty,paramspec,outsort)
548     | LETCOREC ; defs = let_defs -> 
549         nmk_rec_corec `CoInductive defs loc
550     | LETREC ; defs = let_defs -> 
551         nmk_rec_corec `Inductive defs loc
552     | IDENT "inductive"; spec = inductive_spec ->
553         let (params, ind_types) = spec in
554         G.NObj (loc, N.Inductive (params, ind_types))
555     | IDENT "coinductive"; spec = inductive_spec ->
556         let (params, ind_types) = spec in
557         let ind_types = (* set inductive flags to false (coinductive) *)
558           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
559             ind_types
560         in
561         G.NObj (loc, N.Inductive (params, ind_types))
562     | IDENT "universe"; IDENT "constraint"; u1 = tactic_term; 
563         SYMBOL <:unicode<lt>> ; u2 = tactic_term ->
564         let urify = function 
565           | NotationPt.AttributedTerm (_, NotationPt.Sort (`NType i)) ->
566               NUri.uri_of_string ("cic:/matita/pts/Type"^i^".univ")
567           | _ -> raise (Failure "only a Type[…] sort can be constrained")
568         in
569         let u1 = urify u1 in
570         let u2 = urify u2 in
571          G.NUnivConstraint (loc,u1,u2)
572     | IDENT "unification"; IDENT "hint"; n = int; t = tactic_term ->
573         G.UnificationHint (loc, t, n)
574     | IDENT "coercion"; name = IDENT; SYMBOL ":"; ty = term; 
575         SYMBOL <:unicode<def>>; t = term; "on"; 
576         id = [ IDENT | PIDENT ]; SYMBOL ":"; source = term;
577         "to"; target = term ->
578           G.NCoercion(loc,name,t,ty,(id,source),target)     
579     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
580         G.NObj (loc, N.Record (params,name,ty,fields))
581     | IDENT "copy" ; s = IDENT; IDENT "from"; u = URI; "with"; 
582       m = LIST0 [ u1 = URI; SYMBOL <:unicode<mapsto>>; u2 = URI -> u1,u2 ] ->
583         G.NCopy (loc,s,NUri.uri_of_string u,
584           List.map (fun a,b -> NUri.uri_of_string a, NUri.uri_of_string b) m)
585     | lc = lexicon_command -> lc
586   ]];
587
588   lexicon_command: [ [
589       IDENT "alias" ; spec = alias_spec ->
590         G.Alias (loc, spec)
591     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
592         G.Notation (loc, dir, l1, assoc, prec, l2)
593     | IDENT "interpretation"; id = QSTRING;
594       (symbol, args, l3) = interpretation ->
595         G.Interpretation (loc, id, (symbol, args), l3)
596   ]];
597   executable: [
598     [ ncmd = grafite_ncommand; SYMBOL "." -> G.NCommand (loc, ncmd)
599     | punct = npunctuation_tactical -> G.NTactic (loc, [punct])
600     | tac = nnon_punctuation_tactical(*; punct = npunctuation_tactical*) ->
601           G.NTactic (loc, [tac])
602     | tac = ntactic (*; punct = npunctuation_tactical*) ->
603          tac 
604 (*
605     | tac = nnon_punctuation_tactical; 
606         punct = npunctuation_tactical ->
607           G.NTactic (loc, [tac; punct])
608 *)
609     ]
610   ];
611   comment: [
612     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
613        G.Code (loc, ex)
614     | str = NOTE -> 
615        G.Note (loc, str)
616     ]
617   ];
618   statement: [
619     [ ex = executable -> G.Executable (loc, ex)
620     | com = comment -> G.Comment (loc, com)
621     | (iloc,fname,mode) = include_command ; SYMBOL "."  ->
622                G.Executable (loc,G.NCommand (loc,G.Include (iloc,mode,fname)))
623     | EOI -> raise End_of_file
624     ]
625   ];
626   END;
627 (* }}} *)
628   statement
629 ;;
630
631 type db = GrafiteAst.statement Grammar.Entry.e ;;
632
633 class type g_status =
634  object
635   inherit CicNotationParser.g_status
636   method parser_db: db
637  end
638
639 class status =
640  object(self)
641   inherit CicNotationParser.status ~keywords:[]
642   val mutable db = None
643   method parser_db = match db with None -> assert false | Some x -> x
644   method set_parser_db v = {< db = Some v >}
645   method set_parser_status
646    : 'status. #g_status as 'status -> 'self
647    = fun o -> {< db = Some o#parser_db >}#set_notation_parser_status o
648   initializer
649    let grammar = CicNotationParser.level2_ast_grammar self in
650    db <- Some (mk_parser (Grammar.Entry.create grammar "statement") self)
651  end
652
653 let extend status l1 action = 
654   let status = CicNotationParser.extend status l1 action in
655   let grammar = CicNotationParser.level2_ast_grammar status in
656   status#set_parser_db
657     (mk_parser (Grammar.Entry.create grammar "statement") status)
658 ;;
659
660
661 let parse_statement status = 
662   parse_statement status#parser_db
663
664 (* vim:set foldmethod=marker: *)