]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/cicTextualParser2.ml
The pattern of a fold cannot have the "wanted" part (for the same reasons as
[helm.git] / helm / ocaml / cic_disambiguation / cicTextualParser2.ml
1 (* Copyright (C) 2004, 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 let debug = false
27 let debug_print s =
28   if debug then begin
29     prerr_endline "<NEW_TEXTUAL_PARSER>";
30     prerr_endline s;
31     prerr_endline "</NEW_TEXTUAL_PARSER>"
32   end
33
34   (** if set to true each number will have a different insance number and can
35   * thus be interpreted differently than others *)
36 let use_fresh_num_instances = false
37
38   (** does the lexer return COMMENT tokens? *)
39 let return_comments = false
40
41 open Printf
42
43 open DisambiguateTypes
44
45 exception Parse_error of Token.flocation * string
46
47 let cic_lexer = CicTextualLexer2.cic_lexer ~comments:return_comments ()
48
49 let fresh_num_instance =
50   let n = ref 0 in
51   if use_fresh_num_instances then
52     (fun () -> incr n; !n)
53   else
54     (fun () -> 0)
55
56 let choice_of_uri suri =
57   let term = CicUtil.term_of_uri (UriManager.uri_of_string suri) in
58   (suri, (fun _ _ _ -> term))
59
60 let grammar = Grammar.gcreate cic_lexer
61
62 let term = Grammar.Entry.create grammar "term"
63 let term0 = Grammar.Entry.create grammar "term0"
64 let tactic = Grammar.Entry.create grammar "tactic"
65 let tactical = Grammar.Entry.create grammar "tactical"
66 let tactical0 = Grammar.Entry.create grammar "tactical0"
67 let command = Grammar.Entry.create grammar "command"
68 let alias_spec = Grammar.Entry.create grammar "alias_spec"
69 let macro = Grammar.Entry.create grammar "macro"
70 let script = Grammar.Entry.create grammar "script"
71 let statement = Grammar.Entry.create grammar "statement"
72 let statements = Grammar.Entry.create grammar "statements"
73
74 let return_term loc term = CicAst.AttributedTerm (`Loc loc, term)
75
76 let fail floc msg =
77   let (x, y) = CicAst.loc_of_floc floc in
78   failwith (Printf.sprintf "Error at characters %d - %d: %s" x y msg)
79
80 let name_of_string = function
81   | "_" -> Cic.Anonymous
82   | s -> Cic.Name s
83
84 let string_of_name = function
85   | Cic.Anonymous -> "_"
86   | Cic.Name s -> s
87   
88 let int_opt = function
89   | None -> None
90   | Some lexeme -> Some (int_of_string lexeme)
91
92 let int_of_string s =
93   try
94     Pervasives.int_of_string s
95   with Failure _ ->
96     failwith (sprintf "Lexer failure: string_of_int \"%s\" failed" s)
97
98   (** the uri of an inductive type (a ".ind" uri) is not meaningful without an
99   * xpointer. Still, it's likely that an user who wrote "cic:/blabla/foo.ind"
100   * actually meant "cic:/blabla/foo.ind#xpointer(1/1)", i.e. the first inductive
101   * type in a block of mutual inductive types.
102   *
103   * This function performs the expansion foo.ind -> foo#xpointer..., if needed
104   *)
105 let ind_expansion uri =
106   let len = String.length uri in
107   if len >= 4 && String.sub uri (len - 4) 4 = ".ind" then
108     uri ^ "#xpointer(1/1)"
109   else
110     uri
111
112 let mk_binder_ast binder typ vars body =
113   List.fold_right
114     (fun var body ->
115        let name = name_of_string var in
116        CicAst.Binder (binder, (name, typ), body))
117     vars body
118
119 EXTEND
120   GLOBAL: term term0 statement statements;
121   int: [
122     [ num = NUM ->
123         try
124           int_of_string num
125         with Failure _ -> raise (Parse_error (loc, "integer literal expected"))
126     ]
127   ];
128   meta_subst: [
129     [ s = SYMBOL "_" -> None
130     | t = term -> Some t ]
131   ];
132   binder_low: [
133     [ SYMBOL <:unicode<Pi>>     (* Π *) -> `Pi
134     | SYMBOL <:unicode<exists>> (* ∃ *) -> `Exists
135     | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall ]
136   ];
137   binder_high: [ [ SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda ] ];
138   sort: [
139     [ "Prop" -> `Prop
140     | "Set" -> `Set
141     | "Type" -> `Type
142     | "CProp" -> `CProp ]
143   ];
144   typed_name: [
145     [ PAREN "("; i = IDENT; SYMBOL ":"; typ = term; PAREN ")" ->
146         (Cic.Name i, Some typ)
147     | i = IDENT -> (Cic.Name i, None)
148     ]
149   ];
150   subst: [
151     [ SYMBOL "\\subst";  (* to avoid catching frequent "a [1]" cases *)
152       PAREN "[";
153       substs = LIST1 [
154         i = IDENT; SYMBOL <:unicode<Assign>> (* ≔ *); t = term -> (i, t)
155       ] SEP SYMBOL ";";
156       PAREN "]" ->
157         substs
158     ]
159   ];
160   substituted_name: [ (* a subs.name is an explicit substitution subject *)
161     [ s = IDENT; subst = OPT subst -> CicAst.Ident (s, subst)
162     | s = URI; subst = OPT subst -> CicAst.Uri (ind_expansion s, subst)
163     ]
164   ];
165   name: [ (* as substituted_name with no explicit substitution *)
166     [ s = [ IDENT | SYMBOL ] -> s ]
167   ];
168   pattern: [
169     [ n = name -> (n, [])
170     | PAREN "("; head = name; vars = LIST1 typed_name; PAREN ")" ->
171         (head, vars)
172     ]
173   ];
174   arg: [
175    [ PAREN "(" ; names = LIST1 IDENT SEP SYMBOL ",";
176       SYMBOL ":"; ty = term; PAREN ")" -> names,ty
177    | name = IDENT -> [name],CicAst.Implicit
178    ]
179   ];
180   let_defs:[
181     [ defs = LIST1 [
182         name = IDENT;
183         args = LIST1 [arg = arg -> arg];
184         index_name = OPT [ IDENT "on"; idx = IDENT -> idx ];
185         ty = OPT [ SYMBOL ":" ; t = term -> t ];
186         SYMBOL <:unicode<def>> (* ≝ *);
187         t1 = term ->
188           let rec list_of_binder binder ty final_term = function
189             | [] -> final_term
190             | name::tl -> 
191                 CicAst.Binder (binder, (Cic.Name name, Some ty), 
192                   list_of_binder binder ty final_term tl)
193           in
194           let rec binder_of_arg_list binder final_term = function
195             | [] -> final_term
196             | (l,ty)::tl ->  
197                 list_of_binder binder ty 
198                   (binder_of_arg_list binder final_term tl) l
199           in
200           let t1' = binder_of_arg_list `Lambda t1 args in
201           let ty' = 
202             match ty with 
203             | None -> None
204             | Some ty -> Some (binder_of_arg_list `Pi ty args)
205           in
206           let rec get_position_of name n = function 
207             | [] -> (None,n)
208             | nam::tl -> 
209                 if nam = name then 
210                   (Some n,n) 
211                 else 
212                   (get_position_of name (n+1) tl)
213           in
214           let rec find_arg name n = function 
215             | [] -> (fail loc (sprintf "Argument %s not found" name))
216             | (l,_)::tl -> 
217                 let (got,len) = get_position_of name 0 l in
218                 (match got with 
219                 | None -> (find_arg name (n+len) tl)
220                 | Some where -> n + where)
221           in
222           let index = 
223             (match index_name with 
224              | None -> 0 
225              | (Some name) -> find_arg name 0 args)
226           in
227           ((Cic.Name name,ty'), t1', index)
228       ] SEP "and" -> defs
229     ]];
230   constructor: [ [ name = IDENT; SYMBOL ":"; typ = term -> (name, typ) ] ];
231   binder_vars: [
232       [ vars = [ l = LIST1 IDENT SEP SYMBOL "," -> l | SYMBOL "_" -> ["_"]];
233         typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
234       | PAREN "("; 
235           vars = [ l =  LIST1 IDENT SEP SYMBOL "," -> l | SYMBOL "_" -> ["_"]];
236           typ = OPT [ SYMBOL ":"; t = term -> t ]; 
237         PAREN ")" -> (vars, typ)
238       ]
239   ];
240   term0: [ [ t = term; EOI -> return_term loc t ] ];
241   term:
242     [ "letin" NONA
243       [ "let"; var = typed_name;
244         SYMBOL <:unicode<def>> (* ≝ *);
245         t1 = term; "in"; t2 = term ->
246           return_term loc (CicAst.LetIn (var, t1, t2))
247       | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
248         defs = let_defs; "in"; body = term ->
249             return_term loc (CicAst.LetRec (ind_kind, defs, body))
250       ]
251     | "binder" RIGHTA
252       [
253         b = binder_low; (vars, typ) = binder_vars; SYMBOL "."; body = term ->
254           let binder = mk_binder_ast b typ vars body in
255           return_term loc binder
256       | b = binder_high; (vars, typ) = binder_vars; SYMBOL "."; body = term ->
257           let binder = mk_binder_ast b typ vars body in
258           return_term loc binder
259       | t1 = term; SYMBOL <:unicode<to>> (* → *); t2 = term ->
260           return_term loc (CicAst.Binder (`Pi, (Cic.Anonymous, Some t1), t2))
261       ]
262     | "logic_add" LEFTA   [ (* nothing here by default *) ]
263     | "logic_mult" LEFTA  [ (* nothing here by default *) ]
264     | "logic_inv" NONA    [ (* nothing here by default *) ]
265     | "relop" LEFTA
266       [ t1 = term; SYMBOL "="; t2 = term ->
267         return_term loc (CicAst.Appl [CicAst.Symbol ("eq", 0); t1; t2])
268       ]
269     | "add" LEFTA     [ (* nothing here by default *) ]
270     | "mult" LEFTA    [ (* nothing here by default *) ]
271     | "power" LEFTA   [ (* nothing here by default *) ]
272     | "inv" NONA      [ (* nothing here by default *) ]
273     | "apply" LEFTA
274       [ t1 = term; t2 = term ->
275         let rec aux = function
276           | CicAst.Appl (hd :: tl) -> aux hd @ tl
277           | term -> [term]
278         in
279         CicAst.Appl (aux t1 @ [t2])
280       ]
281     | "simple" NONA
282       [ sort = sort -> CicAst.Sort sort
283       | n = substituted_name -> return_term loc n
284       | i = NUM -> return_term loc (CicAst.Num (i, (fresh_num_instance ())))
285       | IMPLICIT -> return_term loc CicAst.Implicit
286       | PLACEHOLDER -> return_term loc CicAst.UserInput
287       | m = META;
288         substs = [
289           PAREN "["; substs = LIST0 meta_subst SEP SYMBOL ";" ; PAREN "]" ->
290             substs
291         ] ->
292             let index =
293               try
294                 int_of_string (String.sub m 1 (String.length m - 1))
295               with Failure "int_of_string" ->
296                 fail loc ("Invalid meta variable number: " ^ m)
297             in
298             return_term loc (CicAst.Meta (index, substs))
299       | outtyp = OPT [ PAREN "["; typ = term; PAREN "]" -> typ ];
300         "match"; t = term;
301         indty_ident = OPT ["in" ; id = IDENT -> id ];
302         "with";
303         PAREN "[";
304         patterns = LIST0 [
305           lhs = pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *); rhs = term
306           ->
307             ((lhs: CicAst.case_pattern), rhs)
308         ] SEP SYMBOL "|";
309         PAREN "]" ->
310           return_term loc
311             (CicAst.Case (t, indty_ident, outtyp, patterns))
312       | PAREN "("; t1 = term; SYMBOL ":"; t2 = term; PAREN ")" ->
313           return_term loc (CicAst.Appl [CicAst.Symbol ("cast", 0); t1; t2])
314       | PAREN "("; t = term; PAREN ")" -> return_term loc t
315       ]
316     ];
317   tactic_term: [ [ t = term -> t ] ];
318   ident_list0: [
319     [ PAREN "["; idents = LIST0 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
320   ];
321   tactic_term_list1: [
322     [ tactic_terms = LIST1 tactic_term SEP SYMBOL "," -> tactic_terms ]
323   ];
324   reduction_kind: [
325     [ [ IDENT "reduce" ] -> `Reduce
326     | [ IDENT "simplify" ] -> `Simpl
327     | [ IDENT "whd" ] -> `Whd 
328     | [ IDENT "normalize" ] -> `Normalize ]
329   ];
330   pattern_spec: [
331     [ wanted = OPT term;
332       hyp_paths_and_goal_path =
333        OPT [
334         "in";
335         hyp_paths =
336          LIST0
337           [ id = IDENT ;
338             path = OPT [SYMBOL ":" ; path = term -> path ] ->
339             (id,match path with Some p -> p | None -> CicAst.UserInput) ]
340           SEP SYMBOL ";";
341         goal_path = OPT [ SYMBOL <:unicode<vdash>>; term = term -> term ] ->
342          let goal_path =
343           match goal_path with
344              None -> CicAst.UserInput
345            | Some goal_path -> goal_path
346          in
347           hyp_paths,goal_path
348        ] ->
349          let hyp_paths,goal_path =
350           match hyp_paths_and_goal_path with
351              None -> [], CicAst.UserInput
352            | Some (hyp_paths,goal_path) -> hyp_paths,goal_path
353          in
354           wanted, hyp_paths, goal_path ]
355   ];
356   direction: [
357     [ SYMBOL ">" -> `LeftToRight
358     | SYMBOL "<" -> `RightToLeft ]
359   ];
360   tactic: [
361     [ IDENT "absurd"; t = tactic_term ->
362         TacticAst.Absurd (loc, t)
363     | IDENT "apply"; t = tactic_term ->
364         TacticAst.Apply (loc, t)
365     | IDENT "assumption" ->
366         TacticAst.Assumption loc
367     | IDENT "auto";
368       depth = OPT [ IDENT "depth"; SYMBOL "="; i = NUM -> int_of_string i ];
369       width = OPT [ IDENT "width"; SYMBOL "="; i = NUM -> int_of_string i ] -> 
370           TacticAst.Auto (loc,depth,width)
371     | IDENT "clear"; id = IDENT ->
372         TacticAst.Clear (loc,id)
373     | IDENT "clearbody"; id = IDENT ->
374         TacticAst.ClearBody (loc,id)
375     | IDENT "change"; what = pattern_spec; "with"; t = tactic_term ->
376         TacticAst.Change (loc, what, t)
377     | IDENT "compare"; t = tactic_term ->
378         TacticAst.Compare (loc,t)
379     | IDENT "constructor"; n = NUM ->
380         TacticAst.Constructor (loc,int_of_string n)
381     | IDENT "contradiction" ->
382         TacticAst.Contradiction loc
383     | IDENT "cut"; t = tactic_term; ident = OPT [ "as"; id = IDENT -> id] ->
384         TacticAst.Cut (loc, ident, t)
385     | IDENT "decide"; IDENT "equality" ->
386         TacticAst.DecideEquality loc
387     | IDENT "decompose"; where = tactic_term ->
388         TacticAst.Decompose (loc, where)
389     | IDENT "discriminate"; t = tactic_term ->
390         TacticAst.Discriminate (loc, t)
391     | IDENT "elim"; t1 = tactic_term;
392       using = OPT [ "using"; using = tactic_term -> using ] ->
393         TacticAst.Elim (loc, t1, using)
394     | IDENT "elimType"; t = tactic_term ->
395         TacticAst.ElimType (loc, t)
396     | IDENT "exact"; t = tactic_term ->
397         TacticAst.Exact (loc, t)
398     | IDENT "exists" ->
399         TacticAst.Exists loc
400     | IDENT "fail" -> TacticAst.Fail loc
401     | IDENT "fold"; kind = reduction_kind; t = tactic_term; p = pattern_spec ->
402        let (pt,_,_) = p in
403         if pt <> None then
404          raise
405           (Parse_error
406             (loc,"the pattern cannot specify the term to replace, only its paths in the hypotheses and in the conclusion"))
407         else
408          TacticAst.Fold (loc, kind, t, p)
409     | IDENT "fourier" ->
410         TacticAst.Fourier loc
411     | IDENT "fwd"; hyp = IDENT; idents = OPT ident_list0 ->
412         let idents = match idents with None -> [] | Some idents -> idents in
413         TacticAst.FwdSimpl (loc, hyp, idents)
414     | IDENT "generalize"; p=pattern_spec; id = OPT ["as" ; id = IDENT -> id] ->
415        TacticAst.Generalize (loc,p,id)
416     | IDENT "goal"; n = NUM ->
417         TacticAst.Goal (loc, int_of_string n)
418     | IDENT "id" -> TacticAst.IdTac loc
419     | IDENT "injection"; t = tactic_term ->
420         TacticAst.Injection (loc, t)
421     | IDENT "intro"; ident = OPT IDENT ->
422         let idents = match ident with None -> [] | Some id -> [id] in
423         TacticAst.Intros (loc, Some 1, idents)
424     | IDENT "intros"; num = OPT [num = int -> num]; idents = OPT ident_list0 ->
425         let idents = match idents with None -> [] | Some idents -> idents in
426         TacticAst.Intros (loc, num, idents)
427     | IDENT "lapply"; 
428       depth = OPT [ IDENT "depth"; SYMBOL "="; i = NUM -> int_of_string i ];
429       what = tactic_term; 
430       to_what = OPT [ "to" ; t = tactic_term_list1 -> t ];
431       ident = OPT [ "using" ; ident = IDENT -> ident ] ->
432         let to_what = match to_what with None -> [] | Some to_what -> to_what in
433         TacticAst.LApply (loc, depth, to_what, what, ident)
434     | IDENT "left" -> TacticAst.Left loc
435     | IDENT "letin"; where = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term ->
436         TacticAst.LetIn (loc, t, where)
437     | kind = reduction_kind; p = pattern_spec ->
438         TacticAst.Reduce (loc, kind, p)
439     | IDENT "reflexivity" ->
440         TacticAst.Reflexivity loc
441     | IDENT "replace"; p = pattern_spec; "with"; t = tactic_term ->
442         TacticAst.Replace (loc, p, t)
443     | IDENT "rewrite" ; d = direction; t = tactic_term ; p = pattern_spec ->
444        let (pt,_,_) = p in
445         if pt <> None then
446          raise
447           (Parse_error
448             (loc,"the pattern cannot specify the term to rewrite, only its paths in the hypotheses and in the conclusion"))
449         else
450          TacticAst.Rewrite (loc, d, t, p)
451     | IDENT "right" ->
452         TacticAst.Right loc
453     | IDENT "ring" ->
454         TacticAst.Ring loc
455     | IDENT "split" ->
456         TacticAst.Split loc
457     | IDENT "symmetry" ->
458         TacticAst.Symmetry loc
459     | IDENT "transitivity"; t = tactic_term ->
460         TacticAst.Transitivity (loc, t)
461     ]
462   ];
463   tactical:
464     [ "sequence" LEFTA
465       [ tacticals = LIST1 NEXT SEP SYMBOL ";" ->
466           TacticAst.Seq (loc, tacticals)
467       ]
468     | "then" NONA
469       [ tac = tactical;
470         PAREN "["; tacs = LIST0 tactical SEP SYMBOL "|"; PAREN "]" ->
471           (TacticAst.Then (loc, tac, tacs))
472       ]
473     | "loops" RIGHTA
474       [ [ IDENT "do" ]; count = int; tac = tactical ->
475           TacticAst.Do (loc, count, tac)
476       | [ IDENT "repeat" ]; tac = tactical ->
477           TacticAst.Repeat (loc, tac)
478       ]
479     | "simple" NONA
480       [ IDENT "tries";
481         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
482           TacticAst.Tries (loc, tacs)
483       | IDENT "try"; tac = NEXT ->
484           TacticAst.Try (loc, tac)
485       | PAREN "("; tac = tactical; PAREN ")" -> tac
486       | tac = tactic -> TacticAst.Tactic (loc, tac)
487       ]
488     ];
489   theorem_flavour: [
490     [ [ IDENT "definition"  ] -> `Definition
491     | [ IDENT "fact"        ] -> `Fact
492     | [ IDENT "lemma"       ] -> `Lemma
493     | [ IDENT "remark"      ] -> `Remark
494     | [ IDENT "theorem"     ] -> `Theorem
495     ]
496   ];
497   inductive_spec: [ [
498     fst_name = IDENT; params = LIST0 [ arg=arg -> arg ];
499     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
500     fst_constructors = LIST0 constructor SEP SYMBOL "|";
501     tl = OPT [ "with";
502       types = LIST1 [
503         name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
504        OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
505           (name, true, typ, constructors) ] SEP "with" -> types
506     ] ->
507       let params =
508         List.fold_right
509           (fun (names, typ) acc ->
510             (List.map (fun name -> (name, typ)) names) @ acc)
511           params []
512       in
513       let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
514       let tl_ind_types = match tl with None -> [] | Some types -> types in
515       let ind_types = fst_ind_type :: tl_ind_types in
516       (params, ind_types)
517   ] ];
518   
519   record_spec: [ [
520     name = IDENT; params = LIST0 [ arg = arg -> arg ] ;
521      SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; PAREN "{" ; 
522      fields = LIST0 [ 
523        name = IDENT ; SYMBOL ":" ; ty = term -> (name,ty) 
524      ] SEP SYMBOL ";"; PAREN "}" -> 
525       let params =
526         List.fold_right
527           (fun (names, typ) acc ->
528             (List.map (fun name -> (name, typ)) names) @ acc)
529           params []
530       in
531       (params,name,typ,fields)
532   ] ];
533   
534   macro: [
535     [ [ IDENT "quit"  ] -> TacticAst.Quit loc
536 (*     | [ IDENT "abort" ] -> TacticAst.Abort loc *)
537     | [ IDENT "print" ]; name = QSTRING -> TacticAst.Print (loc, name)
538 (*     | [ IDENT "undo"   ]; steps = OPT NUM ->
539         TacticAst.Undo (loc, int_opt steps)
540     | [ IDENT "redo"   ]; steps = OPT NUM ->
541         TacticAst.Redo (loc, int_opt steps) *)
542     | [ IDENT "check"   ]; t = term ->
543         TacticAst.Check (loc, t)
544     | [ IDENT "hint" ] -> TacticAst.Hint loc
545     | [ IDENT "whelp"; "match" ] ; t = term -> 
546         TacticAst.WMatch (loc,t)
547     | [ IDENT "whelp"; IDENT "instance" ] ; t = term -> 
548         TacticAst.WInstance (loc,t)
549     | [ IDENT "whelp"; IDENT "locate" ] ; id = IDENT -> 
550         TacticAst.WLocate (loc,id)
551     | [ IDENT "whelp"; IDENT "elim" ] ; t = term ->
552         TacticAst.WElim (loc, t)
553     | [ IDENT "whelp"; IDENT "hint" ] ; t = term -> 
554         TacticAst.WHint (loc,t)
555     | [ IDENT "print" ]; name = QSTRING -> TacticAst.Print (loc, name)
556     ]
557   ];
558
559   alias_spec: [
560     [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
561       let alpha = "[a-zA-Z]" in
562       let num = "[0-9]+" in
563       let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
564       let ident = "\\("^alpha^ident_cont^"*\\|_"^ident_cont^"+\\)" in
565       let rex = Str.regexp ("^"^ident^"$") in
566       if Str.string_match rex id 0 then
567         let rex = Str.regexp 
568           ("^\\(cic:/\\|theory:/\\)"^ident^
569            "\\(/"^ident^"+\\)*\\(\\."^ident^"\\)+"^
570            "\\(#xpointer("^ num^"\\(/"^num^"\\)+)\\)?$") 
571         in
572         if Str.string_match rex uri 0 then
573           TacticAst.Ident_alias (id, uri)
574         else 
575           raise (Parse_error (loc,sprintf "Not a valid uri: %s" uri))
576       else
577         raise (Parse_error (loc,sprintf "Not a valid identifier: %s" id))
578     | IDENT "symbol"; symbol = QSTRING;
579       instance = OPT [ PAREN "("; IDENT "instance"; n = NUM; PAREN ")" -> n ];
580       SYMBOL "="; dsc = QSTRING ->
581         let instance =
582           match instance with Some i -> int_of_string i | None -> 0
583         in
584         TacticAst.Symbol_alias (symbol, instance, dsc)
585     | IDENT "num";
586       instance = OPT [ PAREN "("; IDENT "instance"; n = NUM; PAREN ")" -> n ];
587       SYMBOL "="; dsc = QSTRING ->
588         let instance =
589           match instance with Some i -> int_of_string i | None -> 0
590         in
591         TacticAst.Number_alias (instance, dsc)
592     ]
593   ];
594   
595   command: [[
596        [ IDENT "set" ]; n = QSTRING; v = QSTRING ->
597         TacticAst.Set (loc, n, v)
598     |  [ IDENT "drop" ] -> TacticAst.Drop loc
599     | [ IDENT "qed"   ] -> TacticAst.Qed loc
600     | flavour = theorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
601       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
602         TacticAst.Obj (loc,TacticAst.Theorem (flavour, name, typ, body))
603     | flavour = theorem_flavour; name = IDENT;
604       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
605         TacticAst.Obj (loc,TacticAst.Theorem (flavour, name, CicAst.Implicit, body))
606     | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
607         defs = let_defs -> 
608           let name,ty = 
609             match defs with
610             | ((Cic.Name name,Some ty),_,_) :: _ -> name,ty
611             | ((Cic.Name name,None),_,_) :: _ -> name,CicAst.Implicit
612             | _ -> assert false 
613           in
614           let body = CicAst.Ident (name,None) in
615           TacticAst.Obj (loc,TacticAst.Theorem(`Definition, name, ty,
616             Some (CicAst.LetRec (ind_kind, defs, body))))
617           
618     | [ IDENT "inductive" ]; spec = inductive_spec ->
619         let (params, ind_types) = spec in
620         TacticAst.Obj (loc,TacticAst.Inductive (params, ind_types))
621     | [ IDENT "coinductive" ]; spec = inductive_spec ->
622         let (params, ind_types) = spec in
623         let ind_types = (* set inductive flags to false (coinductive) *)
624           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
625             ind_types
626         in
627         TacticAst.Obj (loc,TacticAst.Inductive (params, ind_types))
628     | [ IDENT "coercion" ] ; name = IDENT -> 
629         TacticAst.Coercion (loc, CicAst.Ident (name,Some []))
630     | [ IDENT "coercion" ] ; name = URI -> 
631         TacticAst.Coercion (loc, CicAst.Uri (name,Some []))
632     | [ IDENT "alias"   ]; spec = alias_spec ->
633         TacticAst.Alias (loc, spec)
634     | [ IDENT "record" ]; (params,name,ty,fields) = record_spec ->
635         TacticAst.Obj (loc,TacticAst.Record (params,name,ty,fields))
636   ]];
637
638   executable: [
639     [ cmd = command; SYMBOL "." -> TacticAst.Command (loc, cmd)
640     | tac = tactical; SYMBOL "." -> TacticAst.Tactical (loc, tac)
641     | mac = macro; SYMBOL "." -> TacticAst.Macro (loc, mac)
642     ]
643   ];
644   
645   comment: [
646     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
647        TacticAst.Code (loc, ex)
648     | str = NOTE -> 
649        TacticAst.Note (loc, str)
650     ]
651   ];
652   
653   statement: [
654     [ ex = executable -> TacticAst.Executable (loc,ex)
655     | com = comment -> TacticAst.Comment (loc, com)
656     ]
657   ];
658   statements: [
659     [ l = LIST0 statement ; EOI -> l 
660     ]  
661   ];
662 END
663
664 let exc_located_wrapper f =
665   try
666     f ()
667   with
668   | Stdpp.Exc_located (floc, Stream.Error msg) ->
669       raise (Parse_error (floc, msg))
670   | Stdpp.Exc_located (floc, exn) ->
671       raise (Parse_error (floc, (Printexc.to_string exn)))
672
673 let parse_term stream =
674   exc_located_wrapper (fun () -> (Grammar.Entry.parse term0 stream))
675 let parse_statement stream =
676   exc_located_wrapper (fun () -> (Grammar.Entry.parse statement stream))
677 let parse_statements stream =
678   exc_located_wrapper (fun () -> (Grammar.Entry.parse statements stream))
679   
680
681 (**/**)
682
683 (** {2 Interface for gTopLevel} *)
684
685 module EnvironmentP3 =
686   struct
687     type t = environment
688
689     let empty = ""
690
691     let aliases_grammar = Grammar.gcreate cic_lexer
692     let aliases = Grammar.Entry.create aliases_grammar "aliases"
693
694     let to_string env =
695       let aliases =
696         Environment.fold
697           (fun domain_item (dsc, _) acc ->
698             let s =
699               match domain_item with
700               | Id id ->
701                   TacticAstPp.pp_alias (TacticAst.Ident_alias (id, dsc)) ^ "."
702               | Symbol (symb, i) ->
703                   TacticAstPp.pp_alias (TacticAst.Symbol_alias (symb, i, dsc))
704                   ^ "."
705               | Num i ->
706                   TacticAstPp.pp_alias (TacticAst.Number_alias (i, dsc)) ^ "."
707             in
708             s :: acc)
709           env []
710       in
711       String.concat "\n" (List.sort compare aliases)
712
713     EXTEND
714       GLOBAL: aliases;
715       aliases: [  (* build an environment from an aliases list *)
716         [ aliases = LIST0 alias; EOI ->
717             List.fold_left
718               (fun env (domain_item, codomain_item) ->
719                 Environment.add domain_item codomain_item env)
720               Environment.empty aliases
721         ]
722       ];
723       alias: [  (* return a pair <domain_item, codomain_item> from an alias *)
724         [ IDENT "alias";
725           choice =
726             [ IDENT "id"; id = IDENT; SYMBOL "="; suri = URI ->
727                 (Id id, choice_of_uri suri)
728             | IDENT "symbol"; symbol = QSTRING;
729               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
730               SYMBOL "="; dsc = QSTRING ->
731                 (Symbol (symbol, int_of_string instance),
732                  DisambiguateChoices.lookup_symbol_by_dsc symbol dsc)
733             | IDENT "num";
734               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
735               SYMBOL "="; dsc = QSTRING ->
736                 (Num (int_of_string instance),
737                  DisambiguateChoices.lookup_num_by_dsc dsc)
738             ] -> choice ]
739       ];
740     END
741
742     let of_string s =
743       if s = empty then
744         Environment.empty
745       else
746         exc_located_wrapper
747           (fun () -> Grammar.Entry.parse aliases (Stream.of_string s))
748   end
749
750 (* vim:set encoding=utf8: *)