]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaInterpreter.ml
c9d5a71612d7e1893c11b033307b518d54759eec
[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 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 type state = Command | Proof
40 type outcome = New_state of state | Quiet | Echo of string
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 = lazy (ref ("cic:/matita/" ^ Helm_registry.get "matita.owner"))
50 let basedir = ref ((Unix.getpwuid (Unix.getuid ())).Unix.pw_dir) ;;
51
52 let qualify name =
53   let baseuri = !(Lazy.force baseuri) in
54   if baseuri.[String.length baseuri - 1] = '/' then
55     baseuri ^ name
56   else
57     String.concat "/" [baseuri; name]
58 let split_obj = function
59   | Cic.Constant (name, body, ty, _, attrs)
60   | Cic.Variable (name, body, ty, _, attrs) -> (name, body, ty, attrs)
61   | _ -> assert false
62
63 let canonical_context metano metasenv =
64   try
65     let (_, context, _) = List.find (fun (m, _, _) -> m = metano) metasenv in
66     context
67   with Not_found ->
68     failwith (sprintf "Can't find canonical context for %d" metano)
69
70 let get_context_and_metasenv (currentProof:MatitaTypes.currentProof) =
71   if currentProof#onGoing () then
72     let proof = currentProof#proof in
73     let metasenv = proof#metasenv in
74     let goal = proof#goal in
75     (canonical_context goal metasenv, metasenv)
76   else
77     ([], [])
78
79   (** term AST -> Cic.term. Uses disambiguator and change imperatively the
80   * metasenv as needed *)
81 let disambiguate ~(disambiguator:MatitaTypes.disambiguator) ~currentProof ast =
82   if currentProof#onGoing () then begin
83     let proof = currentProof#proof in
84     let metasenv = proof#metasenv in
85     let goal = proof#goal in
86     let context = canonical_context goal metasenv in
87     let (_, metasenv, term,ugraph) as retval =
88       disambiguator#disambiguateTermAst ~context ~metasenv ast
89     in
90     proof#set_metasenv metasenv;
91     retval
92   end else
93     disambiguator#disambiguateTermAst ast
94
95 class virtual interpreterState = 
96     (* static values, shared by all states inheriting this class *)
97   let loc = ref None in
98   let history = ref [] in
99   fun ~(console: MatitaTypes.console) ->
100   object (self)
101
102       (** eval a toplevel phrase in the current state and return the new state
103       *)
104     method parsePhrase s =
105       match CicTextualParser2.parse_tactical s with
106       | (TacticAst.LocatedTactical (loc', tac)) as tactical ->
107           loc := Some loc';
108           (match tac with (* update interpreter history *)
109           | TacticAst.Command (TacticAst.Qed None) ->
110               history := `Qed :: !history
111           | TacticAst.Command (TacticAst.Theorem (_, Some name, _, None)) ->
112               history := `Theorem name :: !history
113           | TacticAst.Command (TacticAst.Qed _)
114           | TacticAst.Command (TacticAst.Theorem _) -> assert false
115           | _ -> history := `Tactic :: !history);
116           tactical
117       | _ -> assert false
118
119     method virtual evalTactical:
120       (CicAst.term, string) TacticAst.tactical -> outcome
121
122     method evalPhrase s =
123       debug_print (sprintf "evaluating '%s'" s);
124       self#evalTactical (self#parsePhrase (Stream.of_string s))
125
126     method evalAst ast = self#evalTactical ast
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   (** Implements phrases that should be accepted in all states *)
136 class sharedState
137   ~(disambiguator: MatitaTypes.disambiguator)
138   ~(currentProof: MatitaTypes.currentProof)
139   ~(console: MatitaTypes.console)
140   ?(mathViewer: MatitaTypes.mathViewer option)
141   ~(dbd: Mysql.dbd)
142   ()
143 =
144   object (self)
145     inherit interpreterState ~console
146     method evalTactical = function
147       | TacticAst.Command TacticAst.Quit ->
148           currentProof#quit ();
149           assert false  (* dummy answer, useless *)
150       | TacticAst.Command TacticAst.Proof ->
151             (* do nothing, just for compatibility with coq syntax *)
152           New_state Command
153       | TacticAst.Command (TacticAst.Baseuri (Some uri)) ->
154           Lazy.force baseuri := uri;
155           console#echo_message (sprintf "base uri set to \"%s\"" uri);
156           Quiet
157       | TacticAst.Command (TacticAst.Baseuri None) ->
158           console#echo_message (sprintf "base uri is \"%s\""
159             !(Lazy.force baseuri));
160           Quiet
161       | TacticAst.Command (TacticAst.Basedir (Some path)) ->
162           basedir := path;
163           console#echo_message (sprintf "base dir set to \"%s\"" path);
164           Quiet
165       | TacticAst.Command (TacticAst.Basedir None) ->
166           console#echo_message (sprintf "base dir is \"%s\"" !basedir);
167           Quiet
168       | TacticAst.Command (TacticAst.Check term) ->
169           let (_, _, term,ugraph) = 
170             disambiguate ~disambiguator ~currentProof term 
171           in
172           let (context, metasenv) = get_context_and_metasenv currentProof in
173 (* this is the Eval Compute
174           let term = CicReduction.whd context term in
175 *)         
176           let dummyno = CicMkImplicit.new_meta metasenv [] in
177           let ty,ugraph1 = 
178             CicTypeChecker.type_of_aux' metasenv context term ugraph 
179           in
180             (* TASSI: here ugraph1 is unused.... FIXME *)
181           let expr = Cic.Cast (term, ty) in
182           let sequent = (dummyno, context, expr) in
183           (match mathViewer with
184           | None -> ()
185           | Some v -> v#checkTerm sequent metasenv);
186           Quiet
187       | TacticAst.Command (TacticAst.Search_pat (search_kind, pat)) ->
188           let uris =
189             match search_kind with
190             | `Locate -> MetadataQuery.locate ~dbd pat
191             | `Elim -> MetadataQuery.elim ~dbd pat
192             | _ -> assert false
193           in
194           (* TODO ZACK: show URIs to the user *)
195           Quiet
196       | TacticAst.Command (TacticAst.Print `Env) ->
197           let uris = CicEnvironment.list_uri () in
198           console#echo_message "Environment:";
199           List.iter (fun u ->
200             console#echo_message ("  " ^ (UriManager.string_of_uri u))
201           ) uris;
202           Quiet
203       | TacticAst.Command (TacticAst.Print `Coer) ->
204           let uris = CoercGraph.get_coercions_list () in
205           console#echo_message "Coercions:";
206           List.iter (fun (s,t,u) ->
207             console#echo_message ("  " ^ (UriManager.string_of_uri u))
208           ) uris;
209           Quiet
210       | tactical ->
211           raise (Command_error (TacticAstPp.pp_tactical tactical))
212   end
213
214 open Printf
215
216 let pp_indtypes indTypes =
217   List.iter
218     (fun (name, _, typ, constructors) ->
219       printf "%s: %s\n" name (CicPp.ppterm typ);
220       List.iter
221         (fun (name, term) -> printf "\t%s: %s\n" name (CicPp.ppterm term))
222         constructors)
223     indTypes;
224   flush stdout
225
226 let inddef_of_ast params indTypes (disambiguator:MatitaTypes.disambiguator) =
227   let add_pi binders t =
228     List.fold_right
229       (fun (name, ast) acc ->
230         CicAst.Binder (`Forall, (Cic.Name name, Some ast), acc))
231       binders t
232   in
233   let ind_binders =
234     List.map (fun (name, _, typ, _) -> (name, add_pi params typ)) indTypes
235   in
236   let binders = ind_binders @ params in
237   let asts = ref [] in
238   let add_ast ast = asts := ast :: !asts in
239   let paramsno = List.length params in
240   let indbindersno = List.length ind_binders in
241   List.iter
242     (fun (name, _, typ, constructors) ->
243       add_ast (add_pi params typ);
244       List.iter (fun (_, ast) -> add_ast (add_pi binders ast)) constructors)
245     indTypes;
246   let (_, metasenv, terms, ugraph) =
247     disambiguator#disambiguateTermAsts ~metasenv:[] !asts
248   in
249   let terms = ref (List.rev terms) in
250   let get_term () =
251     match !terms with [] -> assert false | hd :: tl -> terms := tl; hd
252   in
253   let uri =
254     match indTypes with
255     | (name, _, _, _) :: _ -> qualify name ^ ".ind"
256     | _ -> assert false
257   in
258   let mutinds =
259     let counter = ref 0 in
260     List.map
261       (fun _ ->
262         incr counter;
263         CicUtil.term_of_uri (sprintf "%s#xpointer(1/%d)" uri !counter))
264       indTypes
265   in
266   let subst_mutinds = List.fold_right CicSubstitution.subst mutinds in
267   let cicIndTypes =
268     List.fold_left
269       (fun acc (name, inductive, typ, constructors) ->
270         let cicTyp = get_term () in
271         let cicConstructors =
272           List.fold_left
273             (fun acc (name, _) ->
274               let typ =
275                 subst_mutinds (CicUtil.strip_prods indbindersno (get_term ()))
276               in
277               (name, typ) :: acc)
278             [] constructors
279         in
280         (name, inductive, cicTyp, List.rev cicConstructors) :: acc)
281       [] indTypes
282   in
283   let cicIndTypes = List.rev cicIndTypes in
284   (UriManager.uri_of_string uri, (cicIndTypes, [], paramsno))
285
286 let 
287  save_object_to_disk uri obj 
288 =
289   (* generate annobj, ids_to_inner_sorts and ids_to_inner_types *)
290   let annobj,_,_,ids_to_inner_sorts,ids_to_inner_types,_,_ =
291     Cic2acic.acic_object_of_cic_object ~eta_fix:false obj
292   in 
293
294   (* prepare XML *)
295   let xml, bodyxml =
296    Cic2Xml.print_object uri ~ids_to_inner_sorts ~ask_dtd_to_the_getter:false
297     annobj 
298   in
299   let xmlinnertypes =
300    Cic2Xml.print_inner_types uri ~ids_to_inner_sorts ~ids_to_inner_types
301     ~ask_dtd_to_the_getter:false
302   in
303   
304   (* prepare URIs and paths *)
305   let innertypesuri = UriManager.innertypesuri_of_uri uri in
306   let bodyuri = UriManager.bodyuri_of_uri uri in
307   let innertypesfilename = Str.replace_first (Str.regexp "^cic:") ""
308         (UriManager.string_of_uri innertypesuri) ^ ".xml" in
309   let innertypespath = !basedir ^ "/" ^ innertypesfilename in
310   let xmlfilename = Str.replace_first (Str.regexp "^cic:") ""
311         (UriManager.string_of_uri uri) ^ ".xml" in
312   let xmlpath = !basedir ^ "/" ^ xmlfilename in
313   let xmlbodyfilename = Str.replace_first (Str.regexp "^cic:") ""
314         (UriManager.string_of_uri uri) ^ ".body.xml" in
315   let xmlbodypath = !basedir ^ "/" ^  xmlbodyfilename in
316   let path_scheme_of path = "file:/" ^ path in
317
318    (* now write to disk *)
319     Xml.pp ~quiet:true xmlinnertypes (Some innertypespath) ;
320     Xml.pp ~quiet:true xml (Some xmlpath) ;
321
322    (* now register to the getter *)
323     Http_getter.register' innertypesuri (path_scheme_of innertypespath); 
324     Http_getter.register' uri (path_scheme_of xmlpath);
325    
326     (* now the optional body, both write and register *)
327     (match bodyxml,bodyuri with
328        None,None -> ()
329      | Some bodyxml,Some bodyuri->
330          Xml.pp ~quiet:true bodyxml (Some xmlbodypath) ;
331          Http_getter.register' bodyuri (path_scheme_of xmlbodypath)
332      | _-> assert false) 
333 ;;
334
335
336
337   (* TODO Zack a lot more to be done here:
338     * - save object to disk in xml format
339     * - register uri to the getter 
340     * - save universe file *)
341 let add_constant_to_world ~(console:MatitaTypes.console)
342   ~dbd ~uri ?body ~ty ?(params = []) ?(attrs = []) ~ugraph ()
343 =
344   let suri = UriManager.string_of_uri uri in
345   if CicEnvironment.in_library uri then
346     error (sprintf "%s constant already defined" suri)
347   else begin
348     let name = UriManager.name_of_uri uri in
349     let obj = Cic.Constant (name, body, ty, params, attrs) in
350     let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
351     CicEnvironment.add_type_checked_term uri (obj, ugraph);
352     MetadataDb.index_constant ~dbd
353       ~owner:(Helm_registry.get "matita.owner") ~uri ~body ~ty;
354     save_object_to_disk uri obj;  
355     console#echo_message (sprintf "%s constant defined" suri)
356   end
357
358 let add_inductive_def_to_world ~(console:MatitaTypes.console)
359   ~dbd ~uri ~indTypes ?(params = []) ?(leftno = 0) ?(attrs = []) ~ugraph ()
360 =
361   let suri = UriManager.string_of_uri uri in
362   if CicEnvironment.in_library uri then
363     error (sprintf "%s inductive type already defined" suri)
364   else begin
365     let name = UriManager.name_of_uri uri in
366     let obj = Cic.InductiveDefinition (indTypes, params, leftno, attrs) in
367     let ugraph = CicUnivUtils.clean_and_fill uri obj ugraph in
368     CicEnvironment.put_inductive_definition uri (obj, ugraph);
369     MetadataDb.index_inductive_def ~dbd
370       ~owner:(Helm_registry.get "matita.owner") ~uri ~types:indTypes;
371     save_object_to_disk uri obj;  
372     console#echo_message (sprintf "%s inductive type defined" suri);
373     let elim sort =
374       try
375         let obj = CicElim.elim_of ~sort uri 0 in
376         let (name, body, ty, attrs) = split_obj obj in
377         let suri = qualify name ^ ".con" in
378         let uri = UriManager.uri_of_string suri in
379           (* TODO Zack: make CicElim returns a universe *)
380         let ugraph = CicUniv.empty_ugraph in
381         add_constant_to_world ~console ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
382 (*
383         console#echo_message
384           (sprintf "%s eliminator (automatically) defined" suri)
385 *)
386       with CicElim.Can_t_eliminate -> ()
387     in
388     List.iter elim [ Cic.Prop; Cic.Set; (Cic.Type (CicUniv.fresh ())) ];
389   end
390
391   (** Implements phrases that should be accepted only in Command state *)
392 class commandState
393   ~(disambiguator: MatitaTypes.disambiguator)
394   ~(currentProof: MatitaTypes.currentProof)
395   ~(console: MatitaTypes.console)
396   ?mathViewer
397   ~(dbd: Mysql.dbd)
398   ()
399 =
400   let shared =
401     new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
402   in
403   object (self)
404     inherit interpreterState ~console
405
406     method evalTactical = function
407       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
408       | TacticAst.Command (TacticAst.Theorem (_, Some name, ast, None)) ->
409           let (_, metasenv, expr,ugraph) = 
410             disambiguator#disambiguateTermAst ast 
411           in
412           let uri = UriManager.uri_of_string (qualify name ^ ".con") in
413           let proof = MatitaProof.proof ~typ:expr ~uri ~metasenv () in
414           currentProof#start proof;
415           New_state Proof
416       | TacticAst.Command
417         (TacticAst.Theorem (_, Some name, type_ast, Some body_ast)) ->
418           let (_, metasenv, type_cic, ugraph) = 
419             disambiguator#disambiguateTermAst type_ast
420           in
421           let (_, metasenv, body_cic, ugraph) = 
422             disambiguator#disambiguateTermAst ~metasenv body_ast
423           in
424           let (body_type, ugraph) =
425             CicTypeChecker.type_of_aux' metasenv [] body_cic ugraph
426           in
427           let uri = UriManager.uri_of_string (qualify name ^ ".con") in
428           let (subst, metasenv, ugraph) =
429             CicUnification.fo_unif metasenv [] body_type type_cic ugraph
430           in
431           let body = CicMetaSubst.apply_subst subst body_cic in
432           let ty = CicMetaSubst.apply_subst subst type_cic in
433           add_constant_to_world ~console ~dbd ~uri ~body ~ty ~ugraph ();
434           Quiet
435       | TacticAst.Command (TacticAst.Inductive (params, indTypes)) ->
436           
437           let (uri, (indTypes, params, leftno)) =
438             inddef_of_ast params indTypes disambiguator
439           in
440           let obj = Cic.InductiveDefinition (indTypes, params, leftno, []) in
441           let ugraph =
442             CicTypeChecker.typecheck_mutual_inductive_defs uri
443               (indTypes, params, leftno) CicUniv.empty_ugraph
444           in
445           add_inductive_def_to_world ~console
446             ~dbd ~uri ~indTypes ~params ~leftno ~ugraph ();
447           Quiet
448       | TacticAst.Command TacticAst.Quit ->
449           currentProof#quit ();
450           New_state Command (* dummy answer, useless *)
451       | TacticAst.Command TacticAst.Proof ->
452             (* do nothing, just for compatibility with coq syntax *)
453           New_state Command
454       | TacticAst.Command (TacticAst.Coercion c_ast) ->
455           let env, metasenv, coercion, ugraph = 
456             disambiguator#disambiguateTermAst c_ast 
457           in
458           let coer_uri,coer_ty =
459             match coercion with 
460             | Cic.Const (uri,_)
461             | Cic.Var (uri,_) ->
462                 let o,_ = 
463                   CicEnvironment.get_obj CicUniv.empty_ugraph uri 
464                 in
465                 (match o with
466                 | Cic.Constant (_,_,ty,_,_)
467                 | Cic.Variable (_,_,ty,_,_) ->
468                     uri,ty
469                 | _ -> assert false)
470             | Cic.MutConstruct (uri,t,c,_) ->
471                 let o,_ = 
472                   CicEnvironment.get_obj CicUniv.empty_ugraph uri 
473                 in
474                 (match o with
475                 | Cic.InductiveDefinition (l,_,_,_) ->
476                     let (_,_,_,cl) = List.nth l t in
477                     let (_,cty) = List.nth cl c in
478                       uri,cty
479                 | _ -> assert false)
480             | _ -> assert false 
481           in
482           (* we have to get the source and the tgt type uri 
483            * in Coq syntax we have already their names, but 
484            * since we don't support Funclass and similar I think
485            * all the coercion should be of the form
486            * (A:?)(B:?)T1->T2
487            * So we should be able to extract them from the coercion type
488            *)
489           let extract_last_two_p ty =
490             let rec aux = function
491               | Cic.Prod( _, src, Cic.Prod (n,t1,t2)) -> aux (Cic.Prod(n,t1,t2))   
492               | Cic.Prod( _, src, tgt) -> src, tgt
493               | _ -> assert false
494             in  
495             aux ty
496           in
497           let rec uri_of_term = function
498             | Cic.Const(u,_) -> u
499             | Cic.MutInd (u, i , _) ->
500                 (* we have to build by hand the #xpointer *)
501                 let base = UriManager.string_of_uri u in
502                 let xp = "#xpointer(1/" ^ (string_of_int (i+1)) ^ ")" in
503                   UriManager.uri_of_string (base ^ xp)
504             | Cic.Appl (he::_) -> uri_of_term he
505             | t -> 
506                 prerr_endline ("Fallisco a estrarre la uri di " ^ 
507                   (CicPp.ppterm t));
508                 assert false 
509           in
510           let ty_src,ty_tgt = extract_last_two_p coer_ty in
511           let src_uri = uri_of_term ty_src in
512           let tgt_uri = uri_of_term ty_tgt in
513           let coercions_to_add = 
514             CoercGraph.close_coercion_graph src_uri tgt_uri coer_uri
515           in
516           (* FIXME: we should chek it this object can be a coercion 
517            * maybe add the check to extract_last_two_p
518            *)
519           console#echo_message (sprintf "Coercion %s"
520             (UriManager.string_of_uri coer_uri));
521           List.iter (fun (uri,obj,ugraph) -> 
522           (*  
523             console#echo_message 
524              (sprintf "Coercion (automatic) %s" 
525                (UriManager.string_of_uri uri));
526           *)
527             let (name, body, ty, attrs) = split_obj obj in
528             add_constant_to_world ~console 
529               ~dbd ~uri ?body ~ty ~attrs ~ugraph ();
530           ) coercions_to_add;
531           Quiet
532       | tactical -> shared#evalTactical tactical
533   end
534
535   (** create a ProofEngineTypes.mk_fresh_name_type function which uses given
536   * names as long as they are available, then it fallbacks to name generation
537   * using FreshNamesGenerator module *)
538 let namer_of names =
539   let len = List.length names in
540   let count = ref 0 in
541   fun metasenv context name ~typ ->
542     if !count < len then begin
543       let name = Cic.Name (List.nth names !count) in
544       incr count;
545       name
546     end else
547       FreshNamesGenerator.mk_fresh_name ~subst:[] metasenv context name ~typ
548
549   (** Implements phrases that should be accepted only in Proof state, basically
550   * tacticals *)
551 class proofState
552   ~(disambiguator: MatitaTypes.disambiguator)
553   ~(currentProof: MatitaTypes.currentProof)
554   ~(console: MatitaTypes.console)
555   ?mathViewer
556   ~(dbd: Mysql.dbd)
557   ()
558 =
559   let disambiguate ast =
560     let (_, _, term, _) = disambiguate ~disambiguator ~currentProof ast in
561     term
562   in
563     (** tactic AST -> ProofEngineTypes.tactic *)
564   let rec lookup_tactic = function
565     | TacticAst.LocatedTactic (_, tactic) -> lookup_tactic tactic
566     | TacticAst.Intros (_, names) ->  (* TODO Zack implement intros length *)
567         PrimitiveTactics.intros_tac ~mk_fresh_name_callback:(namer_of names) ()
568     | TacticAst.Reflexivity -> Tactics.reflexivity
569     | TacticAst.Assumption -> Tactics.assumption
570     | TacticAst.Contradiction -> Tactics.contradiction
571     | TacticAst.Exists -> Tactics.exists
572     | TacticAst.Fourier -> Tactics.fourier
573     | TacticAst.Left -> Tactics.left
574     | TacticAst.Right -> Tactics.right
575     | TacticAst.Ring -> Tactics.ring
576     | TacticAst.Split -> Tactics.split
577     | TacticAst.Symmetry -> Tactics.symmetry
578     | TacticAst.Transitivity term -> Tactics.transitivity (disambiguate term)
579     | TacticAst.Apply term -> Tactics.apply (disambiguate term)
580     | TacticAst.Absurd term -> Tactics.absurd (disambiguate term)
581     | TacticAst.Exact term -> Tactics.exact (disambiguate term)
582     | TacticAst.Cut term -> Tactics.cut (disambiguate term)
583     | TacticAst.Elim (term, _) -> (* TODO Zack implement "using" argument *)
584         Tactics.elim_intros_simpl (disambiguate term)
585     | TacticAst.ElimType term -> Tactics.elim_type (disambiguate term)
586     | TacticAst.Replace (what, with_what) ->
587         Tactics.replace ~what:(disambiguate what)
588           ~with_what:(disambiguate with_what)
589     | TacticAst.Auto -> Tactics.auto_new ~dbd
590   (*
591     (* TODO Zack a lot more of tactics to be implemented here ... *)
592     | TacticAst.Change of 'term * 'term * 'ident option
593     | TacticAst.Change_pattern of 'term pattern * 'term * 'ident option
594     | TacticAst.Decompose of 'ident * 'ident list
595     | TacticAst.Discriminate of 'ident
596     | TacticAst.Fold of reduction_kind * 'term
597     | TacticAst.Injection of 'ident
598     | TacticAst.LetIn of 'term * 'ident
599     | TacticAst.Reduce of reduction_kind * 'term pattern * 'ident option
600     | TacticAst.Replace_pattern of 'term pattern * 'term
601     | TacticAst.Rewrite of direction * 'term * 'ident option
602   *)
603     | _ ->
604         MatitaTypes.not_implemented "some tactic"
605   in
606   let shared =
607     new sharedState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
608   in
609   object (self)
610     inherit interpreterState ~console
611
612     method evalTactical = function
613       | TacticAst.LocatedTactical (_, tactical) -> self#evalTactical tactical
614       | TacticAst.Command TacticAst.Abort ->
615           currentProof#abort ();
616           New_state Command
617       | TacticAst.Command (TacticAst.Undo steps) ->
618           currentProof#proof#undo ?steps ();
619           New_state Proof
620       | TacticAst.Command (TacticAst.Redo steps) ->
621           currentProof#proof#redo ?steps ();
622           New_state Proof
623       | TacticAst.Command (TacticAst.Qed None) ->
624           if not (currentProof#onGoing ()) then assert false;
625           let proof = currentProof#proof in
626           let (uri, metasenv, bo, ty) = proof#proof in
627           let uri = MatitaTypes.unopt_uri uri in
628           let suri = UriManager.string_of_uri uri in
629             (* TODO Zack this function probably should not simply fail with
630             * Failure, but rather raise some more meaningful exception *)
631           if metasenv <> [] then failwith "Proof not completed";
632           let proved_ty,ugraph = 
633             CicTypeChecker.type_of_aux' [] [] bo CicUniv.empty_ugraph
634           in
635           let b,ugraph = 
636             CicReduction.are_convertible [] proved_ty ty ugraph 
637           in
638           if not b then failwith "Wrong proof";
639           add_constant_to_world ~console ~dbd ~uri ~body:bo ~ty ~ugraph ();
640           currentProof#abort ();
641           (match mathViewer with None -> () | Some v -> v#unload ());
642           console#echo_message (sprintf "%s defined" suri);
643           New_state Command
644       | TacticAst.Seq tacticals ->
645           (* TODO Zack check for proof completed at each step? *)
646           List.iter (fun t -> ignore (self#evalTactical t)) tacticals;
647           New_state Proof
648       | TacticAst.Tactic tactic_phrase ->
649           let tactic = lookup_tactic tactic_phrase in
650           currentProof#proof#apply_tactic tactic;
651           New_state Proof
652       | tactical -> shared#evalTactical tactical
653   end
654
655 class interpreter
656   ~(disambiguator: MatitaTypes.disambiguator)
657   ~(currentProof: MatitaTypes.currentProof)
658   ~(console: MatitaTypes.console)
659   ?mathViewer
660   ~(dbd: Mysql.dbd)
661   ()
662 =
663   let commandState =
664     new commandState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
665   in
666   let proofState =
667     new proofState ~disambiguator ~currentProof ~console ?mathViewer ~dbd ()
668   in
669   object (self)
670     val mutable state = commandState
671
672     method reset = state <- commandState
673
674     method endOffset = state#endOffset
675
676     method private updateState = function
677       | New_state Command -> (state <- commandState)
678       | New_state Proof -> (state <- proofState)
679       | _ -> ()
680
681     method private eval f =
682       let ok () = (* console#clear (); *) (true, true) in
683       match console#wrap_exn f with
684       | Some (New_state Command) -> (state <- commandState); ok ()
685       | Some (New_state Proof) -> (state <- proofState); ok ()
686       | Some (Echo msg) -> console#echo_message msg; (true, false)
687       | Some Quiet -> ok ()
688       | None -> (false, false)
689
690     method evalPhrase s = self#eval (fun () -> state#evalPhrase s)
691     method evalAst ast = self#eval (fun () -> state#evalAst ast)
692   end
693