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