]> matita.cs.unibo.it Git - helm.git/blob - matita/components/grafite_parser/grafiteParser.ml
cic module removed (RIP)
[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 (UriManager.uri_of_string uri); true
465               with UriManager.IllFormedUri _ -> false) ||
466              (try ignore (NReference.reference_of_string uri); true
467               with NReference.IllFormedReference _ -> false)
468           then
469             L.Ident_alias (id, uri)
470           else
471             raise
472              (HExtlib.Localized (loc, CicNotationParser.Parse_error (Printf.sprintf "Not a valid uri: %s" uri)))
473         else
474           raise (HExtlib.Localized (loc, CicNotationParser.Parse_error (
475             Printf.sprintf "Not a valid identifier: %s" id)))
476       | IDENT "symbol"; symbol = QSTRING;
477         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
478         SYMBOL "="; dsc = QSTRING ->
479           let instance =
480             match instance with Some i -> i | None -> 0
481           in
482           L.Symbol_alias (symbol, instance, dsc)
483       | IDENT "num";
484         instance = OPT [ LPAREN; IDENT "instance"; n = int; RPAREN -> n ];
485         SYMBOL "="; dsc = QSTRING ->
486           let instance =
487             match instance with Some i -> i | None -> 0
488           in
489           L.Number_alias (instance, dsc)
490       ]
491      ];
492     argument: [
493       [ l = LIST0 [ SYMBOL <:unicode<eta>> (* η *); SYMBOL "." -> () ];
494         id = IDENT ->
495           N.IdentArg (List.length l, id)
496       ]
497     ];
498     associativity: [
499       [ IDENT "left";  IDENT "associative" -> Gramext.LeftA
500       | IDENT "right"; IDENT "associative" -> Gramext.RightA
501       | IDENT "non"; IDENT "associative" -> Gramext.NonA
502       ]
503     ];
504     precedence: [
505       [ "with"; IDENT "precedence"; n = NUMBER -> int_of_string n ]
506     ];
507     notation: [
508       [ dir = OPT direction; s = QSTRING;
509         assoc = OPT associativity; prec = precedence;
510         IDENT "for";
511         p2 = 
512           [ blob = UNPARSED_AST ->
513               add_raw_attribute ~text:(Printf.sprintf "@{%s}" blob)
514                 (CicNotationParser.parse_level2_ast
515                   (Ulexing.from_utf8_string blob))
516           | blob = UNPARSED_META ->
517               add_raw_attribute ~text:(Printf.sprintf "${%s}" blob)
518                 (CicNotationParser.parse_level2_meta
519                   (Ulexing.from_utf8_string blob))
520           ] ->
521             let assoc =
522               match assoc with
523               | None -> default_associativity
524               | Some assoc -> assoc
525             in
526             let p1 =
527               add_raw_attribute ~text:s
528                 (CicNotationParser.parse_level1_pattern prec
529                   (Ulexing.from_utf8_string s))
530             in
531             (dir, p1, assoc, prec, p2)
532       ]
533     ];
534     level3_term: [
535       [ u = URI -> N.UriPattern (UriManager.uri_of_string u)
536       | r = NREF -> N.NRefPattern (NReference.reference_of_string r)
537       | IMPLICIT -> N.ImplicitPattern
538       | id = IDENT -> N.VarPattern id
539       | LPAREN; terms = LIST1 SELF; RPAREN ->
540           (match terms with
541           | [] -> assert false
542           | [term] -> term
543           | terms -> N.ApplPattern terms)
544       ]
545     ];
546     interpretation: [
547       [ s = CSYMBOL; args = LIST0 argument; SYMBOL "="; t = level3_term ->
548           (s, args, t)
549       ]
550     ];
551     
552     include_command: [ [
553         IDENT "include" ; path = QSTRING -> 
554           loc,path,true,L.WithPreferences
555       | IDENT "include" ; IDENT "source" ; path = QSTRING -> 
556           loc,path,false,L.WithPreferences        
557       | IDENT "include'" ; path = QSTRING -> 
558           loc,path,true,L.WithoutPreferences
559      ]];
560
561   grafite_ncommand: [ [
562       IDENT "qed" -> G.NQed loc
563     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
564       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
565         G.NObj (loc, N.Theorem (nflavour, name, typ, body,`Regular))
566     | nflavour = ntheorem_flavour; name = IDENT; SYMBOL <:unicode<def>> (* ≝ *);
567       body = term ->
568         G.NObj (loc, N.Theorem (nflavour, name, N.Implicit `JustOne, Some body,`Regular))
569     | IDENT "axiom"; name = IDENT; SYMBOL ":"; typ = term ->
570         G.NObj (loc, N.Theorem (`Axiom, name, typ, None, `Regular))
571     | IDENT "discriminator" ; indty = tactic_term -> G.NDiscriminator (loc,indty)
572     | IDENT "inverter"; name = IDENT; IDENT "for" ; indty = tactic_term ;
573       paramspec = OPT inverter_param_list ; 
574       outsort = OPT [ SYMBOL ":" ; outsort = term -> outsort ] -> 
575         G.NInverter (loc,name,indty,paramspec,outsort)
576     | NLETCOREC ; defs = let_defs -> 
577         nmk_rec_corec `CoInductive defs loc
578     | NLETREC ; defs = let_defs -> 
579         nmk_rec_corec `Inductive defs loc
580     | IDENT "inductive"; spec = inductive_spec ->
581         let (params, ind_types) = spec in
582         G.NObj (loc, N.Inductive (params, ind_types))
583     | IDENT "coinductive"; spec = inductive_spec ->
584         let (params, ind_types) = spec in
585         let ind_types = (* set inductive flags to false (coinductive) *)
586           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
587             ind_types
588         in
589         G.NObj (loc, N.Inductive (params, ind_types))
590     | IDENT "universe"; IDENT "constraint"; u1 = tactic_term; 
591         SYMBOL <:unicode<lt>> ; u2 = tactic_term ->
592         let urify = function 
593           | NotationPt.AttributedTerm (_, NotationPt.Sort (`NType i)) ->
594               NUri.uri_of_string ("cic:/matita/pts/Type"^i^".univ")
595           | _ -> raise (Failure "only a Type[…] sort can be constrained")
596         in
597         let u1 = urify u1 in
598         let u2 = urify u2 in
599          G.NUnivConstraint (loc,u1,u2)
600     | IDENT "unification"; IDENT "hint"; n = int; t = tactic_term ->
601         G.UnificationHint (loc, t, n)
602     | IDENT "coercion"; name = IDENT; SYMBOL ":"; ty = term; 
603         SYMBOL <:unicode<def>>; t = term; "on"; 
604         id = [ IDENT | PIDENT ]; SYMBOL ":"; source = term;
605         "to"; target = term ->
606           G.NCoercion(loc,name,t,ty,(id,source),target)     
607     | IDENT "record" ; (params,name,ty,fields) = record_spec ->
608         G.NObj (loc, N.Record (params,name,ty,fields))
609     | IDENT "copy" ; s = IDENT; IDENT "from"; u = URI; "with"; 
610       m = LIST0 [ u1 = URI; SYMBOL <:unicode<mapsto>>; u2 = URI -> u1,u2 ] ->
611         G.NCopy (loc,s,NUri.uri_of_string u,
612           List.map (fun a,b -> NUri.uri_of_string a, NUri.uri_of_string b) m)
613   ]];
614
615   lexicon_command: [ [
616       IDENT "alias" ; spec = alias_spec ->
617         L.Alias (loc, spec)
618     | IDENT "notation"; (dir, l1, assoc, prec, l2) = notation ->
619         L.Notation (loc, dir, l1, assoc, prec, l2)
620     | IDENT "interpretation"; id = QSTRING;
621       (symbol, args, l3) = interpretation ->
622         L.Interpretation (loc, id, (symbol, args), l3)
623   ]];
624   executable: [
625     [ ncmd = grafite_ncommand; SYMBOL "." -> G.NCommand (loc, ncmd)
626     | punct = npunctuation_tactical -> G.NTactic (loc, [punct])
627     | tac = nnon_punctuation_tactical(*; punct = npunctuation_tactical*) ->
628           G.NTactic (loc, [tac])
629     | tac = ntactic (*; punct = npunctuation_tactical*) ->
630          tac 
631 (*
632     | tac = nnon_punctuation_tactical; 
633         punct = npunctuation_tactical ->
634           G.NTactic (loc, [tac; punct])
635 *)
636     ]
637   ];
638   comment: [
639     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
640        G.Code (loc, ex)
641     | str = NOTE -> 
642        G.Note (loc, str)
643     ]
644   ];
645   statement: [
646     [ ex = executable ->
647        fun ?(never_include=false) ~include_paths status ->
648           let stm = G.Executable (loc, ex) in
649           !grafite_callback stm;
650           status, LSome stm
651     | com = comment ->
652        fun ?(never_include=false) ~include_paths status -> 
653           let stm = G.Comment (loc, com) in
654           !grafite_callback stm;
655           status, LSome stm
656     | (iloc,fname,normal,mode) = include_command ; SYMBOL "."  ->
657        fun ?(never_include=false) ~include_paths status ->
658         let _root, buri, fullpath, _rrelpath = 
659           Librarian.baseuri_of_script ~include_paths fname in
660         if never_include then raise (NoInclusionPerformed fullpath)
661         else
662          begin
663           let stm =
664            G.Executable
665             (loc, G.Command (loc, G.Include (iloc,fname))) in
666           !grafite_callback stm;
667           let status =
668            LE.eval_command status (L.Include (iloc,buri,mode,fullpath)) in
669           let stm =
670            G.Executable
671             (loc,G.Command (loc,G.Include (iloc,buri)))
672           in
673            status, LSome stm
674          end
675     | scom = lexicon_command ; SYMBOL "." ->
676        fun ?(never_include=false) ~include_paths status ->
677           !lexicon_callback scom;         
678           let status = LE.eval_command status scom in
679           status, LNone loc
680     | EOI -> raise End_of_file
681     ]
682   ];
683 END
684 (* }}} *)
685 ;;
686
687 let _ = initialize_parser () ;;
688
689 let exc_located_wrapper f =
690   try
691     f ()
692   with
693   | Stdpp.Exc_located (_, End_of_file) -> raise End_of_file
694   | Stdpp.Exc_located (floc, Stream.Error msg) ->
695       raise (HExtlib.Localized (floc,CicNotationParser.Parse_error msg))
696   | Stdpp.Exc_located (floc, HExtlib.Localized(_,exn)) ->
697       raise
698        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
699   | Stdpp.Exc_located (floc, exn) ->
700       raise
701        (HExtlib.Localized (floc,CicNotationParser.Parse_error (Printexc.to_string exn)))
702
703 let parse_statement lexbuf =
704   exc_located_wrapper
705     (fun () -> (Grammar.Entry.parse (Obj.magic !grafite_parser.statement) (Obj.magic lexbuf)))
706
707 let statement () = Obj.magic !grafite_parser.statement
708
709 let history = ref [] ;;
710
711 let push () =
712   LexiconSync.push ();
713   history := !grafite_parser :: !history;
714   grafite_parser := initial_parser ();
715   initialize_parser ()
716 ;;
717
718 let pop () =
719   LexiconSync.pop ();
720   match !history with
721   | [] -> assert false
722   | gp :: tail ->
723       grafite_parser := gp;
724       history := tail
725 ;;
726
727 (* vim:set foldmethod=marker: *)
728
729