]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_parser/grafiteParser.ml
urimanager removed
[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        params = nauto_params; SYMBOL "/" ; 
225        just = OPT [ IDENT "by"; by = 
226          [ univ = tactic_term_list1 -> `Univ univ
227          | SYMBOL "{"; SYMBOL "}" -> `EmptyUniv
228          | SYMBOL "_" -> `Trace ] -> by ] ->
229        let depth = match num with Some n -> n | None -> "1" in
230        (match just with
231        | None -> 
232            G.NTactic(loc,
233             [G.NAuto(loc,(None,["slir","";"depth",depth]@params))])
234        | Some (`Univ univ) ->
235            G.NTactic(loc,
236             [G.NAuto(loc,(Some univ,["slir","";"depth",depth]@params))])
237        | Some `EmptyUniv ->
238            G.NTactic(loc,
239             [G.NAuto(loc,(Some [],["slir","";"depth",depth]@params))])
240        | Some `Trace ->
241            G.NMacro(loc,
242              G.NAutoInteractive (loc, (None,["slir","";"depth",depth]@params))))
243     | IDENT "intros" -> G.NMacro (loc, G.NIntroGuess loc)
244     | IDENT "check"; t = term -> G.NMacro(loc,G.NCheck (loc,t))
245     | IDENT "screenshot"; fname = QSTRING -> 
246         G.NMacro(loc,G.Screenshot (loc, fname))
247     | IDENT "cases"; what = tactic_term ; where = pattern_spec ->
248         G.NTactic(loc,[G.NCases (loc, what, where)])
249     | IDENT "change"; what = pattern_spec; "with"; with_what = tactic_term -> 
250         G.NTactic(loc,[G.NChange (loc, what, with_what)])
251     | SYMBOL "@"; num = OPT NUMBER; l = LIST0 tactic_term -> 
252         G.NTactic(loc,[G.NConstructor (loc, (match num with None -> None | Some x -> Some (int_of_string x)),l)])
253     | IDENT "cut"; t = tactic_term -> G.NTactic(loc,[G.NCut (loc, t)])
254 (*  | IDENT "discriminate"; t = tactic_term -> G.NDiscriminate (loc, t)
255     | IDENT "subst"; t = tactic_term -> G.NSubst (loc, t) *)
256     | IDENT "destruct"; just = OPT [ dom = ident_list1 -> dom ];
257       exclude = OPT [ IDENT "skip"; skip = ident_list1 -> skip ]
258         -> let exclude' = match exclude with None -> [] | Some l -> l in
259            G.NTactic(loc,[G.NDestruct (loc,just,exclude')])
260     | IDENT "elim"; what = tactic_term ; where = pattern_spec ->
261         G.NTactic(loc,[G.NElim (loc, what, where)])
262     | IDENT "generalize"; p=pattern_spec ->
263         G.NTactic(loc,[G.NGeneralize (loc, p)])
264     | IDENT "inversion"; what = tactic_term ; where = pattern_spec ->
265         G.NTactic(loc,[G.NInversion (loc, what, where)])
266     | IDENT "lapply"; t = tactic_term -> G.NTactic(loc,[G.NLApply (loc, t)])
267     | IDENT "letin"; name = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term;
268         where = pattern_spec ->
269         G.NTactic(loc,[G.NLetIn (loc,where,t,name)])
270     | kind = nreduction_kind; p = pattern_spec ->
271         G.NTactic(loc,[G.NReduce (loc, kind, p)])
272     | dir = direction; what = tactic_term ; where = pattern_spec ->     
273         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
274     | IDENT "rewrite"; dir = direction; what = tactic_term ; where = pattern_spec ->    
275         G.NTactic(loc,[G.NRewrite (loc, dir, what, where)])
276     | IDENT "try"; tac = SELF -> 
277         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
278         G.NTactic(loc,[ G.NTry (loc,tac)])
279     | IDENT "repeat"; tac = SELF -> 
280         let tac = match tac with G.NTactic(_,[t]) -> t | _ -> assert false in
281         G.NTactic(loc,[ G.NRepeat (loc,tac)])
282     | LPAREN; l = LIST1 SELF; RPAREN -> 
283         let l = 
284           List.flatten 
285             (List.map (function G.NTactic(_,t) -> t | _ -> assert false) l) in
286         G.NTactic(loc,[G.NBlock (loc,l)])
287     | IDENT "assumption" -> G.NTactic(loc,[ G.NAssumption loc])
288     | SYMBOL "#"; ns=IDENT -> G.NTactic(loc,[ G.NIntros (loc,[ns])])
289     | SYMBOL "#"; SYMBOL "_" -> G.NTactic(loc,[ G.NIntro (loc,"_")])
290     | SYMBOL "*" -> G.NTactic(loc,[ G.NCase1 (loc,"_")])
291     | SYMBOL "*"; n=IDENT -> G.NTactic(loc,[ G.NCase1 (loc,n)])
292     ]
293   ];
294   auto_fixed_param: [
295    [ IDENT "demod"
296    | IDENT "fast_paramod"
297    | IDENT "paramod"
298    | IDENT "depth"
299    | IDENT "width"
300    | IDENT "size"
301    | IDENT "timeout"
302    | IDENT "library"
303    | IDENT "type"
304    | IDENT "all"
305    ]
306 ];
307   auto_params: [
308     [ params = 
309       LIST0 [
310          i = auto_fixed_param -> i,""
311        | i = auto_fixed_param ; SYMBOL "="; v = [ v = int ->
312               string_of_int v | v = IDENT -> v ] -> i,v ]; 
313       tl = OPT [ IDENT "by"; tl = tactic_term_list1 -> tl] -> tl,
314       (* (match tl with Some l -> l | None -> []), *)
315       params
316    ]
317 ];
318   nauto_params: [
319     [ params = 
320       LIST0 [
321          i = auto_fixed_param -> i,""
322        | i = auto_fixed_param ; SYMBOL "="; v = [ v = int ->
323               string_of_int v | v = IDENT -> v ] -> i,v ] ->
324       params
325    ]
326 ];
327
328   by_continuation: [
329     [ 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)
330     | WEPROVED; ty = tactic_term ; t1 = OPT [IDENT "that" ; IDENT "is" ; IDENT "equivalent" ; "to" ; t2 = tactic_term -> t2] ; 
331             "done" -> BYC_weproved (ty,None,t1)
332     | "done" -> BYC_done
333     | "let" ; id1 = IDENT ; SYMBOL ":" ; t1 = tactic_term ;
334       IDENT "such" ; IDENT "that" ; t2=tactic_term ; LPAREN ; 
335       id2 = IDENT ; RPAREN -> BYC_letsuchthat (id1,t1,id2,t2)
336     | WEHAVE; t1=tactic_term ; LPAREN ; id1=IDENT ; RPAREN ;"and" ; t2=tactic_term ; LPAREN ; id2=IDENT ; RPAREN ->
337               BYC_wehaveand (id1,t1,id2,t2)
338     ]
339 ];
340   rewriting_step_continuation : [
341     [ "done" -> true
342     | -> false
343     ]
344 ];
345 (* MATITA 1.0
346   atomic_tactical:
347     [ "sequence" LEFTA
348       [ t1 = SELF; SYMBOL ";"; t2 = SELF ->
349           let ts =
350             match t1 with
351             | G.Seq (_, l) -> l @ [ t2 ]
352             | _ -> [ t1; t2 ]
353           in
354           G.Seq (loc, ts)
355       ]
356     | "then" NONA
357       [ tac = SELF; SYMBOL ";";
358         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
359           (G.Then (loc, tac, tacs))
360       ]
361     | "loops" RIGHTA
362       [ IDENT "do"; count = int; tac = SELF ->
363           G.Do (loc, count, tac)
364       | IDENT "repeat"; tac = SELF -> G.Repeat (loc, tac)
365       ]
366     | "simple" NONA
367       [ IDENT "first";
368         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
369           G.First (loc, tacs)
370       | IDENT "try"; tac = SELF -> G.Try (loc, tac)
371       | IDENT "solve";
372         SYMBOL "["; tacs = LIST0 SELF SEP SYMBOL "|"; SYMBOL "]"->
373           G.Solve (loc, tacs)
374       | IDENT "progress"; tac = SELF -> G.Progress (loc, tac)
375       | LPAREN; tac = SELF; RPAREN -> tac
376       | tac = tactic -> tac
377         ]
378       ];
379 *)
380   npunctuation_tactical:
381     [
382       [ SYMBOL "[" -> G.NBranch loc
383       | SYMBOL "|" -> G.NShift loc
384       | i = LIST1 int SEP SYMBOL ","; SYMBOL ":" -> G.NPos (loc, i)
385       | SYMBOL "*"; SYMBOL ":" -> G.NWildcard loc
386       | name = IDENT; SYMBOL ":" -> G.NPosbyname (loc, name)
387       | SYMBOL "]" -> G.NMerge loc
388       | SYMBOL ";" -> G.NSemicolon loc
389       | SYMBOL "." -> G.NDot loc
390       ]
391     ];
392   nnon_punctuation_tactical:
393     [ "simple" NONA
394       [ IDENT "focus"; goals = LIST1 int -> G.NFocus (loc, goals)
395       | IDENT "unfocus" -> G.NUnfocus loc
396       | IDENT "skip" -> G.NSkip loc
397       ]
398       ];
399   ntheorem_flavour: [
400     [ [ IDENT "definition"  ] -> `Definition
401     | [ IDENT "fact"        ] -> `Fact
402     | [ IDENT "lemma"       ] -> `Lemma
403     | [ IDENT "example"     ] -> `Example
404     | [ IDENT "theorem"     ] -> `Theorem
405     | [ IDENT "corollary"   ] -> `Corollary
406     ]
407   ];
408   inductive_spec: [ [
409     fst_name = IDENT; 
410       params = LIST0 protected_binder_vars;
411     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
412     fst_constructors = LIST0 constructor SEP SYMBOL "|";
413     tl = OPT [ "with";
414         types = LIST1 [
415           name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
416          OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
417             (name, true, typ, constructors) ] SEP "with" -> types
418       ] ->
419         let params =
420           List.fold_right
421             (fun (names, typ) acc ->
422               (List.map (fun name -> (name, typ)) names) @ acc)
423             params []
424         in
425         let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
426         let tl_ind_types = match tl with None -> [] | Some types -> types in
427         let ind_types = fst_ind_type :: tl_ind_types in
428         (params, ind_types)
429     ] ];
430     
431     record_spec: [ [
432       name = IDENT; 
433       params = LIST0 protected_binder_vars;
434        SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; SYMBOL "{" ; 
435        fields = LIST0 [ 
436          name = IDENT ; 
437          coercion = [ 
438              SYMBOL ":" -> false,0 
439            | SYMBOL ":"; SYMBOL ">" -> true,0
440            | SYMBOL ":"; arity = int ; SYMBOL ">" -> true,arity
441          ]; 
442          ty = term -> 
443            let b,n = coercion in 
444            (name,ty,b,n) 
445        ] SEP SYMBOL ";"; SYMBOL "}" -> 
446         let params =
447           List.fold_right
448             (fun (names, typ) acc ->
449               (List.map (fun name -> (name, typ)) names) @ acc)
450             params []
451         in
452         (params,name,typ,fields)
453     ] ];
454
455     alias_spec: [
456       [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
457         let alpha = "[a-zA-Z]" in
458         let num = "[0-9]+" in
459         let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
460         let decoration = "\\'" in
461         let ident = "\\("^alpha^ident_cont^"*"^decoration^"*\\|_"^ident_cont^"+"^decoration^"*\\)" in
462         let rex = Str.regexp ("^"^ident^"$") in
463         if Str.string_match rex id 0 then
464           if (try ignore (NReference.reference_of_string uri); true
465               with NReference.IllFormedReference _ -> false)
466           then
467             L.Ident_alias (id, uri)
468           else
469             raise
470              (HExtlib.Localized (loc, CicNotationParser.Parse_error (Printf.sprintf "Not a valid uri: %s" uri)))
471         else
472           raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
473             Printf.sprintf "Not a valid identifier: %s" id)))
474       | IDENT "symbol"; symbol = QSTRING;
475         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
476         SYMBOL "="; dsc = QSTRING ->
477           let instance =
478             match instance with Some i -> i | None -> 0
479           in
480           L.Symbol_alias (symbol, instance, dsc)
481       | IDENT "num";
482         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
483         SYMBOL "="; dsc = QSTRING ->
484           let instance =
485             match instance with Some i -> i | None -> 0
486           in
487           L.Number_alias (instance, dsc)
488       ]
489      ];
490     argument: [
491       [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
492         id = IDENT ->
493           N.IdentArg (List.length l, id)
494       ]
495     ];
496     associativity: [
497       [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
498       | IDENT "right"; IDENT "associative" -> Gramext.RightA
499       | IDENT "non"; IDENT "associative" -> Gramext.NonA
500       ]
501     ];
502     precedence: [
503       [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
504     ];
505     notation: [
506       [ dir = OPT direction; s = QSTRING;
507         assoc = OPT associativity; prec = precedence;
508         IDENT "for";
509         p2 = 
510           [ blob = UNPARSED_AST ->
511               add_raw_attribute ~text:(Printf.sprintf "@{%s}" blob)
512                 (CicNotationParser.parse_level2_ast
513                   (Ulexing.from_utf8_string blob))
514           | blob = UNPARSED_META ->
515               add_raw_attribute ~text:(Printf.sprintf "${%s}" blob)
516                 (CicNotationParser.parse_level2_meta
517                   (Ulexing.from_utf8_string blob))
518           ] ->
519             let assoc =
520               match assoc with
521               | None -> default_associativity
522               | Some assoc -> assoc
523             in
524             let p1 =
525               add_raw_attribute ~text:s
526                 (CicNotationParser.parse_level1_pattern prec
527                   (Ulexing.from_utf8_string s))
528             in
529             (dir, p1, assoc, prec, p2)
530       ]
531     ];
532     level3_term: [
533       [ r = NREF -> N.NRefPattern (NReference.reference_of_string r)
534       | IMPLICIT -> N.ImplicitPattern
535       | id = IDENT -> N.VarPattern id
536       | LPAREN; terms = LIST1 SELF; RPAREN ->
537           (match terms with
538           | [] -> assert false
539           | [term] -> term
540           | terms -> N.ApplPattern terms)
541       ]
542     ];
543     interpretation: [
544       [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
545           (s, args, t)
546       ]
547     ];
548     
549     include_command: [ [
550         IDENT "include" ; path = QSTRING -> 
551           loc,path,true,L.WithPreferences
552       | IDENT "include" ; IDENT "source" ; path = QSTRING -> 
553           loc,path,false,L.WithPreferences        
554       | IDENT "include'" ; path = QSTRING -> 
555           loc,path,true,L.WithoutPreferences
556      ]];
557
558   grafite_ncommand: [ [
559       IDENT "qed" -> G.NQed loc
560     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
561       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
562         G.NObj (loc, N.Theorem (nflavour, name, typ, body,`Regular))
563     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
564       body = term ->
565         G.NObj (loc, N.Theorem (nflavour, name, N.Implicit `JustOne, Some body,`Regular))
566     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
567         G.NObj (loc, N.Theorem (`Axiom, name, typ, None, `Regular))
568     | IDENT "discriminator" ; indty = tactic_term -> G.NDiscriminator (loc,indty)
569     | IDENT "inverter"; name = IDENT; IDENT "for" ; indty = tactic_term ;
570       paramspec = OPT inverter_param_list ; 
571       outsort = OPT [ SYMBOL ":" ; outsort = term -> outsort ] -> 
572         G.NInverter (loc,name,indty,paramspec,outsort)
573     | NLETCOREC ; defs = let_defs -> 
574         nmk_rec_corec `CoInductive defs loc
575     | NLETREC ; defs = let_defs -> 
576         nmk_rec_corec `Inductive defs loc
577     | IDENT "inductive"; spec = inductive_spec ->
578         let (params, ind_types) = spec in
579         G.NObj (loc, N.Inductive (params, ind_types))
580     | IDENT "coinductive"; spec = inductive_spec ->
581         let (params, ind_types) = spec in
582         let ind_types = (* set inductive flags to false (coinductive) *)
583           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
584             ind_types
585         in
586         G.NObj (loc, N.Inductive (params, ind_types))
587     | IDENT "universe"; IDENT "constraint"; u1 = tactic_term; 
588         SYMBOL <:unicode<lt>> ; u2 = tactic_term ->
589         let urify = function 
590           | NotationPt.AttributedTerm (_, NotationPt.Sort (`NType i)) ->
591               NUri.uri_of_string ("cic:/matita/pts/Type"^i^".univ")
592           | _ -> raise (Failure "only a Type[…] sort can be constrained")
593         in
594         let u1 = urify u1 in
595         let u2 = urify u2 in
596          G.NUnivConstraint (loc,u1,u2)
597     | IDENT "unification"; IDENT "hint"; n = int; t = tactic_term ->
598         G.UnificationHint (loc, t, n)
599     | IDENT "coercion"; name = IDENT; SYMBOL ":"; ty = term; 
600         SYMBOL <:unicode<def>>; t = term; "on"; 
601         id = [ IDENT | PIDENT ]; SYMBOL ":"; source = term;
602         "to"; target = term ->
603           G.NCoercion(loc,name,t,ty,(id,source),target)     
604     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
605         G.NObj (loc, N.Record (params,name,ty,fields))
606     | IDENT "copy" ; s = IDENT; IDENT "from"; u = URI; "with"; 
607       m = LIST0 [ u1 = URI; SYMBOL <:unicode<mapsto>>; u2 = URI -> u1,u2 ] ->
608         G.NCopy (loc,s,NUri.uri_of_string u,
609           List.map (fun a,b -> NUri.uri_of_string a, NUri.uri_of_string b) m)
610   ]];
611
612   lexicon_command: [ [
613       IDENT "alias" ; spec = alias_spec ->
614         L.Alias (loc, spec)
615     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
616         L.Notation (loc, dir, l1, assoc, prec, l2)
617     | IDENT "interpretation"; id = QSTRING;
618       (symbol, args, l3) = interpretation ->
619         L.Interpretation (loc, id, (symbol, args), l3)
620   ]];
621   executable: [
622     [ ncmd = grafite_ncommand; SYMBOL "." -> G.NCommand (loc, ncmd)
623     | punct = npunctuation_tactical -> G.NTactic (loc, [punct])
624     | tac = nnon_punctuation_tactical(*; punct = npunctuation_tactical*) ->
625           G.NTactic (loc, [tac])
626     | tac = ntactic (*; punct = npunctuation_tactical*) ->
627          tac 
628 (*
629     | tac = nnon_punctuation_tactical; 
630         punct = npunctuation_tactical ->
631           G.NTactic (loc, [tac; punct])
632 *)
633     ]
634   ];
635   comment: [
636     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
637        G.Code (loc, ex)
638     | str = NOTE -> 
639        G.Note (loc, str)
640     ]
641   ];
642   statement: [
643     [ ex = executable ->
644        fun ?(never_include=false) ~include_paths status ->
645           let stm = G.Executable (loc, ex) in
646           !grafite_callback stm;
647           status, LSome stm
648     | com = comment ->
649        fun ?(never_include=false) ~include_paths status -> 
650           let stm = G.Comment (loc, com) in
651           !grafite_callback stm;
652           status, LSome stm
653     | (iloc,fname,normal,mode) = include_command ; SYMBOL "."  ->
654        fun ?(never_include=false) ~include_paths status ->
655         let _root, buri, fullpath, _rrelpath = 
656           Librarian.baseuri_of_script ~include_paths fname in
657         if never_include then raise (NoInclusionPerformed fullpath)
658         else
659          begin
660           let stm =
661            G.Executable
662             (loc, G.Command (loc, G.Include (iloc,fname))) in
663           !grafite_callback stm;
664           let status =
665            LE.eval_command status (L.Include (iloc,buri,mode,fullpath)) in
666           let stm =
667            G.Executable
668             (loc,G.Command (loc,G.Include (iloc,buri)))
669           in
670            status, LSome stm
671          end
672     | scom = lexicon_command ; SYMBOL "." ->
673        fun ?(never_include=false) ~include_paths status ->
674           !lexicon_callback scom;         
675           let status = LE.eval_command status scom in
676           status, LNone loc
677     | EOI -> raise End_of_file
678     ]
679   ];
680 END
681 (* }}} *)
682 ;;
683
684 let _ = initialize_parser () ;;
685
686 let exc_located_wrapper f =
687   try
688     f ()
689   with
690   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
691   | Stdpp.Exc_located (floc, Stream.Error msg) ->
692       raise (HExtlib.Localized (floc,CicNotationParser.Parse_error msg))
693   | Stdpp.Exc_located (floc, HExtlib.Localized(_,exn)) ->
694       raise
695        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
696   | Stdpp.Exc_located (floc, exn) ->
697       raise
698        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
699
700 let parse_statement lexbuf =
701   exc_located_wrapper
702     (fun () -> (Grammar.Entry.parse (Obj.magic !grafite_parser.statement) (Obj.magic lexbuf)))
703
704 let statement () = Obj.magic !grafite_parser.statement
705
706 let history = ref [] ;;
707
708 let push () =
709   LexiconSync.push ();
710   history := !grafite_parser :: !history;
711   grafite_parser := initial_parser ();
712   initialize_parser ()
713 ;;
714
715 let pop () =
716   LexiconSync.pop ();
717   match !history with
718   | [] -> assert false
719   | gp :: tail ->
720       grafite_parser := gp;
721       history := tail
722 ;;
723
724 (* vim:set foldmethod=marker: *)
725
726