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