]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaInterpreter.ml
a1bc1dd9ed2fa0776b9b8d8ad98a25cecfd50345
[helm.git] / helm / matita / matitaInterpreter.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 (** Interpreter for textual phrases coming from matita's console (textual entry
27 * window at the bottom of the main window).
28 *
29 * Interpreter is either in `Command state or in `Proof state (see state_tag type
30 * below). In `Command state commands for starting proofs are accepted, but
31 * tactic and tactical applications are not. In `Proof state both
32 * tactic/tacticals and commands are accepted.
33 *)
34
35 open Printf
36
37 open MatitaTypes
38
39   (** None means: "same state as before" *)
40 type state_tag = [ `Command | `Proof ] option
41
42 exception Command_error of string
43
44 (*
45 let uri name =
46   UriManager.uri_of_string (sprintf "%s/%s" BuildTimeConf.base_uri name)
47 *)
48
49 let baseuri = ref "cic:/matita"
50 let qualify name =
51   let baseuri = !baseuri in
52   if baseuri.[String.length baseuri - 1] = '/' then
53     baseuri ^ name
54   else
55     String.concat "/" [baseuri; name]
56
57 let canonical_context metano metasenv =
58   try
59     let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in
60     context
61   with Not_found ->
62     failwith (sprintf "Can't find canonical context for %d" metano)
63
64 let get_context_and_metasenv (proof_handler:MatitaTypes.proof_handler) =
65   if proof_handler.MatitaTypes.has_proof () then
66     let proof = proof_handler.MatitaTypes.get_proof () in
67     let metasenv = proof#metasenv in
68     let goal = proof#goal in
69     (canonical_context goal metasenv, metasenv)
70   else
71     ([], [])
72
73   (** term AST -> Cic.term. Uses disambiguator and change imperatively the
74   * metasenv as needed *)
75 let disambiguate ~(disambiguator:MatitaTypes.disambiguator) ~proof_handler ast =
76   if proof_handler.MatitaTypes.has_proof () then begin
77     let proof = proof_handler.MatitaTypes.get_proof () in
78     let metasenv = proof#metasenv in
79     let goal = proof#goal in
80     let context = canonical_context goal metasenv in
81     let (_, metasenv, term,ugraph) as retval =
82       disambiguator#disambiguateTermAst ~context ~metasenv ast
83     in
84     proof#set_metasenv metasenv;
85     retval
86   end else
87     disambiguator#disambiguateTermAst ast
88
89 class virtual interpreterState = 
90     (* static values, shared by all states inheriting this class *)
91   let loc = ref None in
92   let history = ref [] in
93   fun ~(console: MatitaConsole.console) ->
94   object (self)
95
96       (** eval a toplevel phrase in the current state and return the new state
97       *)
98     method parsePhrase s =
99       match CicTextualParser2.parse_tactical (Stream.of_string s) with
100       | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
101           loc := Some loc';
102           (match tac with (* update interpreter history *)
103           | TacticAst.Command (TacticAst.Qed None) ->
104               history := `Qed :: !history
105           | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
106               history := `Theorem name :: !history
107           | TacticAst.Command (TacticAst.Qed _)
108           | TacticAst.Command (TacticAst.Theorem _) -> assert false
109           | _ -> history := `Tactic :: !history);
110           tactical
111       | _ -> assert false
112
113     method virtual evalTactical:
114       (CicAst.term, string) TacticAst.tactical -> state_tag
115
116     method evalPhrase s =
117       debug_print (sprintf "evaluating '%s'" s);
118       self#evalTactical (self#parsePhrase s)
119
120     method evalAst ast = self#evalTactical ast
121
122     method endOffset =
123       match !loc with
124       | Some (start_pos, end_pos) -> end_pos.Lexing.pos_cnum
125       | None -> failwith "MatitaInterpreter: no offset recorded"
126
127   end
128
129 let check_widget: MatitaTypes.sequent_viewer lazy_t = lazy
130   (let gui = MatitaGui.instance () in
131   MatitaMathView.sequent_viewer ~show:true ~packing:gui#check#scrolledCheck#add
132     ())
133
134   (** Implements phrases that should be accepted in all states *)
135 class sharedState
136   ~(disambiguator: MatitaTypes.disambiguator)
137   ~(proof_handler: MatitaTypes.proof_handler)
138   ~(console: MatitaConsole.console)
139   ()
140 =
141   object (self)
142     inherit interpreterState ~console
143     method evalTactical = function
144       | TacticAst.Command TacticAst.Quit ->
145           proof_handler.MatitaTypes.quit ();
146           Some `Command (* dummy answer, useless *)
147       | TacticAst.Command TacticAst.Proof ->
148             (* do nothing, just for compatibility with coq syntax *)
149           Some `Command
150       | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
151           baseuri := uri;
152           console#echo_message (sprintf "base uri set to \"%s\"" uri);
153           None
154       | TacticAst.Command (TacticAst.Baseuri None) ->
155           console#echo_message (sprintf "base uri is \"%s\"" !baseuri);
156           None
157       | TacticAst.Command (TacticAst.Check term) ->
158           let (_, _, term,ugraph) = 
159             disambiguate ~disambiguator ~proof_handler term 
160           in
161           let (context, metasenv) = get_context_and_metasenv proof_handler in
162           let dummyno = CicMkImplicit.new_meta metasenv [] in
163           let ty,ugraph1 = 
164             CicTypeChecker.type_of_aux' metasenv context term ugraph 
165           in
166             (* TASSI: here ugraph1 is unused.... FIXME *)
167           let expr = Cic.Cast (term, ty) in
168           let sequent = (dummyno, context, expr) in
169           let widget = Lazy.force check_widget in
170           let gui = MatitaGui.instance () in
171           gui#check#checkWin#show ();
172           gui#main#showCheckMenuItem#set_active true;
173           widget#load_sequent (sequent::metasenv) dummyno;
174           None
175       | tactical ->
176           raise (Command_error (TacticAstPp.pp_tactical tactical))
177   end
178
179   (** Implements phrases that should be accepted only in `Command state *)
180 class commandState
181   ~(disambiguator: MatitaTypes.disambiguator)
182   ~(proof_handler: MatitaTypes.proof_handler)
183   ~(console: MatitaConsole.console)
184   ()
185 =
186   let shared = new sharedState ~disambiguator ~proof_handler ~console () in
187   object (self)
188     inherit interpreterState ~console
189
190     method evalTactical = function
191       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
192       | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
193           let (_, metasenv, expr,ugraph) = 
194             disambiguator#disambiguateTermAst ast 
195           in
196           let uri = UriManager.uri_of_string (qualify name) in
197           let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
198           proof_handler.MatitaTypes.new_proof proof;
199           Some `Proof
200       | TacticAst.Command TacticAst.Quit ->
201           proof_handler.MatitaTypes.quit ();
202           Some `Command (* dummy answer, useless *)
203       | TacticAst.Command TacticAst.Proof ->
204             (* do nothing, just for compatibility with coq syntax *)
205           Some `Command
206       | tactical -> shared#evalTactical tactical
207   end
208
209   (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
210   * names as long as they are available, then it fallbacks to name generation
211   * using FreshNamesGenerator module *)
212 let namer_of names =
213   let len = List.length names in
214   let count = ref 0 in
215   fun metasenv context name ~typ ->
216     if !count < len then begin
217       let name = Cic.Name (List.nth names !count) in
218       incr count;
219       name
220     end else
221       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
222
223   (** Implements phrases that should be accepted only in `Proof state, basically
224   * tacticals *)
225 class proofState
226   ~(disambiguator: MatitaTypes.disambiguator)
227   ~(proof_handler: MatitaTypes.proof_handler)
228   ~(console: MatitaConsole.console)
229   ~(dbd: Mysql.dbd)
230   ()
231 =
232   let disambiguate ast =
233     let (_, _, term,ugraph) = 
234       disambiguate ~disambiguator ~proof_handler ast 
235     in
236     term
237   in
238     (** tactic AST -> ProofEngineTypes.tactic *)
239   let rec lookup_tactic = function
240     | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
241     | TacticAst.Intros (_, names) ->  (* TODO Zack implement intros length *)
242         PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
243     | TacticAst.Reflexivity -> Tactics.reflexivity
244     | TacticAst.Assumption -> Tactics.assumption
245     | TacticAst.Contradiction -> Tactics.contradiction
246     | TacticAst.Exists -> Tactics.exists
247     | TacticAst.Fourier -> Tactics.fourier
248     | TacticAst.Left -> Tactics.left
249     | TacticAst.Right -> Tactics.right
250     | TacticAst.Ring -> Tactics.ring
251     | TacticAst.Split -> Tactics.split
252     | TacticAst.Symmetry -> Tactics.symmetry
253     | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
254     | TacticAst.Apply term -> Tactics.apply (disambiguate term)
255     | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
256     | TacticAst.Exact term -> Tactics.exact (disambiguate term)
257     | TacticAst.Cut term -> Tactics.cut (disambiguate term)
258     | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
259         Tactics.elim_intros_simpl (disambiguate term)
260     | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
261     | TacticAst.Replace (what, with_what) ->
262         Tactics.replace ~what:(disambiguate what)
263           ~with_what:(disambiguate with_what)
264     | TacticAst.Auto -> Tactics.auto_new ~dbd
265   (*
266     (* TODO Zack a lot more of tactics to be implemented here ... *)
267     | TacticAst.Change of 'term * 'term * 'ident option
268     | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
269     | TacticAst.Decompose of 'ident * 'ident list
270     | TacticAst.Discriminate of 'ident
271     | TacticAst.Fold of reduction_kind * 'term
272     | TacticAst.Injection of 'ident
273     | TacticAst.LetIn of 'term * 'ident
274     | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
275     | TacticAst.Replace_pattern of 'term pattern * 'term
276     | TacticAst.Rewrite of direction * 'term * 'ident option
277   *)
278     | _ ->
279         MatitaTypes.not_implemented "some tactic"
280   in
281   let shared = new sharedState ~disambiguator ~proof_handler ~console () in
282   object (self)
283     inherit interpreterState ~console
284
285     method evalTactical = function
286       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
287       | TacticAst.Command TacticAst.Abort ->
288           proof_handler.MatitaTypes.abort_proof ();
289           Some `Command
290       | TacticAst.Command (TacticAst.Undo steps) ->
291           (proof_handler.MatitaTypes.get_proof ())#undo ?steps ();
292           Some `Proof
293       | TacticAst.Command (TacticAst.Redo steps) ->
294           (proof_handler.MatitaTypes.get_proof ())#redo ?steps ();
295           Some `Proof
296       | TacticAst.Command (TacticAst.Qed None) ->
297           (* TODO Zack this function probably should not simply fail with
298           * Failure, but rather raise some more meaningful exception *)
299           if not (proof_handler.MatitaTypes.has_proof ()) then assert false;
300           let proof = proof_handler.MatitaTypes.get_proof () in
301           let (uri, metasenv, bo, ty) = proof#proof in
302           let uri = MatitaTypes.unopt_uri uri in
303           if metasenv <> [] then failwith "Proof not completed";
304           let proved_ty,ugraph = 
305             CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
306           in
307           let b,ugraph1 = 
308             CicReduction.are_convertible [] proved_ty ty ugraph 
309           in
310           if not b then
311             failwith "Wrong proof";
312           (* TODO Zack [] probably wrong *)
313           let ugraph2 = CicUniv.fill_empty_nodes_with_uri ugraph1 uri in
314           CicEnvironment.add_type_checked_term uri
315             ((Cic.Constant ((UriManager.name_of_uri uri),
316                             (Some bo),ty,[])),
317              ugraph2);
318           proof_handler.MatitaTypes.set_proof None;
319           (MatitaMathView.proof_viewer_instance ())#unload;
320           (* TODO Zack a lot more to be done here:
321             * - save object to disk in xml format
322             * - collect metadata
323             * - register uri to the getter 
324             * - save universe file *)
325           Some `Command
326       | TacticAst.Seq tacticals ->
327           (* TODO Zack check for proof completed at each step? *)
328           List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
329           Some `Proof
330       | TacticAst.Tactic tactic_phrase ->
331           let tactic = lookup_tactic tactic_phrase in
332           (proof_handler.MatitaTypes.get_proof ())#apply_tactic tactic;
333           Some `Proof
334       | tactical -> shared#evalTactical tactical
335   end
336
337 class interpreter
338   ~(disambiguator: MatitaTypes.disambiguator)
339   ~(proof_handler: MatitaTypes.proof_handler)
340   ~(console: MatitaConsole.console)
341   ~(dbd: Mysql.dbd)
342   ()
343 =
344   let commandState =
345     new commandState ~disambiguator ~proof_handler ~console ()
346   in
347   let proofState =
348     new proofState ~disambiguator ~proof_handler ~console ~dbd ()
349   in
350   object (self)
351     val mutable state = commandState
352
353     method reset = state <- commandState
354
355     method endOffset = state#endOffset
356
357     method private updateState = function
358       | Some `Command -> state <- commandState
359       | Some `Proof -> state <- proofState
360       | None -> ()
361
362     method evalPhrase s =
363       let success =
364         console#wrap_exn (fun () -> self#updateState (state#evalPhrase s))
365       in
366       if success then console#clear ();
367       success
368
369     method evalAst ast =
370       let success =
371         console#wrap_exn (fun () -> self#updateState (state#evalAst ast))
372       in
373       if success then console#clear ();
374       success
375   end
376