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