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