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