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