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