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