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