]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/cicTextualParser2.ml
737673e143f45949ebec70a2cbb23ac434662ce9
[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 = LIST1 IDENT SEP SYMBOL ",";
233         typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
234       | PAREN "("; vars = LIST1 IDENT SEP SYMBOL ",";
235         typ = OPT [ SYMBOL ":"; t = term -> t ]; PAREN ")" -> (vars, typ)
236       ]
237   ];
238   term0: [ [ t = term; EOI -> return_term loc t ] ];
239   term:
240     [ "letin" NONA
241       [ "let"; var = typed_name;
242         SYMBOL <:unicode<def>> (* ≝ *);
243         t1 = term; "in"; t2 = term ->
244           return_term loc (CicAst.LetIn (var, t1, t2))
245       | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
246         defs = let_defs; "in"; body = term ->
247             return_term loc (CicAst.LetRec (ind_kind, defs, body))
248       ]
249     | "binder" RIGHTA
250       [
251         b = binder_low; (vars, typ) = binder_vars; SYMBOL "."; body = term ->
252           let binder = mk_binder_ast b typ vars body in
253           return_term loc binder
254       | b = binder_high; (vars, typ) = binder_vars; SYMBOL "."; body = term ->
255           let binder = mk_binder_ast b typ vars body in
256           return_term loc binder
257       | t1 = term; SYMBOL <:unicode<to>> (* → *); t2 = term ->
258           return_term loc (CicAst.Binder (`Pi, (Cic.Anonymous, Some t1), t2))
259       ]
260     | "logic_add" LEFTA   [ (* nothing here by default *) ]
261     | "logic_mult" LEFTA  [ (* nothing here by default *) ]
262     | "logic_inv" NONA    [ (* nothing here by default *) ]
263     | "relop" LEFTA
264       [ t1 = term; SYMBOL "="; t2 = term ->
265         return_term loc (CicAst.Appl [CicAst.Symbol ("eq", 0); t1; t2])
266       ]
267     | "add" LEFTA     [ (* nothing here by default *) ]
268     | "mult" LEFTA    [ (* nothing here by default *) ]
269     | "power" LEFTA   [ (* nothing here by default *) ]
270     | "inv" NONA      [ (* nothing here by default *) ]
271     | "apply" LEFTA
272       [ t1 = term; t2 = term ->
273         let rec aux = function
274           | CicAst.Appl (hd :: tl) -> aux hd @ tl
275           | term -> [term]
276         in
277         CicAst.Appl (aux t1 @ [t2])
278       ]
279     | "simple" NONA
280       [ sort = sort -> CicAst.Sort sort
281       | n = substituted_name -> return_term loc n
282       | i = NUM -> return_term loc (CicAst.Num (i, (fresh_num_instance ())))
283       | IMPLICIT -> return_term loc CicAst.Implicit
284       | PLACEHOLDER -> return_term loc CicAst.UserInput
285       | m = META;
286         substs = [
287           PAREN "["; substs = LIST0 meta_subst SEP SYMBOL ";" ; PAREN "]" ->
288             substs
289         ] ->
290             let index =
291               try
292                 int_of_string (String.sub m 1 (String.length m - 1))
293               with Failure "int_of_string" ->
294                 fail loc ("Invalid meta variable number: " ^ m)
295             in
296             return_term loc (CicAst.Meta (index, substs))
297       | outtyp = OPT [ PAREN "["; typ = term; PAREN "]" -> typ ];
298         "match"; t = term;
299         indty_ident = OPT ["in" ; id = IDENT -> id ];
300         "with";
301         PAREN "[";
302         patterns = LIST0 [
303           lhs = pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *); rhs = term
304           ->
305             ((lhs: CicAst.case_pattern), rhs)
306         ] SEP SYMBOL "|";
307         PAREN "]" ->
308           return_term loc
309             (CicAst.Case (t, indty_ident, outtyp, patterns))
310       | PAREN "("; t1 = term; SYMBOL ":"; t2 = term; PAREN ")" ->
311           return_term loc (CicAst.Appl [CicAst.Symbol ("cast", 0); t1; t2])
312       | PAREN "("; t = term; PAREN ")" -> return_term loc t
313       ]
314     ];
315   tactic_where: [
316     [ where = OPT [ "in"; ident = IDENT -> ident ] -> where ]
317   ];
318   tactic_term: [ [ t = term -> t ] ];
319   ident_list0: [
320     [ PAREN "["; idents = LIST0 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
321   ];
322   ident_list1: [
323     [ PAREN "["; idents = LIST1 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
324   ];
325   reduction_kind: [
326     [ [ IDENT "reduce" ] -> `Reduce
327     | [ IDENT "simplify" ] -> `Simpl
328     | [ IDENT "whd" ] -> `Whd 
329     | [ IDENT "normalize" ] -> `Normalize ]
330   ];
331   pattern_spec: [
332     [ "in";
333       hyp_paths =
334        LIST0
335         [ id = IDENT ;
336           path = OPT [SYMBOL ":" ; path = term -> path ] ->
337           (id,match path with Some p -> p | None -> CicAst.UserInput) ]
338         SEP SYMBOL ";";
339       goal_path = OPT [ SYMBOL <:unicode<vdash>>; term = term -> term ] ->
340         (hyp_paths, goal_path) ]
341   ];
342   direction: [
343     [ IDENT "left" -> `Left
344     | SYMBOL ">" -> `Left
345     | IDENT "right" -> `Right
346     | SYMBOL "<" -> `Right ]
347   ];
348   tactic: [
349     [ [ IDENT "absurd" ]; t = tactic_term ->
350         TacticAst.Absurd (loc, t)
351     | [ IDENT "apply" ]; t = tactic_term ->
352         TacticAst.Apply (loc, t)
353     | [ IDENT "assumption" ] ->
354         TacticAst.Assumption loc
355     | [ IDENT "auto" ] ; num = OPT [ i = NUM -> int_of_string i ] -> 
356           TacticAst.Auto (loc,num)
357     | [ IDENT "change" ];
358       t1 = tactic_term; "with"; t2 = tactic_term;
359       where = tactic_where ->
360         TacticAst.Change (loc, t1, t2, where)
361     (* TODO Change_pattern *)
362     | [ IDENT "contradiction" ] ->
363         TacticAst.Contradiction loc
364     | [ IDENT "cut" ];
365       t = tactic_term ->
366         TacticAst.Cut (loc, t)
367     | [ IDENT "decompose" ];
368       principles = ident_list1; where = IDENT ->
369         TacticAst.Decompose (loc, where, principles)
370     | [ IDENT "discriminate" ];
371       t = tactic_term ->
372         TacticAst.Discriminate (loc, t)
373     | [ IDENT "elimType" ]; t = tactic_term ->
374         TacticAst.ElimType (loc, t)
375     | [ IDENT "elim" ];
376       t1 = tactic_term;
377       using = OPT [ "using"; using = tactic_term -> using ] ->
378         TacticAst.Elim (loc, t1, using)
379     | [ IDENT "exact" ]; t = tactic_term ->
380         TacticAst.Exact (loc, t)
381     | [ IDENT "exists" ] ->
382         TacticAst.Exists loc
383     | [ IDENT "fold" ];
384       kind = reduction_kind; t = tactic_term ->
385         TacticAst.Fold (loc, kind, t)
386     | [ IDENT "fourier" ] ->
387         TacticAst.Fourier loc
388     | IDENT "goal"; n = NUM -> TacticAst.Goal (loc, int_of_string n)
389     | [ IDENT "injection" ]; ident = IDENT ->
390         TacticAst.Injection (loc, ident)
391     | [ IDENT "intros" ];
392       num = OPT [ num = int -> num ];
393       idents = OPT ident_list0 ->
394         let idents = match idents with None -> [] | Some idents -> idents in
395         TacticAst.Intros (loc, num, idents)
396     | [ IDENT "intro" ] ->
397         TacticAst.Intros (loc, Some 1, [])
398     | [ IDENT "left" ] -> TacticAst.Left loc
399     | [ IDENT "letin" ];
400        where = IDENT ; SYMBOL <:unicode<def>> ; t = tactic_term ->
401         TacticAst.LetIn (loc, t, where)
402     | kind = reduction_kind;
403       p = OPT [ pattern_spec ] ->
404         let p = match p with None -> [], None | Some p -> p in
405         TacticAst.Reduce (loc, kind, p)
406     | IDENT "generalize"; t = tactic_term; p = OPT [ pattern_spec ] ->
407        let p = match p with None -> [], None | Some p -> p in
408        TacticAst.Generalize (loc,t,p)
409     | [ IDENT "reflexivity" ] ->
410         TacticAst.Reflexivity loc
411     | [ IDENT "replace" ];
412       t1 = tactic_term; "with"; t2 = tactic_term ->
413         TacticAst.Replace (loc, t1, t2)
414     | IDENT "rewrite" ; d = direction; t = term ;
415       p = OPT [ pattern_spec ] ->
416         let p = match p with None -> [], None | Some p -> p in
417         TacticAst.Rewrite (loc, d, t, p)
418     | [ IDENT "right" ] -> TacticAst.Right loc
419     | [ IDENT "ring" ] -> TacticAst.Ring loc
420     | [ IDENT "split" ] -> TacticAst.Split loc
421     | [ IDENT "symmetry" ] ->
422         TacticAst.Symmetry loc
423     | [ IDENT "transitivity" ];
424       t = tactic_term ->
425         TacticAst.Transitivity (loc, t)
426     | [ IDENT "fwd" ]; name = IDENT ->
427         TacticAst.FwdSimpl (loc, name)
428     | [ IDENT "lapply" ]; t = term ->
429         TacticAst.LApply (loc, t, [])
430     ]
431   ];
432   tactical:
433     [ "sequence" LEFTA
434       [ tacticals = LIST1 NEXT SEP SYMBOL ";" ->
435           TacticAst.Seq (loc, tacticals)
436       ]
437     | "then" NONA
438       [ tac = tactical;
439         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
440           (TacticAst.Then (loc, tac, tacs))
441       ]
442     | "loops" RIGHTA
443       [ [ IDENT "do" ]; count = int; tac = tactical ->
444           TacticAst.Do (loc, count, tac)
445       | [ IDENT "repeat" ]; tac = tactical ->
446           TacticAst.Repeat (loc, tac)
447       ]
448     | "simple" NONA
449       [ IDENT "tries";
450         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
451           TacticAst.Tries (loc, tacs)
452       | IDENT "try"; tac = NEXT ->
453           TacticAst.Try (loc, tac)
454       | IDENT "fail" -> TacticAst.Fail loc
455       | IDENT "id" -> TacticAst.IdTac loc
456       | PAREN "("; tac = tactical; PAREN ")" -> tac
457       | tac = tactic -> TacticAst.Tactic (loc, tac)
458       ]
459     ];
460   theorem_flavour: [
461     [ [ IDENT "definition"  ] -> `Definition
462     | [ IDENT "fact"        ] -> `Fact
463     | [ IDENT "lemma"       ] -> `Lemma
464     | [ IDENT "remark"      ] -> `Remark
465     | [ IDENT "theorem"     ] -> `Theorem
466     ]
467   ];
468   inductive_spec: [ [
469     fst_name = IDENT; params = LIST0 [ arg=arg -> arg ];
470     SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
471     fst_constructors = LIST0 constructor SEP SYMBOL "|";
472     tl = OPT [ "with";
473       types = LIST1 [
474         name = IDENT; SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>;
475        OPT SYMBOL "|"; constructors = LIST0 constructor SEP SYMBOL "|" ->
476           (name, true, typ, constructors) ] SEP "with" -> types
477     ] ->
478       let params =
479         List.fold_right
480           (fun (names, typ) acc ->
481             (List.map (fun name -> (name, typ)) names) @ acc)
482           params []
483       in
484       let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
485       let tl_ind_types = match tl with None -> [] | Some types -> types in
486       let ind_types = fst_ind_type :: tl_ind_types in
487       (params, ind_types)
488   ] ];
489   
490   record_spec: [ [
491     name = IDENT; params = LIST0 [ arg = arg -> arg ] ;
492      SYMBOL ":"; typ = term; SYMBOL <:unicode<def>>; PAREN "{" ; 
493      fields = LIST0 [ 
494        name = IDENT ; SYMBOL ":" ; ty = term -> (name,ty) 
495      ] SEP SYMBOL ";"; PAREN "}" -> 
496       let params =
497         List.fold_right
498           (fun (names, typ) acc ->
499             (List.map (fun name -> (name, typ)) names) @ acc)
500           params []
501       in
502       (params,name,typ,fields)
503   ] ];
504   
505   macro: [
506     [ [ IDENT "quit"  ] -> TacticAst.Quit loc
507 (*     | [ IDENT "abort" ] -> TacticAst.Abort loc *)
508     | [ IDENT "print" ]; name = QSTRING -> TacticAst.Print (loc, name)
509 (*     | [ IDENT "undo"   ]; steps = OPT NUM ->
510         TacticAst.Undo (loc, int_opt steps)
511     | [ IDENT "redo"   ]; steps = OPT NUM ->
512         TacticAst.Redo (loc, int_opt steps) *)
513     | [ IDENT "check"   ]; t = term ->
514         TacticAst.Check (loc, t)
515     | [ IDENT "hint" ] -> TacticAst.Hint loc
516     | [ IDENT "whelp"; "match" ] ; t = term -> 
517         TacticAst.WMatch (loc,t)
518     | [ IDENT "whelp"; IDENT "instance" ] ; t = term -> 
519         TacticAst.WInstance (loc,t)
520     | [ IDENT "whelp"; IDENT "locate" ] ; id = IDENT -> 
521         TacticAst.WLocate (loc,id)
522     | [ IDENT "whelp"; IDENT "elim" ] ; t = term ->
523         TacticAst.WElim (loc, t)
524     | [ IDENT "whelp"; IDENT "hint" ] ; t = term -> 
525         TacticAst.WHint (loc,t)
526     | [ IDENT "print" ]; name = QSTRING -> TacticAst.Print (loc, name)
527     ]
528   ];
529
530   alias_spec: [
531     [ IDENT "id"; id = QSTRING; SYMBOL "="; uri = QSTRING ->
532       let alpha = "[a-zA-Z]" in
533       let num = "[0-9]+" in
534       let ident_cont = "\\("^alpha^"\\|"^num^"\\|_\\|\\\\\\)" in
535       let ident = "\\("^alpha^ident_cont^"*\\|_"^ident_cont^"+\\)" in
536       let rex = Str.regexp ("^"^ident^"$") in
537       if Str.string_match rex id 0 then
538         let rex = Str.regexp 
539           ("^\\(cic:/\\|theory:/\\)"^ident^
540            "\\(/"^ident^"+\\)*\\(\\."^ident^"\\)+"^
541            "\\(#xpointer("^ num^"\\(/"^num^"\\)+)\\)?$") 
542         in
543         if Str.string_match rex uri 0 then
544           TacticAst.Ident_alias (id, uri)
545         else 
546           raise (Parse_error (loc,sprintf "Not a valid uri: %s" uri))
547       else
548         raise (Parse_error (loc,sprintf "Not a valid identifier: %s" id))
549     | IDENT "symbol"; symbol = QSTRING;
550       instance = OPT [ PAREN "("; IDENT "instance"; n = NUM; PAREN ")" -> n ];
551       SYMBOL "="; dsc = QSTRING ->
552         let instance =
553           match instance with Some i -> int_of_string i | None -> 0
554         in
555         TacticAst.Symbol_alias (symbol, instance, dsc)
556     | IDENT "num";
557       instance = OPT [ PAREN "("; IDENT "instance"; n = NUM; PAREN ")" -> n ];
558       SYMBOL "="; dsc = QSTRING ->
559         let instance =
560           match instance with Some i -> int_of_string i | None -> 0
561         in
562         TacticAst.Number_alias (instance, dsc)
563     ]
564   ];
565   
566   command: [[
567       [ IDENT "set"    ]; n = QSTRING; v = QSTRING ->
568         TacticAst.Set (loc, n, v)
569     | [ IDENT "qed"   ] -> TacticAst.Qed loc
570     | flavour = theorem_flavour; name = IDENT; SYMBOL ":"; typ = term;
571       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
572         TacticAst.Obj (loc,TacticAst.Theorem (flavour, name, typ, body))
573     | flavour = theorem_flavour; name = IDENT;
574       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
575         TacticAst.Obj (loc,TacticAst.Theorem (flavour, name, CicAst.Implicit, body))
576     | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
577         defs = let_defs -> 
578           let name,ty = 
579             match defs with
580             | ((Cic.Name name,Some ty),_,_) :: _ -> name,ty
581             | ((Cic.Name name,None),_,_) :: _ -> name,CicAst.Implicit
582             | _ -> assert false 
583           in
584           let body = CicAst.Ident (name,None) in
585           TacticAst.Obj (loc,TacticAst.Theorem(`Definition, name, ty,
586             Some (CicAst.LetRec (ind_kind, defs, body))))
587           
588     | [ IDENT "inductive" ]; spec = inductive_spec ->
589         let (params, ind_types) = spec in
590         TacticAst.Obj (loc,TacticAst.Inductive (params, ind_types))
591     | [ IDENT "coinductive" ]; spec = inductive_spec ->
592         let (params, ind_types) = spec in
593         let ind_types = (* set inductive flags to false (coinductive) *)
594           List.map (fun (name, _, term, ctors) -> (name, false, term, ctors))
595             ind_types
596         in
597         TacticAst.Obj (loc,TacticAst.Inductive (params, ind_types))
598     | [ IDENT "coercion" ] ; name = IDENT -> 
599         TacticAst.Coercion (loc, CicAst.Ident (name,Some []))
600     | [ IDENT "coercion" ] ; name = URI -> 
601         TacticAst.Coercion (loc, CicAst.Uri (name,Some []))
602     | [ IDENT "alias"   ]; spec = alias_spec ->
603         TacticAst.Alias (loc, spec)
604     | [ IDENT "record" ]; (params,name,ty,fields) = record_spec ->
605         TacticAst.Obj (loc,TacticAst.Record (params,name,ty,fields))
606   ]];
607
608   executable: [
609     [ cmd = command; SYMBOL "." -> TacticAst.Command (loc, cmd)
610     | tac = tactical; SYMBOL "." -> TacticAst.Tactical (loc, tac)
611     | mac = macro; SYMBOL "." -> TacticAst.Macro (loc, mac)
612     ]
613   ];
614   
615   comment: [
616     [ BEGINCOMMENT ; ex = executable ; ENDCOMMENT -> 
617        TacticAst.Code (loc, ex)
618     | str = NOTE -> 
619        TacticAst.Note (loc, str)
620     ]
621   ];
622   
623   statement: [
624     [ ex = executable -> TacticAst.Executable (loc,ex)
625     | com = comment -> TacticAst.Comment (loc, com)
626     ]
627   ];
628   statements: [
629     [ l = LIST0 statement ; EOI -> l 
630     ]  
631   ];
632 END
633
634 let exc_located_wrapper f =
635   try
636     f ()
637   with
638   | Stdpp.Exc_located (floc, Stream.Error msg) ->
639       raise (Parse_error (floc, msg))
640   | Stdpp.Exc_located (floc, exn) ->
641       raise (Parse_error (floc, (Printexc.to_string exn)))
642
643 let parse_term stream =
644   exc_located_wrapper (fun () -> (Grammar.Entry.parse term0 stream))
645 let parse_statement stream =
646   exc_located_wrapper (fun () -> (Grammar.Entry.parse statement stream))
647 let parse_statements stream =
648   exc_located_wrapper (fun () -> (Grammar.Entry.parse statements stream))
649   
650
651 (**/**)
652
653 (** {2 Interface for gTopLevel} *)
654
655 module EnvironmentP3 =
656   struct
657     type t = environment
658
659     let empty = ""
660
661     let aliases_grammar = Grammar.gcreate cic_lexer
662     let aliases = Grammar.Entry.create aliases_grammar "aliases"
663
664     let to_string env =
665       let aliases =
666         Environment.fold
667           (fun domain_item (dsc, _) acc ->
668             let s =
669               match domain_item with
670               | Id id ->
671                   TacticAstPp.pp_alias (TacticAst.Ident_alias (id, dsc)) ^ "."
672               | Symbol (symb, i) ->
673                   TacticAstPp.pp_alias (TacticAst.Symbol_alias (symb, i, dsc))
674                   ^ "."
675               | Num i ->
676                   TacticAstPp.pp_alias (TacticAst.Number_alias (i, dsc)) ^ "."
677             in
678             s :: acc)
679           env []
680       in
681       String.concat "\n" (List.sort compare aliases)
682
683     EXTEND
684       GLOBAL: aliases;
685       aliases: [  (* build an environment from an aliases list *)
686         [ aliases = LIST0 alias; EOI ->
687             List.fold_left
688               (fun env (domain_item, codomain_item) ->
689                 Environment.add domain_item codomain_item env)
690               Environment.empty aliases
691         ]
692       ];
693       alias: [  (* return a pair <domain_item, codomain_item> from an alias *)
694         [ IDENT "alias";
695           choice =
696             [ IDENT "id"; id = IDENT; SYMBOL "="; suri = URI ->
697                 (Id id, choice_of_uri suri)
698             | IDENT "symbol"; symbol = QSTRING;
699               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
700               SYMBOL "="; dsc = QSTRING ->
701                 (Symbol (symbol, int_of_string instance),
702                  DisambiguateChoices.lookup_symbol_by_dsc symbol dsc)
703             | IDENT "num";
704               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
705               SYMBOL "="; dsc = QSTRING ->
706                 (Num (int_of_string instance),
707                  DisambiguateChoices.lookup_num_by_dsc dsc)
708             ] -> choice ]
709       ];
710     END
711
712     let of_string s =
713       if s = empty then
714         Environment.empty
715       else
716         exc_located_wrapper
717           (fun () -> Grammar.Entry.parse aliases (Stream.of_string s))
718   end
719
720 (* vim:set encoding=utf8: *)