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