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