]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaInterpreter.ml
3a4295f4ac99f94f8d75eca3ff94953f22d8b4ba
[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) 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) = disambiguate ~disambiguator ~proof_handler term in
159           let (context, metasenv) = get_context_and_metasenv proof_handler in
160           let dummyno = CicMkImplicit.new_meta metasenv [] in
161           let ty = CicTypeChecker.type_of_aux' metasenv context term in
162           let expr = Cic.Cast (term, ty) in
163           let sequent = (dummyno, context, expr) in
164           let widget = Lazy.force check_widget in
165           let gui = MatitaGui.instance () in
166           gui#check#checkWin#show ();
167           gui#main#showCheckMenuItem#set_active true;
168           widget#load_sequent (sequent::metasenv) dummyno;
169           None
170       | tactical ->
171           raise (Command_error (TacticAstPp.pp_tactical tactical))
172   end
173
174   (** Implements phrases that should be accepted only in `Command state *)
175 class commandState
176   ~(disambiguator: MatitaTypes.disambiguator)
177   ~(proof_handler: MatitaTypes.proof_handler)
178   ~(console: MatitaConsole.console)
179   ()
180 =
181   let shared = new sharedState ~disambiguator ~proof_handler ~console () in
182   object (self)
183     inherit interpreterState ~console
184
185     method evalTactical = function
186       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
187       | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
188           let (_, metasenv, expr) = disambiguator#disambiguateTermAst ast in
189           let uri = UriManager.uri_of_string (qualify name) in
190           let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
191           proof_handler.MatitaTypes.new_proof proof;
192           Some `Proof
193       | TacticAst.Command TacticAst.Quit ->
194           proof_handler.MatitaTypes.quit ();
195           Some `Command (* dummy answer, useless *)
196       | TacticAst.Command TacticAst.Proof ->
197             (* do nothing, just for compatibility with coq syntax *)
198           Some `Command
199       | tactical -> shared#evalTactical tactical
200   end
201
202   (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
203   * names as long as they are available, then it fallbacks to name generation
204   * using FreshNamesGenerator module *)
205 let namer_of names =
206   let len = List.length names in
207   let count = ref 0 in
208   fun metasenv context name ~typ ->
209     if !count < len then begin
210       let name = Cic.Name (List.nth names !count) in
211       incr count;
212       name
213     end else
214       FreshNamesGenerator.mk_fresh_name metasenv context name ~typ
215
216   (** Implements phrases that should be accepted only in `Proof state, basically
217   * tacticals *)
218 class proofState
219   ~(disambiguator: MatitaTypes.disambiguator)
220   ~(proof_handler: MatitaTypes.proof_handler)
221   ~(console: MatitaConsole.console)
222   ()
223 =
224   let disambiguate ast =
225     let (_, _, term) = disambiguate ~disambiguator ~proof_handler ast in
226     term
227   in
228     (** tactic AST -> ProofEngineTypes.tactic *)
229   let rec lookup_tactic = function
230     | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
231     | TacticAst.Intros (_, names) ->  (* TODO Zack implement intros length *)
232         PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
233     | TacticAst.Reflexivity -> Tactics.reflexivity
234     | TacticAst.Assumption -> Tactics.assumption
235     | TacticAst.Contradiction -> Tactics.contradiction
236     | TacticAst.Exists -> Tactics.exists
237     | TacticAst.Fourier -> Tactics.fourier
238     | TacticAst.Left -> Tactics.left
239     | TacticAst.Right -> Tactics.right
240     | TacticAst.Ring -> Tactics.ring
241     | TacticAst.Split -> Tactics.split
242     | TacticAst.Symmetry -> Tactics.symmetry
243     | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
244     | TacticAst.Apply term -> Tactics.apply (disambiguate term)
245     | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
246     | TacticAst.Exact term -> Tactics.exact (disambiguate term)
247     | TacticAst.Cut term -> Tactics.cut (disambiguate term)
248     | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
249         Tactics.elim_intros_simpl (disambiguate term)
250     | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
251     | TacticAst.Replace (what, with_what) ->
252         Tactics.replace ~what:(disambiguate what)
253           ~with_what:(disambiguate with_what)
254   (*
255     (* TODO Zack a lot more of tactics to be implemented here ... *)
256     | TacticAst.Change of 'term * 'term * 'ident option
257     | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
258     | TacticAst.Decompose of 'ident * 'ident list
259     | TacticAst.Discriminate of 'ident
260     | TacticAst.Fold of reduction_kind * 'term
261     | TacticAst.Injection of 'ident
262     | TacticAst.LetIn of 'term * 'ident
263     | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
264     | TacticAst.Replace_pattern of 'term pattern * 'term
265     | TacticAst.Rewrite of direction * 'term * 'ident option
266   *)
267     | _ ->
268         MatitaTypes.not_implemented "some tactic"
269   in
270   let shared = new sharedState ~disambiguator ~proof_handler ~console () in
271   object (self)
272     inherit interpreterState ~console
273
274     method evalTactical = function
275       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
276       | TacticAst.Command TacticAst.Abort ->
277           proof_handler.MatitaTypes.abort_proof ();
278           Some `Command
279       | TacticAst.Command (TacticAst.Undo steps) ->
280           (proof_handler.MatitaTypes.get_proof ())#undo ?steps ();
281           Some `Proof
282       | TacticAst.Command (TacticAst.Redo steps) ->
283           (proof_handler.MatitaTypes.get_proof ())#redo ?steps ();
284           Some `Proof
285       | TacticAst.Command (TacticAst.Qed None) ->
286           (* TODO Zack this function probably should not simply fail with
287           * Failure, but rather raise some more meaningful exception *)
288           if not (proof_handler.MatitaTypes.has_proof ()) then assert false;
289           let proof = proof_handler.MatitaTypes.get_proof () in
290           let (uri, metasenv, bo, ty) = proof#proof in
291           let uri = MatitaTypes.unopt_uri uri in
292           if metasenv <> [] then failwith "Proof not completed";
293           let proved_ty = CicTypeChecker.type_of_aux' [] [] bo in
294           if not (CicReduction.are_convertible [] proved_ty ty) then
295             failwith "Wrong proof";
296           (* TODO Zack [] probably wrong *)
297           CicEnvironment.add_type_checked_term uri
298             (Cic.Constant ((UriManager.name_of_uri uri),(Some bo),ty,[]));
299           proof_handler.MatitaTypes.set_proof None;
300           (MatitaMathView.proof_viewer_instance ())#unload;
301           (* TODO Zack a lot more to be done here:
302             * - save object to disk in xml format
303             * - collect metadata
304             * - register uri to the getter *)
305           Some `Command
306       | TacticAst.Seq tacticals ->
307           (* TODO Zack check for proof completed at each step? *)
308           List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
309           Some `Proof
310       | TacticAst.Tactic tactic_phrase ->
311           let tactic = lookup_tactic tactic_phrase in
312           (proof_handler.MatitaTypes.get_proof ())#apply_tactic tactic;
313           Some `Proof
314       | tactical -> shared#evalTactical tactical
315   end
316
317 class interpreter
318   ~(disambiguator: MatitaTypes.disambiguator)
319   ~(proof_handler: MatitaTypes.proof_handler)
320   ~(console: MatitaConsole.console)
321   ()
322 =
323   let commandState =
324     new commandState ~disambiguator ~proof_handler ~console ()
325   in
326   let proofState = new proofState ~disambiguator ~proof_handler ~console () in
327   let wrap_exn transparent f =
328     try
329       f ();
330       true
331     with exn ->
332       if transparent then
333         raise exn
334       else
335         console#echo_error (sprintf "Uncaught exception: %s"
336           (Printexc.to_string exn));
337       false
338   in
339   object (self)
340     val mutable state = commandState
341
342     method reset = state <- commandState
343
344     method endOffset = state#endOffset
345
346     method private updateState = function
347       | Some `Command -> state <- commandState
348       | Some `Proof -> state <- proofState
349       | None -> ()
350
351     method evalPhrase ?(transparent = false) s =
352       wrap_exn transparent (fun () -> self#updateState (state#evalPhrase s))
353
354     method evalAst ?(transparent = false) s =
355       wrap_exn transparent (fun () -> self#updateState (state#evalAst s))
356
357   end
358