]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/cicTextualParser2.ml
- enriched Parse_error exception with error location
[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 = true
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 open Printf
39 open DisambiguateTypes
40
41 exception Parse_error of Token.flocation * string
42
43 let fresh_num_instance =
44   let n = ref 0 in
45   if use_fresh_num_instances then
46     (fun () -> incr n; !n)
47   else
48     (fun () -> 0)
49
50 let choice_of_uri uri =
51   let term = CicUtil.term_of_uri uri in
52   (uri, (fun _ _ _ -> term))
53
54 let grammar = Grammar.gcreate CicTextualLexer2.cic_lexer
55
56 let term = Grammar.Entry.create grammar "term"
57 let term0 = Grammar.Entry.create grammar "term0"
58 let tactic = Grammar.Entry.create grammar "tactic"
59 let tactical = Grammar.Entry.create grammar "tactical"
60 let tactical0 = Grammar.Entry.create grammar "tactical0"
61 let command = Grammar.Entry.create grammar "command"
62
63 let return_term loc term = CicAst.AttributedTerm (`Loc loc, term)
64 let return_tactic loc tactic = TacticAst.LocatedTactic (loc, tactic)
65 let return_tactical loc tactical = TacticAst.LocatedTactical (loc, tactical)
66 let return_command loc cmd = cmd
67
68 let fail floc msg =
69   let (x, y) = CicAst.loc_of_floc floc in
70   failwith (Printf.sprintf "Error at characters %d - %d: %s" x y msg)
71
72 let name_of_string = function
73   | "_" -> Cic.Anonymous
74   | s -> Cic.Name s
75
76 let int_opt = function
77   | None -> None
78   | Some lexeme -> Some (int_of_string lexeme)
79
80 EXTEND
81   GLOBAL: term term0 tactic tactical tactical0 command;
82   int: [
83     [ num = NUM ->
84         try
85           int_of_string num
86         with Failure _ -> raise (Parse_error (loc, "integer literal expected"))
87     ]
88   ];
89   meta_subst: [
90     [ s = SYMBOL "_" -> None
91     | t = term -> Some t ]
92   ];
93   binder: [
94     [ SYMBOL <:unicode<lambda>> (* λ *) -> `Lambda
95     | SYMBOL <:unicode<Pi>>     (* Π *) -> `Pi
96     | SYMBOL <:unicode<exists>> (* ∃ *) -> `Exists
97     | SYMBOL <:unicode<forall>> (* ∀ *) -> `Forall ]
98   ];
99   sort: [
100     [ "Prop" -> `Prop
101     | "Set" -> `Set
102     | "Type" -> `Type
103     | "CProp" -> `CProp ]
104   ];
105   typed_name: [
106     [ PAREN "("; i = IDENT; SYMBOL ":"; typ = term; PAREN ")" ->
107         (name_of_string i, Some typ)
108     | i = IDENT -> (name_of_string i, None)
109     ]
110   ];
111   substituted_name: [ (* a subs.name is an explicit substitution subject *)
112     [ s = IDENT;
113       subst = OPT [
114         SYMBOL "\\subst";  (* to avoid catching frequent "a [1]" cases *)
115         PAREN "[";
116         substs = LIST1 [
117           i = IDENT; SYMBOL <:unicode<Assign>> (* ≔ *); t = term -> (i, t)
118         ] SEP SYMBOL ";";
119         PAREN "]" ->
120           substs
121       ] ->
122         CicAst.Ident (s, subst)
123     ]
124   ];
125   name: [ (* as substituted_name with no explicit substitution *)
126     [ s = [ IDENT | SYMBOL ] -> s ]
127   ];
128   pattern: [
129     [ n = name -> (n, [])
130     | PAREN "("; head = name; vars = LIST1 typed_name; PAREN ")" ->
131         (head, vars)
132     ]
133   ];
134   constructor: [ [ name = IDENT; SYMBOL ":"; typ = term -> (name, typ) ] ];
135   term0: [ [ t = term; EOI -> return_term loc t ] ];
136   term:
137     [ "letin" NONA
138       [ "let"; var = typed_name;
139         SYMBOL "="; (* SYMBOL <:unicode<def>> (* ≝ *); *)
140         t1 = term; "in"; t2 = term ->
141           return_term loc (CicAst.LetIn (var, t1, t2))
142       | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
143           defs = LIST1 [
144             var = typed_name;
145             index = OPT [ PAREN "("; index = NUM; PAREN ")" ->
146               int_of_string index
147             ];
148             SYMBOL "="; (* SYMBOL <:unicode<def>> (* ≝ *); *)
149             t1 = term ->
150               (var, t1, (match index with None -> 0 | Some i -> i))
151           ] SEP "and";
152           "in"; body = term ->
153             return_term loc (CicAst.LetRec (ind_kind, defs, body))
154       ]
155     | "binder" RIGHTA
156       [
157         b = binder;
158         (vars, typ) =
159           [ vars = LIST1 IDENT SEP SYMBOL ",";
160             typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
161           | PAREN "("; vars = LIST1 IDENT SEP SYMBOL ",";
162             typ = OPT [ SYMBOL ":"; t = term -> t ]; PAREN ")" -> (vars, typ)
163           ];
164         SYMBOL "."; body = term ->
165           let binder =
166             List.fold_right
167               (fun var body ->
168                 let name = name_of_string var in
169                 CicAst.Binder (b, (name, typ), body))
170               vars body
171           in
172           return_term loc binder
173       | t1 = term; SYMBOL <:unicode<to>> (* → *); t2 = term ->
174             return_term loc
175               (CicAst.Binder (`Pi, (Cic.Anonymous, Some t1), t2))
176       ]
177     | "logic_add" LEFTA   [ (* nothing here by default *) ]
178     | "logic_mult" LEFTA  [ (* nothing here by default *) ]
179     | "logic_inv" NONA    [ (* nothing here by default *) ]
180     | "relop" LEFTA
181       [ t1 = term; SYMBOL "="; t2 = term ->
182         return_term loc (CicAst.Appl [CicAst.Symbol ("eq", 0); t1; t2])
183       ]
184     | "add" LEFTA     [ (* nothing here by default *) ]
185     | "mult" LEFTA    [ (* nothing here by default *) ]
186     | "power" LEFTA   [ (* nothing here by default *) ]
187     | "inv" NONA      [ (* nothing here by default *) ]
188     | "apply" LEFTA
189       [ t1 = term; t2 = term ->
190         let rec aux = function
191           | CicAst.Appl (hd :: tl) -> aux hd @ tl
192           | term -> [term]
193         in
194         CicAst.Appl (aux t1 @ [t2])
195       ]
196     | "simple" NONA
197       [ sort = sort -> CicAst.Sort sort
198       | n = substituted_name -> return_term loc n
199       | i = NUM -> return_term loc (CicAst.Num (i, (fresh_num_instance ())))
200       | IMPLICIT -> return_term loc CicAst.Implicit
201       | m = META;
202         substs = [
203           PAREN "["; substs = LIST0 meta_subst SEP SYMBOL ";" ; PAREN "]" ->
204             substs
205         ] ->
206             let index =
207               try
208                 int_of_string (String.sub m 1 (String.length m - 1))
209               with Failure "int_of_string" ->
210                 fail loc ("Invalid meta variable number: " ^ m)
211             in
212             return_term loc (CicAst.Meta (index, substs))
213       | outtyp = OPT [ PAREN "["; typ = term; PAREN "]" -> typ ];
214         "match"; t = term;
215         indty_ident = OPT [ SYMBOL ":"; id = IDENT -> id ];
216         "with";
217         PAREN "[";
218         patterns = LIST0 [
219           lhs = pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *); rhs = term ->
220             ((lhs: CicAst.case_pattern), rhs)
221         ] SEP SYMBOL "|";
222         PAREN "]" ->
223           return_term loc
224             (CicAst.Case (t, indty_ident, outtyp, patterns))
225       | PAREN "("; t1 = term; SYMBOL ":"; t2 = term; PAREN ")" ->
226           return_term loc (CicAst.Appl [CicAst.Symbol ("cast", 0); t1; t2])
227       | PAREN "("; t = term; PAREN ")" -> return_term loc t
228       ]
229     ];
230   tactic_where: [
231     [ where = OPT [ "in"; ident = IDENT -> ident ] -> where ]
232   ];
233   tactic_term: [ [ t = term -> t ] ];
234   ident_list0: [
235     [ PAREN "["; idents = LIST0 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
236   ];
237   ident_list1: [
238     [ PAREN "["; idents = LIST1 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
239   ];
240   reduction_kind: [
241     [ [ IDENT "reduce" | IDENT "Reduce" ] -> `Reduce
242     | [ IDENT "simplify" | IDENT "Simplify" ] -> `Simpl
243     | [ IDENT "whd" | IDENT "Whd" ] -> `Whd ]
244   ];
245   tactic: [
246     [ [ IDENT "absurd" | IDENT "Absurd" ]; t = tactic_term ->
247         return_tactic loc (TacticAst.Absurd t)
248     | [ IDENT "apply" | IDENT "Apply" ]; t = tactic_term ->
249         return_tactic loc (TacticAst.Apply t)
250     | [ IDENT "assumption" | IDENT "Assumption" ] ->
251         return_tactic loc TacticAst.Assumption
252     | [ IDENT "auto" | IDENT "Auto" ] -> return_tactic loc TacticAst.Auto
253     | [ IDENT "change" | IDENT "Change" ];
254       t1 = tactic_term; "with"; t2 = tactic_term;
255       where = tactic_where ->
256         return_tactic loc (TacticAst.Change (t1, t2, where))
257     (* TODO Change_pattern *)
258     | [ IDENT "contradiction" | IDENT "Contradiction" ] ->
259         return_tactic loc TacticAst.Contradiction
260     | [ IDENT "cut" | IDENT "Cut" ];
261       t = tactic_term -> return_tactic loc (TacticAst.Cut t)
262     | [ IDENT "decompose" | IDENT "Decompose" ];
263       principles = ident_list1; where = IDENT ->
264         return_tactic loc (TacticAst.Decompose (where, principles))
265     | [ IDENT "discriminate" | IDENT "Discriminate" ];
266       hyp = IDENT ->
267         return_tactic loc (TacticAst.Discriminate hyp)
268     | [ IDENT "elimType" | IDENT "ElimType" ]; t = tactic_term ->
269         return_tactic loc (TacticAst.ElimType t)
270     | [ IDENT "elim" | IDENT "Elim" ];
271       t1 = tactic_term;
272       using = OPT [ "using"; using = tactic_term -> using ] ->
273         return_tactic loc (TacticAst.Elim (t1, using))
274     | [ IDENT "exact" | IDENT "Exact" ]; t = tactic_term ->
275         return_tactic loc (TacticAst.Exact t)
276     | [ IDENT "exists" | IDENT "Exists" ] ->
277         return_tactic loc TacticAst.Exists
278     | [ IDENT "fold" | IDENT "Fold" ];
279       kind = reduction_kind; t = tactic_term ->
280         return_tactic loc (TacticAst.Fold (kind, t))
281     | [ IDENT "fourier" | IDENT "Fourier" ] ->
282         return_tactic loc TacticAst.Fourier
283     | [ IDENT "hint" | IDENT "Hint" ] -> return_tactic loc TacticAst.Hint
284     | [ IDENT "injection" | IDENT "Injection" ]; ident = IDENT ->
285         return_tactic loc (TacticAst.Injection ident)
286     | [ IDENT "intros" | IDENT "Intros" ];
287       num = OPT [ num = int -> num ];
288       idents = OPT ident_list0 ->
289         let idents = match idents with None -> [] | Some idents -> idents in
290         return_tactic loc (TacticAst.Intros (num, idents))
291     | [ IDENT "intro" | IDENT "Intro" ] ->
292         return_tactic loc (TacticAst.Intros (Some 1, []))
293     | [ IDENT "left" | IDENT "Left" ] -> return_tactic loc TacticAst.Left
294     | [ "let" | "Let" ];
295       t = tactic_term; "in"; where = IDENT ->
296         return_tactic loc (TacticAst.LetIn (t, where))
297     | kind = reduction_kind;
298       pat = OPT [
299         "in"; pat = [ IDENT "goal" -> `Goal | IDENT "hyp" -> `Everywhere ] ->
300           pat
301       ];
302       terms = LIST0 term SEP SYMBOL "," ->
303         let tac =
304           (match (pat, terms) with
305           | None, [] -> TacticAst.Reduce (kind, None)
306           | None, terms -> TacticAst.Reduce (kind, Some (terms, `Goal))
307           | Some pat, [] -> TacticAst.Reduce (kind, Some ([], pat))
308           | Some pat, terms -> TacticAst.Reduce (kind, Some (terms, pat)))
309         in
310         return_tactic loc tac
311     | [ IDENT "reflexivity" | IDENT "Reflexivity" ] ->
312         return_tactic loc TacticAst.Reflexivity
313     | [ IDENT "replace" | IDENT "Replace" ];
314       t1 = tactic_term; "with"; t2 = tactic_term ->
315         return_tactic loc (TacticAst.Replace (t1, t2))
316     (* TODO Rewrite *)
317     (* TODO Replace_pattern *)
318     | [ IDENT "right" | IDENT "Right" ] -> return_tactic loc TacticAst.Right
319     | [ IDENT "ring" | IDENT "Ring" ] -> return_tactic loc TacticAst.Ring
320     | [ IDENT "split" | IDENT "Split" ] -> return_tactic loc TacticAst.Split
321     | [ IDENT "symmetry" | IDENT "Symmetry" ] ->
322         return_tactic loc TacticAst.Symmetry
323     | [ IDENT "transitivity" | IDENT "Transitivity" ];
324       t = tactic_term ->
325         return_tactic loc (TacticAst.Transitivity t)
326     ]
327   ];
328   tactical0: [ [ t = tactical; SYMBOL ";;" -> return_tactical loc t ] ];
329   tactical:
330     [ "command" NONA
331       [ cmd = command -> return_tactical loc (TacticAst.Command cmd) ]
332     | "sequence" LEFTA
333       [ tactics = LIST1 NEXT SEP SYMBOL ";" ->
334           return_tactical loc (TacticAst.Seq tactics)
335       ]
336     | "then" NONA
337       [ tac = tactical;
338         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
339           return_tactical loc (TacticAst.Then (tac, tacs))
340       ]
341     | "loops" RIGHTA
342       [ [ IDENT "do" | IDENT "Do" ]; count = int; tac = tactical ->
343           return_tactical loc (TacticAst.Do (count, tac))
344       | [ IDENT "repeat" | IDENT "Repeat" ]; tac = tactical ->
345           return_tactical loc (TacticAst.Repeat tac)
346       ]
347     | "simple" NONA
348       [ [ IDENT "tries" | IDENT "Tries" ];
349         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
350           return_tactical loc (TacticAst.Tries tacs)
351       | [ IDENT "try" | IDENT "Try" ]; tac = NEXT ->
352           return_tactical loc (TacticAst.Try tac)
353       | [ IDENT "fail" | IDENT "Fail" ] -> return_tactical loc TacticAst.Fail
354       | [ IDENT "id" | IDENT "Id" ] -> return_tactical loc TacticAst.IdTac
355       | PAREN "("; tac = tactical; PAREN ")" -> return_tactical loc tac
356       | tac = tactic -> return_tactical loc (TacticAst.Tactic tac)
357       ]
358     ];
359   theorem_flavour: [  (* all flavours but Goal *)
360     [ [ IDENT "definition"  | IDENT "Definition"  ] -> `Definition
361     | [ IDENT "fact"        | IDENT "Fact"        ] -> `Fact
362     | [ IDENT "lemma"       | IDENT "Lemma"       ] -> `Lemma
363     | [ IDENT "remark"      | IDENT "Remark"      ] -> `Remark
364     | [ IDENT "theorem"     | IDENT "Theorem"     ] -> `Theorem
365     ]
366   ];
367   command: [
368     [ [ IDENT "abort" | IDENT "Abort" ] -> return_command loc TacticAst.Abort
369     | [ IDENT "proof" | IDENT "Proof" ] -> return_command loc TacticAst.Proof
370     | [ IDENT "quit"  | IDENT "Quit"  ] -> return_command loc TacticAst.Quit
371     | [ IDENT "qed"   | IDENT "Qed"   ] ->
372         return_command loc (TacticAst.Qed None)
373     | [ IDENT "save"  | IDENT "Save"  ]; name = IDENT ->
374         return_command loc (TacticAst.Qed (Some name))
375     | flavour = theorem_flavour; name = OPT IDENT; SYMBOL ":"; typ = term;
376       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
377         return_command loc (TacticAst.Theorem (flavour, name, typ, body))
378     | [ IDENT "inductive" | IDENT "Inductive" ]; fst_name = IDENT;
379       params = LIST0 [
380         PAREN "("; names = LIST1 IDENT SEP SYMBOL ","; SYMBOL ":";
381         typ = term; PAREN ")" -> (names, typ) ];
382       SYMBOL ":"; fst_typ = term; SYMBOL <:unicode<def>>; OPT SYMBOL "|";
383       fst_constructors = LIST0 constructor SEP SYMBOL "|" ->
384         let params =
385           List.fold_right
386             (fun (names, typ) acc ->
387               (List.map (fun name -> (name, typ)) names) @ acc)
388             params []
389         in
390         let fst_ind_type = (fst_name, true, fst_typ, fst_constructors) in
391         let ind_types = [fst_ind_type] in
392         return_command loc (TacticAst.Inductive (params, ind_types))
393     | [ IDENT "goal" | IDENT "Goal" ]; typ = term;
394       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ] ->
395         return_command loc (TacticAst.Theorem (`Goal, None, typ, body))
396     | [ IDENT "undo"   | IDENT "Undo" ]; steps = OPT NUM ->
397         return_command loc (TacticAst.Undo (int_opt steps))
398     | [ IDENT "redo"   | IDENT "Redo" ]; steps = OPT NUM ->
399         return_command loc (TacticAst.Redo (int_opt steps))
400     | [ IDENT "baseuri"   | IDENT "Baseuri" ]; uri = OPT QSTRING ->
401         return_command loc (TacticAst.Baseuri uri)
402     | [ IDENT "check"   | IDENT "Check" ]; t = term ->
403         return_command loc (TacticAst.Check t)
404     ]
405   ];
406 END
407
408 let exc_located_wrapper f =
409   try
410     f ()
411   with
412   | Stdpp.Exc_located (floc, Stream.Error msg) ->
413       raise (Parse_error (floc, msg))
414   | Stdpp.Exc_located (floc, exn) ->
415       raise (Parse_error (floc, (Printexc.to_string exn)))
416
417 let parse_term stream =
418   exc_located_wrapper (fun () -> (Grammar.Entry.parse term0 stream))
419 let parse_tactic stream =
420   exc_located_wrapper (fun () -> (Grammar.Entry.parse tactic stream))
421 let parse_tactical stream =
422   exc_located_wrapper (fun () -> (Grammar.Entry.parse tactical0 stream))
423
424 (**/**)
425
426 (** {2 Interface for gTopLevel} *)
427
428 module EnvironmentP3 =
429   struct
430     type t = environment
431
432     let empty = ""
433
434     let aliases_grammar = Grammar.gcreate CicTextualLexer2.cic_lexer
435     let aliases = Grammar.Entry.create aliases_grammar "aliases"
436
437     let to_string env =
438       let aliases =
439         Environment.fold
440           (fun domain_item (dsc, _) acc ->
441             let s =
442               match domain_item with
443               | Id id -> sprintf "alias id %s = %s" id dsc
444               | Symbol (symb, instance) ->
445                   sprintf "alias symbol \"%s\" (instance %d) = \"%s\""
446                     symb instance dsc
447               | Num instance ->
448                   sprintf "alias num (instance %d) = \"%s\"" instance dsc
449             in
450             s :: acc)
451           env []
452       in
453       String.concat "\n" (List.sort compare aliases)
454
455     EXTEND
456       GLOBAL: aliases;
457       aliases: [  (* build an environment from an aliases list *)
458         [ aliases = LIST0 alias; EOI ->
459             List.fold_left
460               (fun env (domain_item, codomain_item) ->
461                 Environment.add domain_item codomain_item env)
462               Environment.empty aliases
463         ]
464       ];
465       alias: [  (* return a pair <domain_item, codomain_item> from an alias *)
466         [ IDENT "alias";
467           choice =
468             [ IDENT "id"; id = IDENT; SYMBOL "="; uri = URI ->
469                 (Id id, choice_of_uri uri)
470             | IDENT "symbol"; symbol = QSTRING;
471               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
472               SYMBOL "="; dsc = QSTRING ->
473                 (Symbol (symbol, int_of_string instance),
474                  DisambiguateChoices.lookup_symbol_by_dsc symbol dsc)
475             | IDENT "num";
476               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
477               SYMBOL "="; dsc = QSTRING ->
478                 (Num (int_of_string instance),
479                  DisambiguateChoices.lookup_num_by_dsc dsc)
480             ] -> choice ]
481       ];
482     END
483
484     let of_string s =
485       if s = empty then
486         Environment.empty
487       else
488         exc_located_wrapper
489           (fun () -> Grammar.Entry.parse aliases (Stream.of_string s))
490   end
491
492 (* vim:set encoding=utf8: *)