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