]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/cic_disambiguation/cicTextualParser2.ml
- split logic operators away from aritmetic ones so that
[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 open Printf
35
36 exception Parse_error of string
37
38 type tactic = (CicAst.term, string) TacticAst.tactic
39 type tactical = (CicAst.term, string) TacticAst.tactic TacticAst.tactical
40 type command = CicAst.term CommandAst.command
41 type script = CicAst.term CommandAst.Script.script
42
43 let fresh_num_instance =
44  let n = ref 0 in
45   function () ->
46    incr n;
47    !n
48 ;;
49
50 let choice_of_uri (uri: string) =
51   let cic = HelmLibraryObjects.term_of_uri (UriManager.uri_of_string uri) in
52   (uri, (fun _ _ _ -> cic))
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 let script = Grammar.Entry.create grammar "script"
63
64 let return_term loc term = CicAst.AttributedTerm (`Loc loc, term)
65 let return_tactic loc tactic = TacticAst.LocatedTactic (loc, tactic)
66 let return_tactical loc tactical = TacticAst.LocatedTactical (loc, tactical)
67 let return_command loc cmd = cmd
68 let return_script loc script = script
69
70 let fail (x, y) msg =
71   failwith (Printf.sprintf "Error at characters %d - %d: %s" x y msg)
72
73 let name_of_string = function
74   | "_" -> Cic.Anonymous
75   | s -> Cic.Name s
76
77 EXTEND
78   GLOBAL: term term0 tactic tactical tactical0 command script;
79   int: [
80     [ num = NUM ->
81         try
82           int_of_string num
83         with Failure _ ->
84           let (x, y) = loc in
85           raise (Parse_error (sprintf
86             "integer literal expected at characters %d-%d" x y))
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 | SYMBOL ];
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   term0: [ [ t = term; EOI -> return_term loc t ] ];
135   term:
136     [ "letin" NONA
137         (* actually "in" and "and" are _not_ keywords. Parsing works anyway
138          * since applications are required to be bound by parens *)
139       [ "let"; var = typed_name;
140         SYMBOL "="; (* SYMBOL <:unicode<def>> (* ≝ *); *)
141         t1 = term;
142         IDENT "in"; t2 = term ->
143           return_term loc (CicAst.LetIn (var, t1, t2))
144       | "let"; ind_kind = [ "corec" -> `CoInductive | "rec"-> `Inductive ];
145           defs = LIST1 [
146             var = typed_name;
147             index = OPT [ PAREN "("; index = NUM; PAREN ")" ->
148               int_of_string index
149             ];
150             SYMBOL "="; (* SYMBOL <:unicode<def>> (* ≝ *); *)
151             t1 = term ->
152               (var, t1, (match index with None -> 0 | Some i -> i))
153           ] SEP (IDENT "and");
154           IDENT "in"; body = term ->
155             return_term loc (CicAst.LetRec (ind_kind, defs, body))
156       ]
157     | "binder" RIGHTA
158       [
159         b = binder;
160         (vars, typ) =
161           [ vars = LIST1 IDENT SEP SYMBOL ",";
162             typ = OPT [ SYMBOL ":"; t = term -> t ] -> (vars, typ)
163           | PAREN "("; vars = LIST1 IDENT SEP SYMBOL ",";
164             typ = OPT [ SYMBOL ":"; t = term -> t ]; PAREN ")" -> (vars, typ)
165           ];
166         SYMBOL "."; body = term ->
167           let binder =
168             List.fold_right
169               (fun var body ->
170                 let name = name_of_string var in
171                 CicAst.Binder (b, (name, typ), body))
172               vars body
173           in
174           return_term loc binder
175       | t1 = term; SYMBOL <:unicode<to>> (* → *); t2 = term ->
176             return_term loc
177               (CicAst.Binder (`Pi, (Cic.Anonymous, Some t1), t2))
178       ]
179     | "logic_add" LEFTA   [ (* nothing here by default *) ]
180     | "logic_mult" LEFTA  [ (* nothing here by default *) ]
181     | "logic_inv" NONA    [ (* nothing here by default *) ]
182     | "relop" LEFTA
183       [ t1 = term; SYMBOL "="; t2 = term ->
184         return_term loc (CicAst.Appl [CicAst.Symbol ("eq", 0); t1; t2])
185       ]
186     | "add" LEFTA     [ (* nothing here by default *) ]
187     | "mult" LEFTA    [ (* nothing here by default *) ]
188     | "power" LEFTA   [ (* nothing here by default *) ]
189     | "inv" NONA      [ (* nothing here by default *) ]
190     | "simple" NONA
191       [ sort = sort -> CicAst.Sort sort
192       | n = substituted_name -> return_term loc n
193       | PAREN "("; head = term; args = LIST1 term; PAREN ")" ->
194           return_term loc (CicAst.Appl (head :: args))
195       | i = NUM -> return_term loc (CicAst.Num (i, (fresh_num_instance ())))
196       | IMPLICIT -> return_term loc CicAst.Implicit
197       | m = META;
198         substs = [
199           PAREN "["; substs = LIST0 meta_subst SEP SYMBOL ";" ; PAREN "]" ->
200             substs
201         ] ->
202             let index =
203               try
204                 int_of_string (String.sub m 1 (String.length m - 1))
205               with Failure "int_of_string" ->
206                 fail loc ("Invalid meta variable number: " ^ m)
207             in
208             return_term loc (CicAst.Meta (index, substs))
209       | outtyp = OPT [ PAREN "["; typ = term; PAREN "]" -> typ ];
210         "match"; t = term;
211         indty_ident = OPT [ SYMBOL ":"; id = IDENT -> id ];
212         "with";
213         PAREN "[";
214         patterns = LIST0 [
215           lhs = pattern; SYMBOL <:unicode<Rightarrow>> (* ⇒ *); rhs = term ->
216             ((lhs: CicAst.case_pattern), rhs)
217         ] SEP SYMBOL "|";
218         PAREN "]" ->
219           return_term loc
220             (CicAst.Case (t, indty_ident, outtyp, patterns))
221       | PAREN "("; t1 = term; SYMBOL ":"; t2 = term; PAREN ")" ->
222           return_term loc (CicAst.Appl [CicAst.Symbol ("cast", 0); t1; t2])
223       | PAREN "("; t = term; PAREN ")" -> return_term loc t
224       ]
225     ];
226   tactic_where: [
227     [ where = OPT [ IDENT "in"; ident = IDENT -> ident ] -> where ]
228   ];
229   tactic_term: [ [ t = term -> t ] ];
230   ident_list0: [
231     [ PAREN "["; idents = LIST0 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
232   ];
233   ident_list1: [
234     [ PAREN "["; idents = LIST1 IDENT SEP SYMBOL ";"; PAREN "]" -> idents ]
235   ];
236   reduction_kind: [
237     [ "reduce" -> `Reduce
238     | "simpl" -> `Simpl
239     | "whd" -> `Whd ]
240   ];
241   tactic: [
242     [ [ IDENT "absurd" | IDENT "Absurd" ] -> return_tactic loc TacticAst.Absurd
243     | [ IDENT "apply" | IDENT "Apply" ];
244       t = tactic_term -> return_tactic loc (TacticAst.Apply t)
245     | [ IDENT "assumption" | IDENT "Assumption" ] ->
246         return_tactic loc TacticAst.Assumption
247     | [ IDENT "change" | IDENT "Change" ];
248       t1 = tactic_term; "with"; t2 = tactic_term;
249       where = tactic_where ->
250         return_tactic loc (TacticAst.Change (t1, t2, where))
251     (* TODO Change_pattern *)
252     | [ IDENT "contradiction" | IDENT "Contradiction" ] ->
253         return_tactic loc TacticAst.Contradiction
254     | [ IDENT "cut" | IDENT "Cut" ];
255       t = tactic_term -> return_tactic loc (TacticAst.Cut t)
256     | [ IDENT "decompose" | IDENT "Decompose" ];
257       principles = ident_list1; where = IDENT ->
258         return_tactic loc (TacticAst.Decompose (where, principles))
259     | [ IDENT "discriminate" | IDENT "Discriminate" ];
260       hyp = IDENT ->
261         return_tactic loc (TacticAst.Discriminate hyp)
262     | [ IDENT "elim" | IDENT "Elim" ]; IDENT "type";
263       t = tactic_term ->
264         return_tactic loc (TacticAst.ElimType t)
265     | [ IDENT "elim" | IDENT "Elim" ];
266       t1 = tactic_term;
267       using = OPT [ "using"; using = tactic_term -> using ] ->
268         return_tactic loc (TacticAst.Elim (t1, using))
269     | [ IDENT "exact" | IDENT "Exact" ]; t = tactic_term ->
270         return_tactic loc (TacticAst.Exact t)
271     | [ IDENT "exists" | IDENT "Exists" ] ->
272         return_tactic loc TacticAst.Exists
273     | [ IDENT "fold" | IDENT "Fold" ];
274       kind = reduction_kind; t = tactic_term ->
275         return_tactic loc (TacticAst.Fold (kind, t))
276     | [ IDENT "fourier" | IDENT "Fourier" ] ->
277         return_tactic loc TacticAst.Fourier
278     | [ IDENT "injection" | IDENT "Injection" ]; ident = IDENT ->
279         return_tactic loc (TacticAst.Injection ident)
280     | [ IDENT "intros" | IDENT "Intros" ];
281       num = OPT [ num = int -> num ];
282       idents = OPT ident_list0 ->
283         let idents = match idents with None -> [] | Some idents -> idents in
284         return_tactic loc (TacticAst.Intros (num, idents))
285     | [ IDENT "left" | IDENT "Left" ] -> return_tactic loc TacticAst.Left
286     | [ "let" | "Let" ];
287       t = tactic_term; IDENT "in"; where = IDENT ->
288         return_tactic loc (TacticAst.LetIn (t, where))
289     (* TODO Reduce *)
290     | [ IDENT "reflexivity" | IDENT "Reflexivity" ] ->
291         return_tactic loc TacticAst.Reflexivity
292     | [ IDENT "replace" | IDENT "Replace" ];
293       t1 = tactic_term; "with"; t2 = tactic_term ->
294         return_tactic loc (TacticAst.Replace (t1, t2))
295     (* TODO Rewrite *)
296     (* TODO Replace_pattern *)
297     | [ IDENT "right" | IDENT "Right" ] -> return_tactic loc TacticAst.Right
298     | [ IDENT "ring" | IDENT "Ring" ] -> return_tactic loc TacticAst.Ring
299     | [ IDENT "split" | IDENT "Split" ] -> return_tactic loc TacticAst.Split
300     | [ IDENT "symmetry" | IDENT "Symmetry" ] ->
301         return_tactic loc TacticAst.Symmetry
302     | [ IDENT "transitivity" | IDENT "Transitivity" ];
303       t = tactic_term ->
304         return_tactic loc (TacticAst.Transitivity t)
305     ]
306   ];
307   tactical0: [ [ t = tactical; SYMBOL "." -> t ] ];
308   tactical:
309     [ "sequence" LEFTA
310       [ tactics = LIST1 NEXT SEP SYMBOL ";" ->
311           return_tactical loc (TacticAst.Seq tactics)
312       ]
313     | "then" NONA
314       [ tac = tactical;
315         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
316           return_tactical loc (TacticAst.Then (tac, tacs))
317       ]
318     | "loops" RIGHTA
319       [ [ IDENT "do" | IDENT "Do" ]; count = int; tac = tactical ->
320           return_tactical loc (TacticAst.Do (count, tac))
321       | [ IDENT "repeat" | IDENT "Repeat" ]; tac = tactical ->
322           return_tactical loc (TacticAst.Repeat tac)
323       ]
324     | "simple" NONA
325       [ [ IDENT "tries" | IDENT "Tries" ];
326         PAREN "["; tacs = LIST0 tactical SEP SYMBOL ";"; PAREN "]" ->
327           return_tactical loc (TacticAst.Tries tacs)
328       | [ IDENT "try" | IDENT "Try" ]; tac = NEXT ->
329           return_tactical loc (TacticAst.Try tac)
330       | [ IDENT "fail" | IDENT "Fail" ] -> return_tactical loc TacticAst.Fail
331       | [ IDENT "id" | IDENT "Id" ] -> return_tactical loc TacticAst.IdTac
332       | PAREN "("; tac = tactical; PAREN ")" -> return_tactical loc tac
333       | tac = tactic -> return_tactical loc (TacticAst.Tactic tac)
334       ]
335     ];
336   theorem_flavour: [  (* all flavours but Goal *)
337     [ [ IDENT "definition"  | IDENT "Definition"  ] -> `Definition
338     | [ IDENT "fact"        | IDENT "Fact"        ] -> `Fact
339     | [ IDENT "lemma"       | IDENT "Lemma"       ] -> `Lemma
340     | [ IDENT "remark"      | IDENT "Remark"      ] -> `Remark
341     | [ IDENT "theorem"     | IDENT "Theorem"     ] -> `Theorem
342 (*     | [ IDENT "goal"        | IDENT "Goal"        ] -> `Goal *)
343     ]
344   ];
345   theorem_cmd: [
346     [ flavour = theorem_flavour; name = OPT IDENT; SYMBOL ":"; typ = term;
347       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ];
348       SYMBOL "." ->
349         (loc, flavour, name, typ, body)
350     | [ IDENT "goal" | IDENT "Goal" ]; typ = term;
351       body = OPT [ SYMBOL <:unicode<def>> (* ≝ *); body = term -> body ];
352       SYMBOL "." ->
353         (loc, `Goal, None, typ, body)
354     ]
355   ];
356   proof_cmd: [ [ [ IDENT "proof" | IDENT "Proof" ]; SYMBOL "." -> loc ] ];
357   qed_cmd: [
358     [ [ IDENT "qed" | IDENT "Qed" ]; SYMBOL "." -> (loc, None)
359     | [ IDENT "save" | IDENT "Save" ]; name = IDENT; SYMBOL "." ->
360         (loc, Some name)
361     ]
362   ];
363   command: [
364     [ (loc', flavour, name, typ, body) = theorem_cmd ->
365         return_command loc (CommandAst.Theorem (loc', flavour, name, typ, body))
366     | (loc') = proof_cmd -> return_command loc (CommandAst.Proof loc')
367     | (loc, name) = qed_cmd -> return_command loc (CommandAst.Qed (loc, name))
368     ]
369   ];
370   script_entry: [
371     [ theorem = theorem_cmd;
372       proof = OPT [
373         proof_cmd; tacticals = LIST1 tactical0; qed = qed_cmd ->
374           (tacticals, qed)
375       ] ->
376         let (loc', flavour, name', typ, body_verbatim) = theorem in
377         let name'' =
378           match proof with
379           | None | Some (_, (_, None)) -> None
380           | Some (_, (_, Some name)) -> Some name
381         in
382         let name =
383           match (name', name'') with
384           | Some name, None -> name
385           | None, Some name -> name
386           | None, None ->
387               Stdpp.raise_with_loc loc (Failure "theorem's name is missing")
388           | Some name', Some name'' when name' <> name'' ->
389               Stdpp.raise_with_loc loc (Failure (sprintf
390                 "theorem's name mismatch: %s <> %s" name' name''))
391           | Some name, _ -> name
392         in
393         let body =
394           match (body_verbatim, proof) with
395           | Some term, None -> CommandAst.Script.Verbatim (loc', term)
396           | None, Some (tacticals, (loc'', _)) ->
397               CommandAst.Script.Tactics (loc'', tacticals)
398           | Some _, Some _ ->
399               Stdpp.raise_with_loc loc (Failure (sprintf
400                 "theorem %s has too many proofs" name))
401           | None, None ->
402               Stdpp.raise_with_loc loc (Failure (sprintf
403                 "theorem %s has no proof" name))
404         in
405         return_script loc (CommandAst.Script.Theorem (flavour, name, typ, body))
406     ]
407   ];
408   script: [ [ entries = LIST0 script_entry; EOI -> entries ] ];
409 END
410
411 let exc_located_wrapper f =
412   try
413     Lazy.force f
414   with Stdpp.Exc_located ((x, y), exn) ->
415     raise (Parse_error (sprintf "parse error at characters %d-%d: %s" x y
416         (Printexc.to_string exn)))
417
418 let parse_term stream =
419   exc_located_wrapper (lazy (Grammar.Entry.parse term0 stream))
420 let parse_tactic stream =
421   exc_located_wrapper (lazy (Grammar.Entry.parse tactic stream))
422 let parse_tactical stream =
423   exc_located_wrapper (lazy (Grammar.Entry.parse tactical0 stream))
424 let parse_command stream =
425   exc_located_wrapper (lazy (Grammar.Entry.parse command stream))
426 let parse_script stream =
427   exc_located_wrapper (lazy (Grammar.Entry.parse script stream))
428
429 (**/**)
430
431 (** {2 Interface for gTopLevel} *)
432
433 open DisambiguateTypes
434
435 module EnvironmentP3 =
436   struct
437     type t = environment
438
439     let empty = ""
440
441     let aliases_grammar = Grammar.gcreate CicTextualLexer2.cic_lexer
442     let aliases = Grammar.Entry.create aliases_grammar "aliases"
443
444     let to_string env =
445       let aliases =
446         Environment.fold
447           (fun domain_item (dsc, _) acc ->
448             let s =
449               match domain_item with
450               | Id id -> sprintf "alias id %s = %s" id dsc
451               | Symbol (symb, instance) ->
452                   sprintf "alias symbol \"%s\" (instance %d) = \"%s\""
453                     symb instance dsc
454               | Num instance ->
455                   sprintf "alias num (instance %d) = \"%s\"" instance dsc
456             in
457             s :: acc)
458           env []
459       in
460       String.concat "\n" (List.sort compare aliases)
461
462     EXTEND
463       GLOBAL: aliases;
464       aliases: [  (* build an environment from an aliases list *)
465         [ aliases = LIST0 alias; EOI ->
466             List.fold_left
467               (fun env (domain_item, codomain_item) ->
468                 Environment.add domain_item codomain_item env)
469               Environment.empty aliases
470         ]
471       ];
472       alias: [  (* return a pair <domain_item, codomain_item> from an alias *)
473         [ IDENT "alias";
474           choice =
475             [ IDENT "id"; id = IDENT; SYMBOL "="; uri = URI ->
476                 (Id id, choice_of_uri uri)
477             | IDENT "symbol"; symbol = QSTRING;
478               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
479               SYMBOL "="; dsc = QSTRING ->
480                 (Symbol (symbol, int_of_string instance),
481                  DisambiguateChoices.lookup_symbol_by_dsc symbol dsc)
482             | IDENT "num";
483               PAREN "("; IDENT "instance"; instance = NUM; PAREN ")";
484               SYMBOL "="; dsc = QSTRING ->
485                 (Num (int_of_string instance),
486                  DisambiguateChoices.lookup_num_by_dsc dsc)
487             ] -> choice ]
488       ];
489     END
490
491     let of_string s =
492       if s = empty then
493         Environment.empty
494       else
495         try
496           Grammar.Entry.parse aliases (Stream.of_string s)
497         with Stdpp.Exc_located ((x, y), exn) ->
498           raise (Parse_error (sprintf "parse error at characters %d-%d: %s" x y
499           (Printexc.to_string exn)))
500   end
501
502 (* vim:set encoding=utf8: *)