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