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